blob: e85096021b0b6960bf9c87750c8e719f57abbb91 [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"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000018#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000019#include "clang/AST/ExternalASTSource.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/RecordLayout.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000021#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000023#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000024#include "llvm/Support/MathExtras.h"
Chris Lattner557c5b12009-03-28 04:27:18 +000025#include "llvm/Support/MemoryBuffer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27
28enum FloatingRank {
29 FloatRank, DoubleRank, LongDoubleRank
30};
31
Chris Lattner61710852008-10-05 17:34:18 +000032ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
33 TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000034 IdentifierTable &idents, SelectorTable &sels,
Douglas Gregor2deaea32009-04-22 18:49:13 +000035 bool FreeMem, unsigned size_reserve,
36 bool InitializeBuiltins) :
Douglas Gregorab452ba2009-03-26 23:50:42 +000037 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
38 ObjCFastEnumerationStateTypeDecl(0), SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor2cf26342009-04-09 22:27:44 +000039 FreeMemory(FreeMem), Target(t), Idents(idents), Selectors(sels),
40 ExternalSource(0) {
Daniel Dunbare91593e2008-08-11 04:54:23 +000041 if (size_reserve > 0) Types.reserve(size_reserve);
42 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000043 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregor7a9cbed2009-04-26 03:57:37 +000044 BuiltinInfo.InitializeTargetBuiltins(Target);
Douglas Gregor2deaea32009-04-22 18:49:13 +000045 if (InitializeBuiltins)
46 this->InitializeBuiltins(idents);
Daniel Dunbare91593e2008-08-11 04:54:23 +000047}
48
Reid Spencer5f016e22007-07-11 17:01:13 +000049ASTContext::~ASTContext() {
50 // Deallocate all the types.
51 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000052 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000053 Types.pop_back();
54 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000055
Nuno Lopesb74668e2008-12-17 22:30:25 +000056 {
57 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
58 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
59 while (I != E) {
60 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
61 delete R;
62 }
63 }
64
65 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000066 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
67 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000068 while (I != E) {
69 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
70 delete R;
71 }
72 }
73
Douglas Gregorab452ba2009-03-26 23:50:42 +000074 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000075 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
76 NNS = NestedNameSpecifiers.begin(),
77 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregore7dcd782009-03-27 23:25:45 +000078 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000079 /* Increment in loop */)
80 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000081
82 if (GlobalNestedNameSpecifier)
83 GlobalNestedNameSpecifier->Destroy(*this);
84
Eli Friedmanb26153c2008-05-27 03:08:09 +000085 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000086}
87
Douglas Gregor2deaea32009-04-22 18:49:13 +000088void ASTContext::InitializeBuiltins(IdentifierTable &idents) {
Douglas Gregor2deaea32009-04-22 18:49:13 +000089 BuiltinInfo.InitializeBuiltins(idents, LangOpts.NoBuiltin);
90}
91
Douglas Gregor2cf26342009-04-09 22:27:44 +000092void
93ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
94 ExternalSource.reset(Source.take());
95}
96
Reid Spencer5f016e22007-07-11 17:01:13 +000097void ASTContext::PrintStats() const {
98 fprintf(stderr, "*** AST Context Stats:\n");
99 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000100
Douglas Gregordbe833d2009-05-26 14:40:08 +0000101 unsigned counts[] = {
102#define TYPE(Name, Parent) 0,
103#define ABSTRACT_TYPE(Name, Parent)
104#include "clang/AST/TypeNodes.def"
105 0 // Extra
106 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000107
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
109 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000110 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 }
112
Douglas Gregordbe833d2009-05-26 14:40:08 +0000113 unsigned Idx = 0;
114 unsigned TotalBytes = 0;
115#define TYPE(Name, Parent) \
116 if (counts[Idx]) \
117 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
118 TotalBytes += counts[Idx] * sizeof(Name##Type); \
119 ++Idx;
120#define ABSTRACT_TYPE(Name, Parent)
121#include "clang/AST/TypeNodes.def"
122
123 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000124
125 if (ExternalSource.get()) {
126 fprintf(stderr, "\n");
127 ExternalSource->PrintStats();
128 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000129}
130
131
132void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Narofff83820b2009-01-27 22:08:43 +0000133 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000134}
135
Reid Spencer5f016e22007-07-11 17:01:13 +0000136void ASTContext::InitBuiltinTypes() {
137 assert(VoidTy.isNull() && "Context reinitialized?");
138
139 // C99 6.2.5p19.
140 InitBuiltinType(VoidTy, BuiltinType::Void);
141
142 // C99 6.2.5p2.
143 InitBuiltinType(BoolTy, BuiltinType::Bool);
144 // C99 6.2.5p3.
Chris Lattner98be4942008-03-05 18:54:05 +0000145 if (Target.isCharSigned())
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 InitBuiltinType(CharTy, BuiltinType::Char_S);
147 else
148 InitBuiltinType(CharTy, BuiltinType::Char_U);
149 // C99 6.2.5p4.
150 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
151 InitBuiltinType(ShortTy, BuiltinType::Short);
152 InitBuiltinType(IntTy, BuiltinType::Int);
153 InitBuiltinType(LongTy, BuiltinType::Long);
154 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
155
156 // C99 6.2.5p6.
157 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
158 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
159 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
160 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
161 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
162
163 // C99 6.2.5p10.
164 InitBuiltinType(FloatTy, BuiltinType::Float);
165 InitBuiltinType(DoubleTy, BuiltinType::Double);
166 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000167
Chris Lattner2df9ced2009-04-30 02:43:43 +0000168 // GNU extension, 128-bit integers.
169 InitBuiltinType(Int128Ty, BuiltinType::Int128);
170 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
171
Chris Lattner3a250322009-02-26 23:43:47 +0000172 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
173 InitBuiltinType(WCharTy, BuiltinType::WChar);
174 else // C99
175 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000176
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000177 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000178 InitBuiltinType(OverloadTy, BuiltinType::Overload);
179
180 // Placeholder type for type-dependent expressions whose type is
181 // completely unknown. No code should ever check a type against
182 // DependentTy and users should never see it; however, it is here to
183 // help diagnose failures to properly check for type-dependent
184 // expressions.
185 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000186
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 // C99 6.2.5p11.
188 FloatComplexTy = getComplexType(FloatTy);
189 DoubleComplexTy = getComplexType(DoubleTy);
190 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000191
Steve Naroff7e219e42007-10-15 14:41:52 +0000192 BuiltinVaListType = QualType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000193 ObjCIdType = QualType();
Steve Naroff7e219e42007-10-15 14:41:52 +0000194 IdStructType = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000195 ObjCClassType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000196 ClassStructType = 0;
197
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000198 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000199
200 // void * type
201 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000202
203 // nullptr type (C++0x 2.14.7)
204 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000205}
206
Chris Lattner464175b2007-07-18 17:52:12 +0000207//===----------------------------------------------------------------------===//
208// Type Sizing and Analysis
209//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000210
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000211/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
212/// scalar floating point type.
213const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
214 const BuiltinType *BT = T->getAsBuiltinType();
215 assert(BT && "Not a floating point type!");
216 switch (BT->getKind()) {
217 default: assert(0 && "Not a floating point type!");
218 case BuiltinType::Float: return Target.getFloatFormat();
219 case BuiltinType::Double: return Target.getDoubleFormat();
220 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
221 }
222}
223
Chris Lattneraf707ab2009-01-24 21:53:27 +0000224/// getDeclAlign - Return a conservative estimate of the alignment of the
225/// specified decl. Note that bitfields do not have a valid alignment, so
226/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000227unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000228 unsigned Align = Target.getCharWidth();
229
230 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
231 Align = std::max(Align, AA->getAlignment());
232
Chris Lattneraf707ab2009-01-24 21:53:27 +0000233 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
234 QualType T = VD->getType();
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000235 if (const ReferenceType* RT = T->getAsReferenceType()) {
236 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000237 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000238 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
239 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000240 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
241 T = cast<ArrayType>(T)->getElementType();
242
243 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
244 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000245 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000246
247 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000248}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000249
Chris Lattnera7674d82007-07-13 22:13:22 +0000250/// getTypeSize - Return the size of the specified type, in bits. This method
251/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000252std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000253ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000254 uint64_t Width=0;
255 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000256 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000257#define TYPE(Class, Base)
258#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000259#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000260#define DEPENDENT_TYPE(Class, Base) case Type::Class:
261#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000262 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000263 break;
264
Chris Lattner692233e2007-07-13 22:27:08 +0000265 case Type::FunctionNoProto:
266 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000267 // GCC extension: alignof(function) = 32 bits
268 Width = 0;
269 Align = 32;
270 break;
271
Douglas Gregor72564e72009-02-26 23:50:07 +0000272 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000273 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000274 Width = 0;
275 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
276 break;
277
Steve Narofffb22d962007-08-30 01:06:46 +0000278 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000279 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000280
Chris Lattner98be4942008-03-05 18:54:05 +0000281 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000282 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000283 Align = EltInfo.second;
284 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000285 }
Nate Begeman213541a2008-04-18 23:10:10 +0000286 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000287 case Type::Vector: {
288 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000289 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000290 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000291 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000292 // If the alignment is not a power of 2, round up to the next power of 2.
293 // This happens for non-power-of-2 length vectors.
294 // FIXME: this should probably be a target property.
295 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000296 break;
297 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000298
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000299 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000300 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000301 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000302 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000303 // GCC extension: alignof(void) = 8 bits.
304 Width = 0;
305 Align = 8;
306 break;
307
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000308 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000309 Width = Target.getBoolWidth();
310 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000311 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000312 case BuiltinType::Char_S:
313 case BuiltinType::Char_U:
314 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000315 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000316 Width = Target.getCharWidth();
317 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000318 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000319 case BuiltinType::WChar:
320 Width = Target.getWCharWidth();
321 Align = Target.getWCharAlign();
322 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000323 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000324 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000325 Width = Target.getShortWidth();
326 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000327 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000328 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000329 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000330 Width = Target.getIntWidth();
331 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000332 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000333 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000334 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000335 Width = Target.getLongWidth();
336 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000337 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000338 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000339 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000340 Width = Target.getLongLongWidth();
341 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000342 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000343 case BuiltinType::Int128:
344 case BuiltinType::UInt128:
345 Width = 128;
346 Align = 128; // int128_t is 128-bit aligned on all targets.
347 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000348 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000349 Width = Target.getFloatWidth();
350 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000351 break;
352 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000353 Width = Target.getDoubleWidth();
354 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000355 break;
356 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000357 Width = Target.getLongDoubleWidth();
358 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000359 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000360 case BuiltinType::NullPtr:
361 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
362 Align = Target.getPointerAlign(0); // == sizeof(void*)
Chris Lattnera7674d82007-07-13 22:13:22 +0000363 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000364 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000365 case Type::FixedWidthInt:
366 // FIXME: This isn't precisely correct; the width/alignment should depend
367 // on the available types for the target
368 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000369 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000370 Align = Width;
371 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000372 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000373 // FIXME: Pointers into different addr spaces could have different sizes and
374 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000375 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000376 case Type::ObjCQualifiedId:
Douglas Gregor72564e72009-02-26 23:50:07 +0000377 case Type::ObjCQualifiedInterface:
Chris Lattner5426bf62008-04-07 07:01:58 +0000378 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000379 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000380 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000381 case Type::BlockPointer: {
382 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
383 Width = Target.getPointerWidth(AS);
384 Align = Target.getPointerAlign(AS);
385 break;
386 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000387 case Type::Pointer: {
388 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000389 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000390 Align = Target.getPointerAlign(AS);
391 break;
392 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000393 case Type::LValueReference:
394 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000395 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000396 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000397 // FIXME: This is wrong for struct layout: a reference in a struct has
398 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000399 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000400 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000401 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
402 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
403 // If we ever want to support other ABIs this needs to be abstracted.
404
Sebastian Redlf30208a2009-01-24 21:16:55 +0000405 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000406 std::pair<uint64_t, unsigned> PtrDiffInfo =
407 getTypeInfo(getPointerDiffType());
408 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000409 if (Pointee->isFunctionType())
410 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000411 Align = PtrDiffInfo.second;
412 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000413 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000414 case Type::Complex: {
415 // Complex types have the same alignment as their elements, but twice the
416 // size.
417 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000418 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000419 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000420 Align = EltInfo.second;
421 break;
422 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000423 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000424 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000425 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
426 Width = Layout.getSize();
427 Align = Layout.getAlignment();
428 break;
429 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000430 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000431 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000432 const TagType *TT = cast<TagType>(T);
433
434 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000435 Width = 1;
436 Align = 1;
437 break;
438 }
439
Daniel Dunbar1d751182008-11-08 05:48:37 +0000440 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000441 return getTypeInfo(ET->getDecl()->getIntegerType());
442
Daniel Dunbar1d751182008-11-08 05:48:37 +0000443 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000444 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
445 Width = Layout.getSize();
446 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000447 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000448 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000449
Douglas Gregor18857642009-04-30 17:32:17 +0000450 case Type::Typedef: {
451 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
452 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
453 Align = Aligned->getAlignment();
454 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
455 } else
456 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000457 break;
Chris Lattner71763312008-04-06 22:05:18 +0000458 }
Douglas Gregor18857642009-04-30 17:32:17 +0000459
460 case Type::TypeOfExpr:
461 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
462 .getTypePtr());
463
464 case Type::TypeOf:
465 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
466
467 case Type::QualifiedName:
468 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
469
470 case Type::TemplateSpecialization:
471 assert(getCanonicalType(T) != T &&
472 "Cannot request the size of a dependent type");
473 // FIXME: this is likely to be wrong once we support template
474 // aliases, since a template alias could refer to a typedef that
475 // has an __aligned__ attribute on it.
476 return getTypeInfo(getCanonicalType(T));
477 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000478
Chris Lattner464175b2007-07-18 17:52:12 +0000479 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000480 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000481}
482
Chris Lattner34ebde42009-01-27 18:08:34 +0000483/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
484/// type for the current target in bits. This can be different than the ABI
485/// alignment in cases where it is beneficial for performance to overalign
486/// a data type.
487unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
488 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000489
490 // Double and long long should be naturally aligned if possible.
491 if (const ComplexType* CT = T->getAsComplexType())
492 T = CT->getElementType().getTypePtr();
493 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
494 T->isSpecificBuiltinType(BuiltinType::LongLong))
495 return std::max(ABIAlign, (unsigned)getTypeSize(T));
496
Chris Lattner34ebde42009-01-27 18:08:34 +0000497 return ABIAlign;
498}
499
500
Devang Patel8b277042008-06-04 21:22:16 +0000501/// LayoutField - Field layout.
502void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000503 bool IsUnion, unsigned StructPacking,
Devang Patel8b277042008-06-04 21:22:16 +0000504 ASTContext &Context) {
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000505 unsigned FieldPacking = StructPacking;
Devang Patel8b277042008-06-04 21:22:16 +0000506 uint64_t FieldOffset = IsUnion ? 0 : Size;
507 uint64_t FieldSize;
508 unsigned FieldAlign;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000509
510 // FIXME: Should this override struct packing? Probably we want to
511 // take the minimum?
512 if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
513 FieldPacking = PA->getAlignment();
Devang Patel8b277042008-06-04 21:22:16 +0000514
515 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
516 // TODO: Need to check this algorithm on other targets!
517 // (tested on Linux-X86)
Eli Friedman9a901bb2009-04-26 19:19:15 +0000518 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
Devang Patel8b277042008-06-04 21:22:16 +0000519
520 std::pair<uint64_t, unsigned> FieldInfo =
521 Context.getTypeInfo(FD->getType());
522 uint64_t TypeSize = FieldInfo.first;
523
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000524 // Determine the alignment of this bitfield. The packing
525 // attributes define a maximum and the alignment attribute defines
526 // a minimum.
527 // FIXME: What is the right behavior when the specified alignment
528 // is smaller than the specified packing?
Devang Patel8b277042008-06-04 21:22:16 +0000529 FieldAlign = FieldInfo.second;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000530 if (FieldPacking)
531 FieldAlign = std::min(FieldAlign, FieldPacking);
Devang Patel8b277042008-06-04 21:22:16 +0000532 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
533 FieldAlign = std::max(FieldAlign, AA->getAlignment());
534
535 // Check if we need to add padding to give the field the correct
536 // alignment.
537 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
538 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
539
540 // Padding members don't affect overall alignment
541 if (!FD->getIdentifier())
542 FieldAlign = 1;
543 } else {
Chris Lattner8389eab2008-08-09 21:35:13 +0000544 if (FD->getType()->isIncompleteArrayType()) {
545 // This is a flexible array member; we can't directly
Devang Patel8b277042008-06-04 21:22:16 +0000546 // query getTypeInfo about these, so we figure it out here.
547 // Flexible array members don't have any size, but they
548 // have to be aligned appropriately for their element type.
549 FieldSize = 0;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000550 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patel8b277042008-06-04 21:22:16 +0000551 FieldAlign = Context.getTypeAlign(ATy->getElementType());
Anders Carlsson2f1169f2009-04-10 05:31:15 +0000552 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
553 unsigned AS = RT->getPointeeType().getAddressSpace();
554 FieldSize = Context.Target.getPointerWidth(AS);
555 FieldAlign = Context.Target.getPointerAlign(AS);
Devang Patel8b277042008-06-04 21:22:16 +0000556 } else {
557 std::pair<uint64_t, unsigned> FieldInfo =
558 Context.getTypeInfo(FD->getType());
559 FieldSize = FieldInfo.first;
560 FieldAlign = FieldInfo.second;
561 }
562
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000563 // Determine the alignment of this bitfield. The packing
564 // attributes define a maximum and the alignment attribute defines
565 // a minimum. Additionally, the packing alignment must be at least
566 // a byte for non-bitfields.
567 //
568 // FIXME: What is the right behavior when the specified alignment
569 // is smaller than the specified packing?
570 if (FieldPacking)
571 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Devang Patel8b277042008-06-04 21:22:16 +0000572 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
573 FieldAlign = std::max(FieldAlign, AA->getAlignment());
574
575 // Round up the current record size to the field's alignment boundary.
576 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
577 }
578
579 // Place this field at the current location.
580 FieldOffsets[FieldNo] = FieldOffset;
581
582 // Reserve space for this field.
583 if (IsUnion) {
584 Size = std::max(Size, FieldSize);
585 } else {
586 Size = FieldOffset + FieldSize;
587 }
588
Daniel Dunbard6884a02009-05-04 05:16:21 +0000589 // Remember the next available offset.
590 NextOffset = Size;
591
Devang Patel8b277042008-06-04 21:22:16 +0000592 // Remember max struct/class alignment.
593 Alignment = std::max(Alignment, FieldAlign);
594}
595
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000596static void CollectLocalObjCIvars(ASTContext *Ctx,
597 const ObjCInterfaceDecl *OI,
598 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000599 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
600 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000601 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000602 if (!IVDecl->isInvalidDecl())
603 Fields.push_back(cast<FieldDecl>(IVDecl));
604 }
605}
606
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000607void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
608 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
609 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
610 CollectObjCIvars(SuperClass, Fields);
611 CollectLocalObjCIvars(this, OI, Fields);
612}
613
Fariborz Jahanian98200742009-05-12 18:14:29 +0000614void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
615 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
616 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
617 E = PD->prop_end(*this); I != E; ++I)
618 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
619 Ivars.push_back(Ivar);
620
621 // Also look into nested protocols.
622 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
623 E = PD->protocol_end(); P != E; ++P)
624 CollectProtocolSynthesizedIvars(*P, Ivars);
625}
626
627/// CollectSynthesizedIvars -
628/// This routine collect synthesized ivars for the designated class.
629///
630void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
631 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
632 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
633 E = OI->prop_end(*this); I != E; ++I) {
634 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
635 Ivars.push_back(Ivar);
636 }
637 // Also look into interface's protocol list for properties declared
638 // in the protocol and whose ivars are synthesized.
639 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
640 PE = OI->protocol_end(); P != PE; ++P) {
641 ObjCProtocolDecl *PD = (*P);
642 CollectProtocolSynthesizedIvars(PD, Ivars);
643 }
644}
645
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000646/// getInterfaceLayoutImpl - Get or compute information about the
647/// layout of the given interface.
648///
649/// \param Impl - If given, also include the layout of the interface's
650/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000651const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000652ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
653 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000654 assert(!D->isForwardDecl() && "Invalid interface decl!");
655
Devang Patel44a3dde2008-06-04 21:54:36 +0000656 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000657 ObjCContainerDecl *Key =
658 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
659 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
660 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000661
Daniel Dunbar453addb2009-05-03 11:16:44 +0000662 unsigned FieldCount = D->ivar_size();
663 // Add in synthesized ivar count if laying out an implementation.
664 if (Impl) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000665 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
666 CollectSynthesizedIvars(D, Ivars);
667 FieldCount += Ivars.size();
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000668 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000669 // entry. Note we can't cache this because we simply free all
670 // entries later; however we shouldn't look up implementations
671 // frequently.
672 if (FieldCount == D->ivar_size())
673 return getObjCLayout(D, 0);
674 }
675
Devang Patel6a5a34c2008-06-06 02:14:01 +0000676 ASTRecordLayout *NewEntry = NULL;
Devang Patel6a5a34c2008-06-06 02:14:01 +0000677 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Devang Patel6a5a34c2008-06-06 02:14:01 +0000678 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
679 unsigned Alignment = SL.getAlignment();
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000680
Daniel Dunbar913af352009-05-07 21:58:26 +0000681 // We start laying out ivars not at the end of the superclass
682 // structure, but at the next byte following the last field.
683 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
Daniel Dunbard6884a02009-05-04 05:16:21 +0000684
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000685 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000686 NewEntry->InitializeLayout(FieldCount);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000687 } else {
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000688 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
Devang Patel6a5a34c2008-06-06 02:14:01 +0000689 NewEntry->InitializeLayout(FieldCount);
690 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000691
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000692 unsigned StructPacking = 0;
693 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
694 StructPacking = PA->getAlignment();
Devang Patel44a3dde2008-06-04 21:54:36 +0000695
696 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
697 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
698 AA->getAlignment()));
699
700 // Layout each ivar sequentially.
701 unsigned i = 0;
702 for (ObjCInterfaceDecl::ivar_iterator IVI = D->ivar_begin(),
703 IVE = D->ivar_end(); IVI != IVE; ++IVI) {
704 const ObjCIvarDecl* Ivar = (*IVI);
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000705 NewEntry->LayoutField(Ivar, i++, false, StructPacking, *this);
Devang Patel44a3dde2008-06-04 21:54:36 +0000706 }
Daniel Dunbar453addb2009-05-03 11:16:44 +0000707 // And synthesized ivars, if this is an implementation.
708 if (Impl) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000709 // FIXME. Do we need to colltect twice?
710 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
711 CollectSynthesizedIvars(D, Ivars);
712 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
713 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
Fariborz Jahanian18191882009-03-31 18:11:23 +0000714 }
Fariborz Jahanian99eee362009-04-01 19:37:34 +0000715
Devang Patel44a3dde2008-06-04 21:54:36 +0000716 // Finally, round the size of the total struct up to the alignment of the
717 // struct itself.
718 NewEntry->FinalizeLayout();
719 return *NewEntry;
720}
721
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000722const ASTRecordLayout &
723ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
724 return getObjCLayout(D, 0);
725}
726
727const ASTRecordLayout &
728ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
729 return getObjCLayout(D->getClassInterface(), D);
730}
731
Devang Patel88a981b2007-11-01 19:11:01 +0000732/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000733/// specified record (struct/union/class), which indicates its size and field
734/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000735const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000736 D = D->getDefinition(*this);
737 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000738
Chris Lattner464175b2007-07-18 17:52:12 +0000739 // Look up this layout, if already laid out, return what we have.
Devang Patel88a981b2007-11-01 19:11:01 +0000740 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000741 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000742
Devang Patel88a981b2007-11-01 19:11:01 +0000743 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
744 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
745 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner464175b2007-07-18 17:52:12 +0000746 Entry = NewEntry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000747
Douglas Gregore267ff32008-12-11 20:41:00 +0000748 // FIXME: Avoid linear walk through the fields, if possible.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000749 NewEntry->InitializeLayout(std::distance(D->field_begin(*this),
750 D->field_end(*this)));
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000751 bool IsUnion = D->isUnion();
Chris Lattner464175b2007-07-18 17:52:12 +0000752
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000753 unsigned StructPacking = 0;
754 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
755 StructPacking = PA->getAlignment();
756
Eli Friedman4bd998b2008-05-30 09:31:38 +0000757 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000758 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
759 AA->getAlignment()));
Anders Carlsson8af226a2008-02-18 07:13:09 +0000760
Eli Friedman4bd998b2008-05-30 09:31:38 +0000761 // Layout each field, for now, just sequentially, respecting alignment. In
762 // the future, this will need to be tweakable by targets.
Douglas Gregor44b43212008-12-11 16:49:14 +0000763 unsigned FieldIdx = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000764 for (RecordDecl::field_iterator Field = D->field_begin(*this),
765 FieldEnd = D->field_end(*this);
Douglas Gregor44b43212008-12-11 16:49:14 +0000766 Field != FieldEnd; (void)++Field, ++FieldIdx)
767 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman4bd998b2008-05-30 09:31:38 +0000768
769 // Finally, round the size of the total struct up to the alignment of the
770 // struct itself.
Devang Patel8b277042008-06-04 21:22:16 +0000771 NewEntry->FinalizeLayout();
Chris Lattner5d2a6302007-07-18 18:26:58 +0000772 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +0000773}
774
Chris Lattnera7674d82007-07-13 22:13:22 +0000775//===----------------------------------------------------------------------===//
776// Type creation/memoization methods
777//===----------------------------------------------------------------------===//
778
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000779QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000780 QualType CanT = getCanonicalType(T);
781 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +0000782 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000783
784 // If we are composing extended qualifiers together, merge together into one
785 // ExtQualType node.
786 unsigned CVRQuals = T.getCVRQualifiers();
787 QualType::GCAttrTypes GCAttr = QualType::GCNone;
788 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +0000789
Chris Lattnerb7d25532009-02-18 22:53:11 +0000790 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
791 // If this type already has an address space specified, it cannot get
792 // another one.
793 assert(EQT->getAddressSpace() == 0 &&
794 "Type cannot be in multiple addr spaces!");
795 GCAttr = EQT->getObjCGCAttr();
796 TypeNode = EQT->getBaseType();
797 }
Chris Lattnerf46699c2008-02-20 20:55:12 +0000798
Chris Lattnerb7d25532009-02-18 22:53:11 +0000799 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +0000800 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000801 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +0000802 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000803 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000804 return QualType(EXTQy, CVRQuals);
805
Christopher Lambebb97e92008-02-04 02:31:56 +0000806 // If the base type isn't canonical, this won't be a canonical type either,
807 // so fill in the canonical type field.
808 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000809 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000810 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +0000811
Chris Lattnerb7d25532009-02-18 22:53:11 +0000812 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000813 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000814 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +0000815 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000816 ExtQualType *New =
817 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000818 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +0000819 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000820 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +0000821}
822
Chris Lattnerb7d25532009-02-18 22:53:11 +0000823QualType ASTContext::getObjCGCQualType(QualType T,
824 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000825 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000826 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000827 return T;
828
Chris Lattnerb7d25532009-02-18 22:53:11 +0000829 // If we are composing extended qualifiers together, merge together into one
830 // ExtQualType node.
831 unsigned CVRQuals = T.getCVRQualifiers();
832 Type *TypeNode = T.getTypePtr();
833 unsigned AddressSpace = 0;
834
835 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
836 // If this type already has an address space specified, it cannot get
837 // another one.
838 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
839 "Type cannot be in multiple addr spaces!");
840 AddressSpace = EQT->getAddressSpace();
841 TypeNode = EQT->getBaseType();
842 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000843
844 // Check if we've already instantiated an gc qual'd type of this type.
845 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000846 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000847 void *InsertPos = 0;
848 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000849 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000850
851 // If the base type isn't canonical, this won't be a canonical type either,
852 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +0000853 // FIXME: Isn't this also not canonical if the base type is a array
854 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000855 QualType Canonical;
856 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +0000857 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000858
Chris Lattnerb7d25532009-02-18 22:53:11 +0000859 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000860 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
861 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
862 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000863 ExtQualType *New =
864 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000865 ExtQualTypes.InsertNode(New, InsertPos);
866 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000867 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000868}
Chris Lattnera7674d82007-07-13 22:13:22 +0000869
Reid Spencer5f016e22007-07-11 17:01:13 +0000870/// getComplexType - Return the uniqued reference to the type for a complex
871/// number with the specified element type.
872QualType ASTContext::getComplexType(QualType T) {
873 // Unique pointers, to guarantee there is only one pointer of a particular
874 // structure.
875 llvm::FoldingSetNodeID ID;
876 ComplexType::Profile(ID, T);
877
878 void *InsertPos = 0;
879 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
880 return QualType(CT, 0);
881
882 // If the pointee type isn't canonical, this won't be a canonical type either,
883 // so fill in the canonical type field.
884 QualType Canonical;
885 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000886 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +0000887
888 // Get the new insert position for the node we care about.
889 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000890 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000891 }
Steve Narofff83820b2009-01-27 22:08:43 +0000892 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000893 Types.push_back(New);
894 ComplexTypes.InsertNode(New, InsertPos);
895 return QualType(New, 0);
896}
897
Eli Friedmanf98aba32009-02-13 02:31:07 +0000898QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
899 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
900 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
901 FixedWidthIntType *&Entry = Map[Width];
902 if (!Entry)
903 Entry = new FixedWidthIntType(Width, Signed);
904 return QualType(Entry, 0);
905}
Reid Spencer5f016e22007-07-11 17:01:13 +0000906
907/// getPointerType - Return the uniqued reference to the type for a pointer to
908/// the specified type.
909QualType ASTContext::getPointerType(QualType T) {
910 // Unique pointers, to guarantee there is only one pointer of a particular
911 // structure.
912 llvm::FoldingSetNodeID ID;
913 PointerType::Profile(ID, T);
914
915 void *InsertPos = 0;
916 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
917 return QualType(PT, 0);
918
919 // If the pointee type isn't canonical, this won't be a canonical type either,
920 // so fill in the canonical type field.
921 QualType Canonical;
922 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000923 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +0000924
925 // Get the new insert position for the node we care about.
926 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000927 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 }
Steve Narofff83820b2009-01-27 22:08:43 +0000929 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000930 Types.push_back(New);
931 PointerTypes.InsertNode(New, InsertPos);
932 return QualType(New, 0);
933}
934
Steve Naroff5618bd42008-08-27 16:04:49 +0000935/// getBlockPointerType - Return the uniqued reference to the type for
936/// a pointer to the specified block.
937QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +0000938 assert(T->isFunctionType() && "block of function types only");
939 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +0000940 // structure.
941 llvm::FoldingSetNodeID ID;
942 BlockPointerType::Profile(ID, T);
943
944 void *InsertPos = 0;
945 if (BlockPointerType *PT =
946 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
947 return QualType(PT, 0);
948
Steve Naroff296e8d52008-08-28 19:20:44 +0000949 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +0000950 // type either so fill in the canonical type field.
951 QualType Canonical;
952 if (!T->isCanonical()) {
953 Canonical = getBlockPointerType(getCanonicalType(T));
954
955 // Get the new insert position for the node we care about.
956 BlockPointerType *NewIP =
957 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000958 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +0000959 }
Steve Narofff83820b2009-01-27 22:08:43 +0000960 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +0000961 Types.push_back(New);
962 BlockPointerTypes.InsertNode(New, InsertPos);
963 return QualType(New, 0);
964}
965
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000966/// getLValueReferenceType - Return the uniqued reference to the type for an
967/// lvalue reference to the specified type.
968QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000969 // Unique pointers, to guarantee there is only one pointer of a particular
970 // structure.
971 llvm::FoldingSetNodeID ID;
972 ReferenceType::Profile(ID, T);
973
974 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000975 if (LValueReferenceType *RT =
976 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +0000977 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000978
Reid Spencer5f016e22007-07-11 17:01:13 +0000979 // If the referencee type isn't canonical, this won't be a canonical type
980 // either, so fill in the canonical type field.
981 QualType Canonical;
982 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000983 Canonical = getLValueReferenceType(getCanonicalType(T));
984
Reid Spencer5f016e22007-07-11 17:01:13 +0000985 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000986 LValueReferenceType *NewIP =
987 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000988 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000989 }
990
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000991 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000992 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000993 LValueReferenceTypes.InsertNode(New, InsertPos);
994 return QualType(New, 0);
995}
996
997/// getRValueReferenceType - Return the uniqued reference to the type for an
998/// rvalue reference to the specified type.
999QualType ASTContext::getRValueReferenceType(QualType T) {
1000 // Unique pointers, to guarantee there is only one pointer of a particular
1001 // structure.
1002 llvm::FoldingSetNodeID ID;
1003 ReferenceType::Profile(ID, T);
1004
1005 void *InsertPos = 0;
1006 if (RValueReferenceType *RT =
1007 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1008 return QualType(RT, 0);
1009
1010 // If the referencee type isn't canonical, this won't be a canonical type
1011 // either, so fill in the canonical type field.
1012 QualType Canonical;
1013 if (!T->isCanonical()) {
1014 Canonical = getRValueReferenceType(getCanonicalType(T));
1015
1016 // Get the new insert position for the node we care about.
1017 RValueReferenceType *NewIP =
1018 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1019 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1020 }
1021
1022 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1023 Types.push_back(New);
1024 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001025 return QualType(New, 0);
1026}
1027
Sebastian Redlf30208a2009-01-24 21:16:55 +00001028/// getMemberPointerType - Return the uniqued reference to the type for a
1029/// member pointer to the specified type, in the specified class.
1030QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1031{
1032 // Unique pointers, to guarantee there is only one pointer of a particular
1033 // structure.
1034 llvm::FoldingSetNodeID ID;
1035 MemberPointerType::Profile(ID, T, Cls);
1036
1037 void *InsertPos = 0;
1038 if (MemberPointerType *PT =
1039 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1040 return QualType(PT, 0);
1041
1042 // If the pointee or class type isn't canonical, this won't be a canonical
1043 // type either, so fill in the canonical type field.
1044 QualType Canonical;
1045 if (!T->isCanonical()) {
1046 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1047
1048 // Get the new insert position for the node we care about.
1049 MemberPointerType *NewIP =
1050 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1051 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1052 }
Steve Narofff83820b2009-01-27 22:08:43 +00001053 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001054 Types.push_back(New);
1055 MemberPointerTypes.InsertNode(New, InsertPos);
1056 return QualType(New, 0);
1057}
1058
Steve Narofffb22d962007-08-30 01:06:46 +00001059/// getConstantArrayType - Return the unique reference to the type for an
1060/// array of the specified element type.
1061QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001062 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001063 ArrayType::ArraySizeModifier ASM,
1064 unsigned EltTypeQuals) {
Chris Lattner38aeec72009-05-13 04:12:56 +00001065 // Convert the array size into a canonical width matching the pointer size for
1066 // the target.
1067 llvm::APInt ArySize(ArySizeIn);
1068 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1069
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001071 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001072
1073 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001074 if (ConstantArrayType *ATP =
1075 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 return QualType(ATP, 0);
1077
1078 // If the element type isn't canonical, this won't be a canonical type either,
1079 // so fill in the canonical type field.
1080 QualType Canonical;
1081 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001082 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001083 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001084 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001085 ConstantArrayType *NewIP =
1086 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001087 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001088 }
1089
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001090 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001091 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001092 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001093 Types.push_back(New);
1094 return QualType(New, 0);
1095}
1096
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001097/// getVariableArrayType - Returns a non-unique reference to the type for a
1098/// variable array of the specified element type.
Steve Naroffc9406122007-08-30 18:10:14 +00001099QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
1100 ArrayType::ArraySizeModifier ASM,
1101 unsigned EltTypeQuals) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001102 // Since we don't unique expressions, it isn't possible to unique VLA's
1103 // that have an expression provided for their size.
1104
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001105 VariableArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001106 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001107
1108 VariableArrayTypes.push_back(New);
1109 Types.push_back(New);
1110 return QualType(New, 0);
1111}
1112
Douglas Gregor898574e2008-12-05 23:32:09 +00001113/// getDependentSizedArrayType - Returns a non-unique reference to
1114/// the type for a dependently-sized array of the specified element
1115/// type. FIXME: We will need these to be uniqued, or at least
1116/// comparable, at some point.
1117QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1118 ArrayType::ArraySizeModifier ASM,
1119 unsigned EltTypeQuals) {
1120 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1121 "Size must be type- or value-dependent!");
1122
1123 // Since we don't unique expressions, it isn't possible to unique
1124 // dependently-sized array types.
1125
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001126 DependentSizedArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001127 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts,
1128 ASM, EltTypeQuals);
Douglas Gregor898574e2008-12-05 23:32:09 +00001129
1130 DependentSizedArrayTypes.push_back(New);
1131 Types.push_back(New);
1132 return QualType(New, 0);
1133}
1134
Eli Friedmanc5773c42008-02-15 18:16:39 +00001135QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1136 ArrayType::ArraySizeModifier ASM,
1137 unsigned EltTypeQuals) {
1138 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001139 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001140
1141 void *InsertPos = 0;
1142 if (IncompleteArrayType *ATP =
1143 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1144 return QualType(ATP, 0);
1145
1146 // If the element type isn't canonical, this won't be a canonical type
1147 // either, so fill in the canonical type field.
1148 QualType Canonical;
1149
1150 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001151 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001152 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001153
1154 // Get the new insert position for the node we care about.
1155 IncompleteArrayType *NewIP =
1156 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001157 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001158 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001159
Steve Narofff83820b2009-01-27 22:08:43 +00001160 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical,
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001161 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001162
1163 IncompleteArrayTypes.InsertNode(New, InsertPos);
1164 Types.push_back(New);
1165 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001166}
1167
Steve Naroff73322922007-07-18 18:00:27 +00001168/// getVectorType - Return the unique reference to a vector type of
1169/// the specified element type and size. VectorType must be a built-in type.
1170QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 BuiltinType *baseType;
1172
Chris Lattnerf52ab252008-04-06 22:59:24 +00001173 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001174 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001175
1176 // Check if we've already instantiated a vector of this type.
1177 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001178 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001179 void *InsertPos = 0;
1180 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1181 return QualType(VTP, 0);
1182
1183 // If the element type isn't canonical, this won't be a canonical type either,
1184 // so fill in the canonical type field.
1185 QualType Canonical;
1186 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001187 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001188
1189 // Get the new insert position for the node we care about.
1190 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001191 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001192 }
Steve Narofff83820b2009-01-27 22:08:43 +00001193 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 VectorTypes.InsertNode(New, InsertPos);
1195 Types.push_back(New);
1196 return QualType(New, 0);
1197}
1198
Nate Begeman213541a2008-04-18 23:10:10 +00001199/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001200/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001201QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001202 BuiltinType *baseType;
1203
Chris Lattnerf52ab252008-04-06 22:59:24 +00001204 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001205 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001206
1207 // Check if we've already instantiated a vector of this type.
1208 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001209 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001210 void *InsertPos = 0;
1211 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1212 return QualType(VTP, 0);
1213
1214 // If the element type isn't canonical, this won't be a canonical type either,
1215 // so fill in the canonical type field.
1216 QualType Canonical;
1217 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001218 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001219
1220 // Get the new insert position for the node we care about.
1221 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001222 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001223 }
Steve Narofff83820b2009-01-27 22:08:43 +00001224 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001225 VectorTypes.InsertNode(New, InsertPos);
1226 Types.push_back(New);
1227 return QualType(New, 0);
1228}
1229
Douglas Gregor72564e72009-02-26 23:50:07 +00001230/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001231///
Douglas Gregor72564e72009-02-26 23:50:07 +00001232QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 // Unique functions, to guarantee there is only one function of a particular
1234 // structure.
1235 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001236 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001237
1238 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001239 if (FunctionNoProtoType *FT =
1240 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 return QualType(FT, 0);
1242
1243 QualType Canonical;
1244 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001245 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001246
1247 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001248 FunctionNoProtoType *NewIP =
1249 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001250 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 }
1252
Douglas Gregor72564e72009-02-26 23:50:07 +00001253 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001255 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 return QualType(New, 0);
1257}
1258
1259/// getFunctionType - Return a normal function type with a typed argument
1260/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001261QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001262 unsigned NumArgs, bool isVariadic,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001263 unsigned TypeQuals) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001264 // Unique functions, to guarantee there is only one function of a particular
1265 // structure.
1266 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001267 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001268 TypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001269
1270 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001271 if (FunctionProtoType *FTP =
1272 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 return QualType(FTP, 0);
1274
1275 // Determine whether the type being created is already canonical or not.
1276 bool isCanonical = ResultTy->isCanonical();
1277 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1278 if (!ArgArray[i]->isCanonical())
1279 isCanonical = false;
1280
1281 // If this type isn't canonical, get the canonical version of it.
1282 QualType Canonical;
1283 if (!isCanonical) {
1284 llvm::SmallVector<QualType, 16> CanonicalArgs;
1285 CanonicalArgs.reserve(NumArgs);
1286 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001287 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001288
Chris Lattnerf52ab252008-04-06 22:59:24 +00001289 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001290 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001291 isVariadic, TypeQuals);
1292
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001294 FunctionProtoType *NewIP =
1295 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001296 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 }
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001298
Douglas Gregor72564e72009-02-26 23:50:07 +00001299 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001300 // for a variable size array (for parameter types) at the end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001301 FunctionProtoType *FTP =
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001302 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1303 NumArgs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001304 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001305 TypeQuals, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001307 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001308 return QualType(FTP, 0);
1309}
1310
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001311/// getTypeDeclType - Return the unique reference to the type for the
1312/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001313QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001314 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001315 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1316
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001317 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001318 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001319 else if (isa<TemplateTypeParmDecl>(Decl)) {
1320 assert(false && "Template type parameter types are always available.");
1321 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001322 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001323
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001324 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001325 if (PrevDecl)
1326 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001327 else
1328 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001329 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001330 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1331 if (PrevDecl)
1332 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001333 else
1334 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001335 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001336 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001337 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001338
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001339 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001340 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001341}
1342
Reid Spencer5f016e22007-07-11 17:01:13 +00001343/// getTypedefType - Return the unique reference to the type for the
1344/// specified typename decl.
1345QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1346 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1347
Chris Lattnerf52ab252008-04-06 22:59:24 +00001348 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001349 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 Types.push_back(Decl->TypeForDecl);
1351 return QualType(Decl->TypeForDecl, 0);
1352}
1353
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001354/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff3536b442007-09-06 21:24:23 +00001355/// specified ObjC interface decl.
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001356QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff3536b442007-09-06 21:24:23 +00001357 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1358
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001359 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1360 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff3536b442007-09-06 21:24:23 +00001361 Types.push_back(Decl->TypeForDecl);
1362 return QualType(Decl->TypeForDecl, 0);
1363}
1364
Douglas Gregorfab9d672009-02-05 23:33:38 +00001365/// \brief Retrieve the template type parameter type for a template
1366/// parameter with the given depth, index, and (optionally) name.
1367QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1368 IdentifierInfo *Name) {
1369 llvm::FoldingSetNodeID ID;
1370 TemplateTypeParmType::Profile(ID, Depth, Index, Name);
1371 void *InsertPos = 0;
1372 TemplateTypeParmType *TypeParm
1373 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1374
1375 if (TypeParm)
1376 return QualType(TypeParm, 0);
1377
1378 if (Name)
1379 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, Name,
1380 getTemplateTypeParmType(Depth, Index));
1381 else
1382 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index);
1383
1384 Types.push_back(TypeParm);
1385 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1386
1387 return QualType(TypeParm, 0);
1388}
1389
Douglas Gregor55f6b142009-02-09 18:46:07 +00001390QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001391ASTContext::getTemplateSpecializationType(TemplateName Template,
1392 const TemplateArgument *Args,
1393 unsigned NumArgs,
1394 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001395 if (!Canon.isNull())
1396 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001397
Douglas Gregor55f6b142009-02-09 18:46:07 +00001398 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001399 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001400
Douglas Gregor55f6b142009-02-09 18:46:07 +00001401 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001402 TemplateSpecializationType *Spec
1403 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001404
1405 if (Spec)
1406 return QualType(Spec, 0);
1407
Douglas Gregor7532dc62009-03-30 22:58:21 +00001408 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001409 sizeof(TemplateArgument) * NumArgs),
1410 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001411 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001412 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001413 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001414
1415 return QualType(Spec, 0);
1416}
1417
Douglas Gregore4e5b052009-03-19 00:18:19 +00001418QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001419ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001420 QualType NamedType) {
1421 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001422 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001423
1424 void *InsertPos = 0;
1425 QualifiedNameType *T
1426 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1427 if (T)
1428 return QualType(T, 0);
1429
Douglas Gregorab452ba2009-03-26 23:50:42 +00001430 T = new (*this) QualifiedNameType(NNS, NamedType,
1431 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001432 Types.push_back(T);
1433 QualifiedNameTypes.InsertNode(T, InsertPos);
1434 return QualType(T, 0);
1435}
1436
Douglas Gregord57959a2009-03-27 23:10:48 +00001437QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1438 const IdentifierInfo *Name,
1439 QualType Canon) {
1440 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1441
1442 if (Canon.isNull()) {
1443 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1444 if (CanonNNS != NNS)
1445 Canon = getTypenameType(CanonNNS, Name);
1446 }
1447
1448 llvm::FoldingSetNodeID ID;
1449 TypenameType::Profile(ID, NNS, Name);
1450
1451 void *InsertPos = 0;
1452 TypenameType *T
1453 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1454 if (T)
1455 return QualType(T, 0);
1456
1457 T = new (*this) TypenameType(NNS, Name, Canon);
1458 Types.push_back(T);
1459 TypenameTypes.InsertNode(T, InsertPos);
1460 return QualType(T, 0);
1461}
1462
Douglas Gregor17343172009-04-01 00:28:59 +00001463QualType
1464ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1465 const TemplateSpecializationType *TemplateId,
1466 QualType Canon) {
1467 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1468
1469 if (Canon.isNull()) {
1470 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1471 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1472 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1473 const TemplateSpecializationType *CanonTemplateId
1474 = CanonType->getAsTemplateSpecializationType();
1475 assert(CanonTemplateId &&
1476 "Canonical type must also be a template specialization type");
1477 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1478 }
1479 }
1480
1481 llvm::FoldingSetNodeID ID;
1482 TypenameType::Profile(ID, NNS, TemplateId);
1483
1484 void *InsertPos = 0;
1485 TypenameType *T
1486 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1487 if (T)
1488 return QualType(T, 0);
1489
1490 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1491 Types.push_back(T);
1492 TypenameTypes.InsertNode(T, InsertPos);
1493 return QualType(T, 0);
1494}
1495
Chris Lattner88cb27a2008-04-07 04:56:42 +00001496/// CmpProtocolNames - Comparison predicate for sorting protocols
1497/// alphabetically.
1498static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1499 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001500 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001501}
1502
1503static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1504 unsigned &NumProtocols) {
1505 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1506
1507 // Sort protocols, keyed by name.
1508 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1509
1510 // Remove duplicates.
1511 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1512 NumProtocols = ProtocolsEnd-Protocols;
1513}
1514
1515
Chris Lattner065f0d72008-04-07 04:44:08 +00001516/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1517/// the given interface decl and the conforming protocol list.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001518QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1519 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001520 // Sort the protocol list alphabetically to canonicalize it.
1521 SortAndUniqueProtocols(Protocols, NumProtocols);
1522
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001523 llvm::FoldingSetNodeID ID;
Chris Lattnerb0489812008-04-07 06:38:24 +00001524 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001525
1526 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001527 if (ObjCQualifiedInterfaceType *QT =
1528 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001529 return QualType(QT, 0);
1530
1531 // No Match;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001532 ObjCQualifiedInterfaceType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001533 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001534
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001535 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001536 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001537 return QualType(QType, 0);
1538}
1539
Chris Lattner88cb27a2008-04-07 04:56:42 +00001540/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl
1541/// and the conforming protocol list.
Chris Lattner62f5f7f2008-07-26 00:46:50 +00001542QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols,
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001543 unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001544 // Sort the protocol list alphabetically to canonicalize it.
1545 SortAndUniqueProtocols(Protocols, NumProtocols);
1546
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001547 llvm::FoldingSetNodeID ID;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001548 ObjCQualifiedIdType::Profile(ID, Protocols, NumProtocols);
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001549
1550 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001551 if (ObjCQualifiedIdType *QT =
Chris Lattner62f5f7f2008-07-26 00:46:50 +00001552 ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001553 return QualType(QT, 0);
1554
1555 // No Match;
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001556 ObjCQualifiedIdType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001557 new (*this,8) ObjCQualifiedIdType(Protocols, NumProtocols);
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001558 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001559 ObjCQualifiedIdTypes.InsertNode(QType, InsertPos);
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001560 return QualType(QType, 0);
1561}
1562
Douglas Gregor72564e72009-02-26 23:50:07 +00001563/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1564/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001565/// multiple declarations that refer to "typeof(x)" all contain different
1566/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1567/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001568QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001569 QualType Canonical = getCanonicalType(tofExpr->getType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001570 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001571 Types.push_back(toe);
1572 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001573}
1574
Steve Naroff9752f252007-08-01 18:02:17 +00001575/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1576/// TypeOfType AST's. The only motivation to unique these nodes would be
1577/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1578/// an issue. This doesn't effect the type checker, since it operates
1579/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001580QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001581 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001582 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001583 Types.push_back(tot);
1584 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001585}
1586
Reid Spencer5f016e22007-07-11 17:01:13 +00001587/// getTagDeclType - Return the unique reference to the type for the
1588/// specified TagDecl (struct/union/class/enum) decl.
1589QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001590 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001591 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001592}
1593
1594/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1595/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1596/// needs to agree with the definition in <stddef.h>.
1597QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001598 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001599}
1600
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001601/// getSignedWCharType - Return the type of "signed wchar_t".
1602/// Used when in C++, as a GCC extension.
1603QualType ASTContext::getSignedWCharType() const {
1604 // FIXME: derive from "Target" ?
1605 return WCharTy;
1606}
1607
1608/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1609/// Used when in C++, as a GCC extension.
1610QualType ASTContext::getUnsignedWCharType() const {
1611 // FIXME: derive from "Target" ?
1612 return UnsignedIntTy;
1613}
1614
Chris Lattner8b9023b2007-07-13 03:05:23 +00001615/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1616/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1617QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001618 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00001619}
1620
Chris Lattnere6327742008-04-02 05:18:44 +00001621//===----------------------------------------------------------------------===//
1622// Type Operators
1623//===----------------------------------------------------------------------===//
1624
Chris Lattner77c96472008-04-06 22:41:35 +00001625/// getCanonicalType - Return the canonical (structural) type corresponding to
1626/// the specified potentially non-canonical type. The non-canonical version
1627/// of a type may have many "decorated" versions of types. Decorators can
1628/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1629/// to be free of any of these, allowing two canonical types to be compared
1630/// for exact equality with a simple pointer comparison.
1631QualType ASTContext::getCanonicalType(QualType T) {
1632 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001633
1634 // If the result has type qualifiers, make sure to canonicalize them as well.
1635 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1636 if (TypeQuals == 0) return CanType;
1637
1638 // If the type qualifiers are on an array type, get the canonical type of the
1639 // array with the qualifiers applied to the element type.
1640 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1641 if (!AT)
1642 return CanType.getQualifiedType(TypeQuals);
1643
1644 // Get the canonical version of the element with the extra qualifiers on it.
1645 // This can recursively sink qualifiers through multiple levels of arrays.
1646 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1647 NewEltTy = getCanonicalType(NewEltTy);
1648
1649 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1650 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1651 CAT->getIndexTypeQualifier());
1652 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1653 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1654 IAT->getIndexTypeQualifier());
1655
Douglas Gregor898574e2008-12-05 23:32:09 +00001656 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1657 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1658 DSAT->getSizeModifier(),
1659 DSAT->getIndexTypeQualifier());
1660
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001661 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1662 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1663 VAT->getSizeModifier(),
1664 VAT->getIndexTypeQualifier());
1665}
1666
Douglas Gregor7da97d02009-05-10 22:57:19 +00001667Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregorc4ccf012009-05-10 22:59:12 +00001668 if (!D)
1669 return 0;
1670
Douglas Gregor7da97d02009-05-10 22:57:19 +00001671 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
1672 QualType T = getTagDeclType(Tag);
1673 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
1674 ->getDecl());
1675 }
1676
1677 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
1678 while (Template->getPreviousDeclaration())
1679 Template = Template->getPreviousDeclaration();
1680 return Template;
1681 }
1682
1683 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1684 while (Function->getPreviousDeclaration())
1685 Function = Function->getPreviousDeclaration();
1686 return const_cast<FunctionDecl *>(Function);
1687 }
1688
1689 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1690 while (Var->getPreviousDeclaration())
1691 Var = Var->getPreviousDeclaration();
1692 return const_cast<VarDecl *>(Var);
1693 }
1694
1695 return D;
1696}
1697
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001698TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1699 // If this template name refers to a template, the canonical
1700 // template name merely stores the template itself.
1701 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor7da97d02009-05-10 22:57:19 +00001702 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001703
1704 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1705 assert(DTN && "Non-dependent template names must refer to template decls.");
1706 return DTN->CanonicalTemplateName;
1707}
1708
Douglas Gregord57959a2009-03-27 23:10:48 +00001709NestedNameSpecifier *
1710ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1711 if (!NNS)
1712 return 0;
1713
1714 switch (NNS->getKind()) {
1715 case NestedNameSpecifier::Identifier:
1716 // Canonicalize the prefix but keep the identifier the same.
1717 return NestedNameSpecifier::Create(*this,
1718 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1719 NNS->getAsIdentifier());
1720
1721 case NestedNameSpecifier::Namespace:
1722 // A namespace is canonical; build a nested-name-specifier with
1723 // this namespace and no prefix.
1724 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1725
1726 case NestedNameSpecifier::TypeSpec:
1727 case NestedNameSpecifier::TypeSpecWithTemplate: {
1728 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1729 NestedNameSpecifier *Prefix = 0;
1730
1731 // FIXME: This isn't the right check!
1732 if (T->isDependentType())
1733 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1734
1735 return NestedNameSpecifier::Create(*this, Prefix,
1736 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1737 T.getTypePtr());
1738 }
1739
1740 case NestedNameSpecifier::Global:
1741 // The global specifier is canonical and unique.
1742 return NNS;
1743 }
1744
1745 // Required to silence a GCC warning
1746 return 0;
1747}
1748
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001749
1750const ArrayType *ASTContext::getAsArrayType(QualType T) {
1751 // Handle the non-qualified case efficiently.
1752 if (T.getCVRQualifiers() == 0) {
1753 // Handle the common positive case fast.
1754 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1755 return AT;
1756 }
1757
1758 // Handle the common negative case fast, ignoring CVR qualifiers.
1759 QualType CType = T->getCanonicalTypeInternal();
1760
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001761 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001762 // test.
1763 if (!isa<ArrayType>(CType) &&
1764 !isa<ArrayType>(CType.getUnqualifiedType()))
1765 return 0;
1766
1767 // Apply any CVR qualifiers from the array type to the element type. This
1768 // implements C99 6.7.3p8: "If the specification of an array type includes
1769 // any type qualifiers, the element type is so qualified, not the array type."
1770
1771 // If we get here, we either have type qualifiers on the type, or we have
1772 // sugar such as a typedef in the way. If we have type qualifiers on the type
1773 // we must propagate them down into the elemeng type.
1774 unsigned CVRQuals = T.getCVRQualifiers();
1775 unsigned AddrSpace = 0;
1776 Type *Ty = T.getTypePtr();
1777
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001778 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001779 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001780 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
1781 AddrSpace = EXTQT->getAddressSpace();
1782 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001783 } else {
1784 T = Ty->getDesugaredType();
1785 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1786 break;
1787 CVRQuals |= T.getCVRQualifiers();
1788 Ty = T.getTypePtr();
1789 }
1790 }
1791
1792 // If we have a simple case, just return now.
1793 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1794 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1795 return ATy;
1796
1797 // Otherwise, we have an array and we have qualifiers on it. Push the
1798 // qualifiers into the array element type and return a new array type.
1799 // Get the canonical version of the element with the extra qualifiers on it.
1800 // This can recursively sink qualifiers through multiple levels of arrays.
1801 QualType NewEltTy = ATy->getElementType();
1802 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001803 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001804 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1805
1806 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1807 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1808 CAT->getSizeModifier(),
1809 CAT->getIndexTypeQualifier()));
1810 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1811 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1812 IAT->getSizeModifier(),
1813 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00001814
Douglas Gregor898574e2008-12-05 23:32:09 +00001815 if (const DependentSizedArrayType *DSAT
1816 = dyn_cast<DependentSizedArrayType>(ATy))
1817 return cast<ArrayType>(
1818 getDependentSizedArrayType(NewEltTy,
1819 DSAT->getSizeExpr(),
1820 DSAT->getSizeModifier(),
1821 DSAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001822
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001823 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1824 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1825 VAT->getSizeModifier(),
1826 VAT->getIndexTypeQualifier()));
Chris Lattner77c96472008-04-06 22:41:35 +00001827}
1828
1829
Chris Lattnere6327742008-04-02 05:18:44 +00001830/// getArrayDecayedType - Return the properly qualified result of decaying the
1831/// specified array type to a pointer. This operation is non-trivial when
1832/// handling typedefs etc. The canonical type of "T" must be an array type,
1833/// this returns a pointer to a properly qualified element of the array.
1834///
1835/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1836QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001837 // Get the element type with 'getAsArrayType' so that we don't lose any
1838 // typedefs in the element type of the array. This also handles propagation
1839 // of type qualifiers from the array type into the element type if present
1840 // (C99 6.7.3p8).
1841 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1842 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00001843
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001844 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00001845
1846 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001847 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00001848}
1849
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001850QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00001851 QualType ElemTy = VAT->getElementType();
1852
1853 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1854 return getBaseElementType(VAT);
1855
1856 return ElemTy;
1857}
1858
Reid Spencer5f016e22007-07-11 17:01:13 +00001859/// getFloatingRank - Return a relative rank for floating point types.
1860/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00001861static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00001862 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001863 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00001864
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001865 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00001866 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00001867 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 case BuiltinType::Float: return FloatRank;
1869 case BuiltinType::Double: return DoubleRank;
1870 case BuiltinType::LongDouble: return LongDoubleRank;
1871 }
1872}
1873
Steve Naroff716c7302007-08-27 01:41:48 +00001874/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1875/// point or a complex type (based on typeDomain/typeSize).
1876/// 'typeDomain' is a real floating point or complex type.
1877/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00001878QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
1879 QualType Domain) const {
1880 FloatingRank EltRank = getFloatingRank(Size);
1881 if (Domain->isComplexType()) {
1882 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00001883 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00001884 case FloatRank: return FloatComplexTy;
1885 case DoubleRank: return DoubleComplexTy;
1886 case LongDoubleRank: return LongDoubleComplexTy;
1887 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001888 }
Chris Lattner1361b112008-04-06 23:58:54 +00001889
1890 assert(Domain->isRealFloatingType() && "Unknown domain!");
1891 switch (EltRank) {
1892 default: assert(0 && "getFloatingRank(): illegal value for rank");
1893 case FloatRank: return FloatTy;
1894 case DoubleRank: return DoubleTy;
1895 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00001896 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001897}
1898
Chris Lattner7cfeb082008-04-06 23:55:33 +00001899/// getFloatingTypeOrder - Compare the rank of the two specified floating
1900/// point types, ignoring the domain of the type (i.e. 'double' ==
1901/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
1902/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00001903int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
1904 FloatingRank LHSR = getFloatingRank(LHS);
1905 FloatingRank RHSR = getFloatingRank(RHS);
1906
1907 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00001908 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00001909 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00001910 return 1;
1911 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001912}
1913
Chris Lattnerf52ab252008-04-06 22:59:24 +00001914/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
1915/// routine will assert if passed a built-in type that isn't an integer or enum,
1916/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00001917unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001918 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00001919 if (EnumType* ET = dyn_cast<EnumType>(T))
1920 T = ET->getDecl()->getIntegerType().getTypePtr();
1921
1922 // There are two things which impact the integer rank: the width, and
1923 // the ordering of builtins. The builtin ordering is encoded in the
1924 // bottom three bits; the width is encoded in the bits above that.
1925 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
1926 return FWIT->getWidth() << 3;
1927 }
1928
Chris Lattnerf52ab252008-04-06 22:59:24 +00001929 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00001930 default: assert(0 && "getIntegerRank(): not a built-in integer");
1931 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001932 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00001933 case BuiltinType::Char_S:
1934 case BuiltinType::Char_U:
1935 case BuiltinType::SChar:
1936 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001937 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00001938 case BuiltinType::Short:
1939 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001940 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00001941 case BuiltinType::Int:
1942 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001943 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00001944 case BuiltinType::Long:
1945 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001946 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00001947 case BuiltinType::LongLong:
1948 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001949 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00001950 case BuiltinType::Int128:
1951 case BuiltinType::UInt128:
1952 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00001953 }
1954}
1955
Chris Lattner7cfeb082008-04-06 23:55:33 +00001956/// getIntegerTypeOrder - Returns the highest ranked integer type:
1957/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
1958/// LHS < RHS, return -1.
1959int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001960 Type *LHSC = getCanonicalType(LHS).getTypePtr();
1961 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00001962 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001963
Chris Lattnerf52ab252008-04-06 22:59:24 +00001964 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
1965 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001966
Chris Lattner7cfeb082008-04-06 23:55:33 +00001967 unsigned LHSRank = getIntegerRank(LHSC);
1968 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00001969
Chris Lattner7cfeb082008-04-06 23:55:33 +00001970 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
1971 if (LHSRank == RHSRank) return 0;
1972 return LHSRank > RHSRank ? 1 : -1;
1973 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001974
Chris Lattner7cfeb082008-04-06 23:55:33 +00001975 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
1976 if (LHSUnsigned) {
1977 // If the unsigned [LHS] type is larger, return it.
1978 if (LHSRank >= RHSRank)
1979 return 1;
1980
1981 // If the signed type can represent all values of the unsigned type, it
1982 // wins. Because we are dealing with 2's complement and types that are
1983 // powers of two larger than each other, this is always safe.
1984 return -1;
1985 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00001986
Chris Lattner7cfeb082008-04-06 23:55:33 +00001987 // If the unsigned [RHS] type is larger, return it.
1988 if (RHSRank >= LHSRank)
1989 return -1;
1990
1991 // If the signed type can represent all values of the unsigned type, it
1992 // wins. Because we are dealing with 2's complement and types that are
1993 // powers of two larger than each other, this is always safe.
1994 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001995}
Anders Carlsson71993dd2007-08-17 05:31:46 +00001996
1997// getCFConstantStringType - Return the type used for constant CFStrings.
1998QualType ASTContext::getCFConstantStringType() {
1999 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002000 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002001 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002002 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002003 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002004
2005 // const int *isa;
2006 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002007 // int flags;
2008 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002009 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002010 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002011 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002012 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002013
Anders Carlsson71993dd2007-08-17 05:31:46 +00002014 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002015 for (unsigned i = 0; i < 4; ++i) {
2016 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2017 SourceLocation(), 0,
2018 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002019 /*Mutable=*/false);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002020 CFConstantStringTypeDecl->addDecl(*this, Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002021 }
2022
2023 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002024 }
2025
2026 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002027}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002028
Douglas Gregor319ac892009-04-23 22:29:11 +00002029void ASTContext::setCFConstantStringType(QualType T) {
2030 const RecordType *Rec = T->getAsRecordType();
2031 assert(Rec && "Invalid CFConstantStringType");
2032 CFConstantStringTypeDecl = Rec->getDecl();
2033}
2034
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002035QualType ASTContext::getObjCFastEnumerationStateType()
2036{
2037 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002038 ObjCFastEnumerationStateTypeDecl =
2039 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2040 &Idents.get("__objcFastEnumerationState"));
2041
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002042 QualType FieldTypes[] = {
2043 UnsignedLongTy,
2044 getPointerType(ObjCIdType),
2045 getPointerType(UnsignedLongTy),
2046 getConstantArrayType(UnsignedLongTy,
2047 llvm::APInt(32, 5), ArrayType::Normal, 0)
2048 };
2049
Douglas Gregor44b43212008-12-11 16:49:14 +00002050 for (size_t i = 0; i < 4; ++i) {
2051 FieldDecl *Field = FieldDecl::Create(*this,
2052 ObjCFastEnumerationStateTypeDecl,
2053 SourceLocation(), 0,
2054 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002055 /*Mutable=*/false);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002056 ObjCFastEnumerationStateTypeDecl->addDecl(*this, Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002057 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002058
Douglas Gregor44b43212008-12-11 16:49:14 +00002059 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002060 }
2061
2062 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2063}
2064
Douglas Gregor319ac892009-04-23 22:29:11 +00002065void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2066 const RecordType *Rec = T->getAsRecordType();
2067 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2068 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2069}
2070
Anders Carlssone8c49532007-10-29 06:33:42 +00002071// This returns true if a type has been typedefed to BOOL:
2072// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002073static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002074 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002075 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2076 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002077
2078 return false;
2079}
2080
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002081/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002082/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002083int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002084 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002085
2086 // Make all integer and enum types at least as large as an int
2087 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002088 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002089 // Treat arrays as pointers, since that's how they're passed in.
2090 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002091 sz = getTypeSize(VoidPtrTy);
2092 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002093}
2094
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002095/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002096/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002097void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002098 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002099 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002100 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002101 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002102 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002103 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002104 // Compute size of all parameters.
2105 // Start with computing size of a pointer in number of bytes.
2106 // FIXME: There might(should) be a better way of doing this computation!
2107 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002108 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002109 // The first two arguments (self and _cmd) are pointers; account for
2110 // their size.
2111 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002112 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2113 E = Decl->param_end(); PI != E; ++PI) {
2114 QualType PType = (*PI)->getType();
2115 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002116 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002117 ParmOffset += sz;
2118 }
2119 S += llvm::utostr(ParmOffset);
2120 S += "@0:";
2121 S += llvm::utostr(PtrSize);
2122
2123 // Argument types.
2124 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002125 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2126 E = Decl->param_end(); PI != E; ++PI) {
2127 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002128 QualType PType = PVDecl->getOriginalType();
2129 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002130 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2131 // Use array's original type only if it has known number of
2132 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002133 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002134 PType = PVDecl->getType();
2135 } else if (PType->isFunctionType())
2136 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002137 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002138 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002139 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002140 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002141 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002142 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002143 }
2144}
2145
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002146/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002147/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002148/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2149/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002150/// Property attributes are stored as a comma-delimited C string. The simple
2151/// attributes readonly and bycopy are encoded as single characters. The
2152/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2153/// encoded as single characters, followed by an identifier. Property types
2154/// are also encoded as a parametrized attribute. The characters used to encode
2155/// these attributes are defined by the following enumeration:
2156/// @code
2157/// enum PropertyAttributes {
2158/// kPropertyReadOnly = 'R', // property is read-only.
2159/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2160/// kPropertyByref = '&', // property is a reference to the value last assigned
2161/// kPropertyDynamic = 'D', // property is dynamic
2162/// kPropertyGetter = 'G', // followed by getter selector name
2163/// kPropertySetter = 'S', // followed by setter selector name
2164/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2165/// kPropertyType = 't' // followed by old-style type encoding.
2166/// kPropertyWeak = 'W' // 'weak' property
2167/// kPropertyStrong = 'P' // property GC'able
2168/// kPropertyNonAtomic = 'N' // property non-atomic
2169/// };
2170/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002171void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2172 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002173 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002174 // Collect information from the property implementation decl(s).
2175 bool Dynamic = false;
2176 ObjCPropertyImplDecl *SynthesizePID = 0;
2177
2178 // FIXME: Duplicated code due to poor abstraction.
2179 if (Container) {
2180 if (const ObjCCategoryImplDecl *CID =
2181 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2182 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00002183 i = CID->propimpl_begin(*this), e = CID->propimpl_end(*this);
2184 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002185 ObjCPropertyImplDecl *PID = *i;
2186 if (PID->getPropertyDecl() == PD) {
2187 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2188 Dynamic = true;
2189 } else {
2190 SynthesizePID = PID;
2191 }
2192 }
2193 }
2194 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002195 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002196 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00002197 i = OID->propimpl_begin(*this), e = OID->propimpl_end(*this);
2198 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002199 ObjCPropertyImplDecl *PID = *i;
2200 if (PID->getPropertyDecl() == PD) {
2201 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2202 Dynamic = true;
2203 } else {
2204 SynthesizePID = PID;
2205 }
2206 }
2207 }
2208 }
2209 }
2210
2211 // FIXME: This is not very efficient.
2212 S = "T";
2213
2214 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002215 // GCC has some special rules regarding encoding of properties which
2216 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002217 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002218 true /* outermost type */,
2219 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002220
2221 if (PD->isReadOnly()) {
2222 S += ",R";
2223 } else {
2224 switch (PD->getSetterKind()) {
2225 case ObjCPropertyDecl::Assign: break;
2226 case ObjCPropertyDecl::Copy: S += ",C"; break;
2227 case ObjCPropertyDecl::Retain: S += ",&"; break;
2228 }
2229 }
2230
2231 // It really isn't clear at all what this means, since properties
2232 // are "dynamic by default".
2233 if (Dynamic)
2234 S += ",D";
2235
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002236 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2237 S += ",N";
2238
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002239 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2240 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002241 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002242 }
2243
2244 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2245 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002246 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002247 }
2248
2249 if (SynthesizePID) {
2250 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2251 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002252 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002253 }
2254
2255 // FIXME: OBJCGC: weak & strong
2256}
2257
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002258/// getLegacyIntegralTypeEncoding -
2259/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002260/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002261/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2262///
2263void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2264 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2265 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002266 if (BT->getKind() == BuiltinType::ULong &&
2267 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002268 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002269 else
2270 if (BT->getKind() == BuiltinType::Long &&
2271 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002272 PointeeTy = IntTy;
2273 }
2274 }
2275}
2276
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002277void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002278 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002279 // We follow the behavior of gcc, expanding structures which are
2280 // directly pointed to, and expanding embedded structures. Note that
2281 // these rules are sufficient to prevent recursive encoding of the
2282 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002283 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2284 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002285}
2286
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002287static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002288 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002289 const Expr *E = FD->getBitWidth();
2290 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2291 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002292 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002293 S += 'b';
2294 S += llvm::utostr(N);
2295}
2296
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002297void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2298 bool ExpandPointedToStructures,
2299 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002300 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002301 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002302 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002303 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002304 if (FD && FD->isBitField()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002305 EncodeBitField(this, S, FD);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002306 }
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002307 else {
2308 char encoding;
2309 switch (BT->getKind()) {
2310 default: assert(0 && "Unhandled builtin type kind");
2311 case BuiltinType::Void: encoding = 'v'; break;
2312 case BuiltinType::Bool: encoding = 'B'; break;
2313 case BuiltinType::Char_U:
2314 case BuiltinType::UChar: encoding = 'C'; break;
2315 case BuiltinType::UShort: encoding = 'S'; break;
2316 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002317 case BuiltinType::ULong:
2318 encoding =
2319 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2320 break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002321 case BuiltinType::UInt128: encoding = 'T'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002322 case BuiltinType::ULongLong: encoding = 'Q'; break;
2323 case BuiltinType::Char_S:
2324 case BuiltinType::SChar: encoding = 'c'; break;
2325 case BuiltinType::Short: encoding = 's'; break;
2326 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002327 case BuiltinType::Long:
2328 encoding =
2329 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2330 break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002331 case BuiltinType::LongLong: encoding = 'q'; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002332 case BuiltinType::Int128: encoding = 't'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002333 case BuiltinType::Float: encoding = 'f'; break;
2334 case BuiltinType::Double: encoding = 'd'; break;
2335 case BuiltinType::LongDouble: encoding = 'd'; break;
2336 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002337
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002338 S += encoding;
2339 }
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002340 } else if (const ComplexType *CT = T->getAsComplexType()) {
2341 S += 'j';
2342 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2343 false);
2344 } else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002345 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2346 ExpandPointedToStructures,
2347 ExpandStructures, FD);
2348 if (FD || EncodingProperty) {
2349 // Note that we do extended encoding of protocol qualifer list
2350 // Only when doing ivar or property encoding.
2351 const ObjCQualifiedIdType *QIDT = T->getAsObjCQualifiedIdType();
2352 S += '"';
2353 for (unsigned i =0; i < QIDT->getNumProtocols(); i++) {
2354 ObjCProtocolDecl *Proto = QIDT->getProtocols(i);
2355 S += '<';
2356 S += Proto->getNameAsString();
2357 S += '>';
2358 }
2359 S += '"';
2360 }
2361 return;
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002362 }
2363 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002364 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002365 bool isReadOnly = false;
2366 // For historical/compatibility reasons, the read-only qualifier of the
2367 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2368 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2369 // Also, do not emit the 'r' for anything but the outermost type!
2370 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2371 if (OutermostType && T.isConstQualified()) {
2372 isReadOnly = true;
2373 S += 'r';
2374 }
2375 }
2376 else if (OutermostType) {
2377 QualType P = PointeeTy;
2378 while (P->getAsPointerType())
2379 P = P->getAsPointerType()->getPointeeType();
2380 if (P.isConstQualified()) {
2381 isReadOnly = true;
2382 S += 'r';
2383 }
2384 }
2385 if (isReadOnly) {
2386 // Another legacy compatibility encoding. Some ObjC qualifier and type
2387 // combinations need to be rearranged.
2388 // Rewrite "in const" from "nr" to "rn"
2389 const char * s = S.c_str();
2390 int len = S.length();
2391 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2392 std::string replace = "rn";
2393 S.replace(S.end()-2, S.end(), replace);
2394 }
2395 }
Steve Naroff389bf462009-02-12 17:52:19 +00002396 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002397 S += '@';
2398 return;
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002399 }
2400 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanianbb99bde2009-02-16 21:41:04 +00002401 if (!EncodingProperty &&
Fariborz Jahanian225dfd72009-02-16 22:09:26 +00002402 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahanian3e1b16c2008-12-23 21:30:15 +00002403 // Another historical/compatibility reason.
2404 // We encode the underlying type which comes out as
2405 // {...};
2406 S += '^';
2407 getObjCEncodingForTypeImpl(PointeeTy, S,
2408 false, ExpandPointedToStructures,
2409 NULL);
2410 return;
2411 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002412 S += '@';
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002413 if (FD || EncodingProperty) {
Fariborz Jahanian86f938b2009-02-21 18:23:24 +00002414 const ObjCInterfaceType *OIT =
2415 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002416 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002417 S += '"';
2418 S += OI->getNameAsCString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002419 for (unsigned i =0; i < OIT->getNumProtocols(); i++) {
2420 ObjCProtocolDecl *Proto = OIT->getProtocol(i);
2421 S += '<';
2422 S += Proto->getNameAsString();
2423 S += '>';
2424 }
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002425 S += '"';
2426 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002427 return;
Steve Naroff389bf462009-02-12 17:52:19 +00002428 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002429 S += '#';
2430 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002431 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002432 S += ':';
2433 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002434 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002435
2436 if (PointeeTy->isCharType()) {
2437 // char pointer types should be encoded as '*' unless it is a
2438 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002439 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002440 S += '*';
2441 return;
2442 }
2443 }
2444
2445 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002446 getLegacyIntegralTypeEncoding(PointeeTy);
2447
2448 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002449 false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002450 NULL);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002451 } else if (const ArrayType *AT =
2452 // Ignore type qualifiers etc.
2453 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002454 if (isa<IncompleteArrayType>(AT)) {
2455 // Incomplete arrays are encoded as a pointer to the array element.
2456 S += '^';
2457
2458 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2459 false, ExpandStructures, FD);
2460 } else {
2461 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002462
Anders Carlsson559a8332009-02-22 01:38:57 +00002463 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2464 S += llvm::utostr(CAT->getSize().getZExtValue());
2465 else {
2466 //Variable length arrays are encoded as a regular array with 0 elements.
2467 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2468 S += '0';
2469 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002470
Anders Carlsson559a8332009-02-22 01:38:57 +00002471 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2472 false, ExpandStructures, FD);
2473 S += ']';
2474 }
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002475 } else if (T->getAsFunctionType()) {
2476 S += '?';
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002477 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002478 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002479 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002480 // Anonymous structures print as '?'
2481 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2482 S += II->getName();
2483 } else {
2484 S += '?';
2485 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002486 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002487 S += '=';
Douglas Gregor6ab35242009-04-09 21:40:53 +00002488 for (RecordDecl::field_iterator Field = RDecl->field_begin(*this),
2489 FieldEnd = RDecl->field_end(*this);
Douglas Gregor44b43212008-12-11 16:49:14 +00002490 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002491 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002492 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002493 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002494 S += '"';
2495 }
2496
2497 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002498 if (Field->isBitField()) {
2499 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2500 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002501 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002502 QualType qt = Field->getType();
2503 getLegacyIntegralTypeEncoding(qt);
2504 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002505 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002506 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002507 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002508 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002509 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff5e711242007-12-12 22:30:11 +00002510 } else if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002511 if (FD && FD->isBitField())
2512 EncodeBitField(this, S, FD);
2513 else
2514 S += 'i';
Steve Naroff485eeff2008-09-24 15:05:44 +00002515 } else if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002516 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002517 } else if (T->isObjCInterfaceType()) {
2518 // @encode(class_name)
2519 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2520 S += '{';
2521 const IdentifierInfo *II = OI->getIdentifier();
2522 S += II->getName();
2523 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002524 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002525 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002526 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002527 if (RecFields[i]->isBitField())
2528 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2529 RecFields[i]);
2530 else
2531 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2532 FD);
2533 }
2534 S += '}';
2535 }
2536 else
Steve Narofff69cc5d2008-01-30 19:17:43 +00002537 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002538}
2539
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002540void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002541 std::string& S) const {
2542 if (QT & Decl::OBJC_TQ_In)
2543 S += 'n';
2544 if (QT & Decl::OBJC_TQ_Inout)
2545 S += 'N';
2546 if (QT & Decl::OBJC_TQ_Out)
2547 S += 'o';
2548 if (QT & Decl::OBJC_TQ_Bycopy)
2549 S += 'O';
2550 if (QT & Decl::OBJC_TQ_Byref)
2551 S += 'R';
2552 if (QT & Decl::OBJC_TQ_Oneway)
2553 S += 'V';
2554}
2555
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002556void ASTContext::setBuiltinVaListType(QualType T)
2557{
2558 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2559
2560 BuiltinVaListType = T;
2561}
2562
Douglas Gregor319ac892009-04-23 22:29:11 +00002563void ASTContext::setObjCIdType(QualType T)
Steve Naroff7e219e42007-10-15 14:41:52 +00002564{
Douglas Gregor319ac892009-04-23 22:29:11 +00002565 ObjCIdType = T;
2566
2567 const TypedefType *TT = T->getAsTypedefType();
2568 if (!TT)
2569 return;
2570
2571 TypedefDecl *TD = TT->getDecl();
Steve Naroff7e219e42007-10-15 14:41:52 +00002572
2573 // typedef struct objc_object *id;
2574 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002575 // User error - caller will issue diagnostics.
2576 if (!ptr)
2577 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002578 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002579 // User error - caller will issue diagnostics.
2580 if (!rec)
2581 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002582 IdStructType = rec;
2583}
2584
Douglas Gregor319ac892009-04-23 22:29:11 +00002585void ASTContext::setObjCSelType(QualType T)
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002586{
Douglas Gregor319ac892009-04-23 22:29:11 +00002587 ObjCSelType = T;
2588
2589 const TypedefType *TT = T->getAsTypedefType();
2590 if (!TT)
2591 return;
2592 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002593
2594 // typedef struct objc_selector *SEL;
2595 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002596 if (!ptr)
2597 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002598 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002599 if (!rec)
2600 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002601 SelStructType = rec;
2602}
2603
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002604void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002605{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002606 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002607}
2608
Douglas Gregor319ac892009-04-23 22:29:11 +00002609void ASTContext::setObjCClassType(QualType T)
Anders Carlsson8baaca52007-10-31 02:53:19 +00002610{
Douglas Gregor319ac892009-04-23 22:29:11 +00002611 ObjCClassType = T;
2612
2613 const TypedefType *TT = T->getAsTypedefType();
2614 if (!TT)
2615 return;
2616 TypedefDecl *TD = TT->getDecl();
Anders Carlsson8baaca52007-10-31 02:53:19 +00002617
2618 // typedef struct objc_class *Class;
2619 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2620 assert(ptr && "'Class' incorrectly typed");
2621 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2622 assert(rec && "'Class' incorrectly typed");
2623 ClassStructType = rec;
2624}
2625
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002626void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2627 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00002628 "'NSConstantString' type already set!");
2629
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002630 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00002631}
2632
Douglas Gregor7532dc62009-03-30 22:58:21 +00002633/// \brief Retrieve the template name that represents a qualified
2634/// template name such as \c std::vector.
2635TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2636 bool TemplateKeyword,
2637 TemplateDecl *Template) {
2638 llvm::FoldingSetNodeID ID;
2639 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2640
2641 void *InsertPos = 0;
2642 QualifiedTemplateName *QTN =
2643 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2644 if (!QTN) {
2645 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2646 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2647 }
2648
2649 return TemplateName(QTN);
2650}
2651
2652/// \brief Retrieve the template name that represents a dependent
2653/// template name such as \c MetaFun::template apply.
2654TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2655 const IdentifierInfo *Name) {
2656 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2657
2658 llvm::FoldingSetNodeID ID;
2659 DependentTemplateName::Profile(ID, NNS, Name);
2660
2661 void *InsertPos = 0;
2662 DependentTemplateName *QTN =
2663 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2664
2665 if (QTN)
2666 return TemplateName(QTN);
2667
2668 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2669 if (CanonNNS == NNS) {
2670 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2671 } else {
2672 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2673 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2674 }
2675
2676 DependentTemplateNames.InsertNode(QTN, InsertPos);
2677 return TemplateName(QTN);
2678}
2679
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002680/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00002681/// TargetInfo, produce the corresponding type. The unsigned @p Type
2682/// is actually a value of type @c TargetInfo::IntType.
2683QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002684 switch (Type) {
2685 case TargetInfo::NoInt: return QualType();
2686 case TargetInfo::SignedShort: return ShortTy;
2687 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2688 case TargetInfo::SignedInt: return IntTy;
2689 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2690 case TargetInfo::SignedLong: return LongTy;
2691 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2692 case TargetInfo::SignedLongLong: return LongLongTy;
2693 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2694 }
2695
2696 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00002697 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002698}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002699
2700//===----------------------------------------------------------------------===//
2701// Type Predicates.
2702//===----------------------------------------------------------------------===//
2703
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002704/// isObjCNSObjectType - Return true if this is an NSObject object using
2705/// NSObject attribute on a c-style pointer type.
2706/// FIXME - Make it work directly on types.
2707///
2708bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2709 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2710 if (TypedefDecl *TD = TDT->getDecl())
2711 if (TD->getAttr<ObjCNSObjectAttr>())
2712 return true;
2713 }
2714 return false;
2715}
2716
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002717/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2718/// to an object type. This includes "id" and "Class" (two 'special' pointers
2719/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2720/// ID type).
2721bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroffd4617772009-02-23 18:36:16 +00002722 if (Ty->isObjCQualifiedIdType())
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002723 return true;
2724
Steve Naroff6ae98502008-10-21 18:24:04 +00002725 // Blocks are objects.
2726 if (Ty->isBlockPointerType())
2727 return true;
2728
2729 // All other object types are pointers.
Chris Lattner16ede0e2009-04-12 23:51:02 +00002730 const PointerType *PT = Ty->getAsPointerType();
2731 if (PT == 0)
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002732 return false;
2733
Chris Lattner16ede0e2009-04-12 23:51:02 +00002734 // If this a pointer to an interface (e.g. NSString*), it is ok.
2735 if (PT->getPointeeType()->isObjCInterfaceType() ||
2736 // If is has NSObject attribute, OK as well.
2737 isObjCNSObjectType(Ty))
2738 return true;
2739
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002740 // Check to see if this is 'id' or 'Class', both of which are typedefs for
2741 // pointer types. This looks for the typedef specifically, not for the
Chris Lattner16ede0e2009-04-12 23:51:02 +00002742 // underlying type. Iteratively strip off typedefs so that we can handle
2743 // typedefs of typedefs.
2744 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2745 if (Ty.getUnqualifiedType() == getObjCIdType() ||
2746 Ty.getUnqualifiedType() == getObjCClassType())
2747 return true;
2748
2749 Ty = TDT->getDecl()->getUnderlyingType();
2750 }
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002751
Chris Lattner16ede0e2009-04-12 23:51:02 +00002752 return false;
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002753}
2754
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002755/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2756/// garbage collection attribute.
2757///
2758QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002759 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002760 if (getLangOptions().ObjC1 &&
2761 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002762 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002763 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002764 // (or pointers to them) be treated as though they were declared
2765 // as __strong.
2766 if (GCAttrs == QualType::GCNone) {
2767 if (isObjCObjectPointerType(Ty))
2768 GCAttrs = QualType::Strong;
2769 else if (Ty->isPointerType())
2770 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
2771 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002772 // Non-pointers have none gc'able attribute regardless of the attribute
2773 // set on them.
2774 else if (!isObjCObjectPointerType(Ty) && !Ty->isPointerType())
2775 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002776 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00002777 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002778}
2779
Chris Lattner6ac46a42008-04-07 06:51:04 +00002780//===----------------------------------------------------------------------===//
2781// Type Compatibility Testing
2782//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00002783
Steve Naroff1c7d0672008-09-04 15:10:53 +00002784/// typesAreBlockCompatible - This routine is called when comparing two
Steve Naroffdd972f22008-09-05 22:11:13 +00002785/// block types. Types must be strictly compatible here. For example,
2786/// C unfortunately doesn't produce an error for the following:
2787///
2788/// int (*emptyArgFunc)();
2789/// int (*intArgList)(int) = emptyArgFunc;
2790///
2791/// For blocks, we will produce an error for the following (similar to C++):
2792///
2793/// int (^emptyArgBlock)();
2794/// int (^intArgBlock)(int) = emptyArgBlock;
2795///
2796/// FIXME: When the dust settles on this integration, fold this into mergeTypes.
2797///
Steve Naroff1c7d0672008-09-04 15:10:53 +00002798bool ASTContext::typesAreBlockCompatible(QualType lhs, QualType rhs) {
Steve Naroffc0febd52008-12-10 17:49:55 +00002799 const FunctionType *lbase = lhs->getAsFunctionType();
2800 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00002801 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2802 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Mike Stumpaab0f7a2009-04-01 01:17:39 +00002803 if (lproto && rproto == 0)
2804 return false;
2805 return !mergeTypes(lhs, rhs).isNull();
Steve Naroff1c7d0672008-09-04 15:10:53 +00002806}
2807
Chris Lattner6ac46a42008-04-07 06:51:04 +00002808/// areCompatVectorTypes - Return true if the two specified vector types are
2809/// compatible.
2810static bool areCompatVectorTypes(const VectorType *LHS,
2811 const VectorType *RHS) {
2812 assert(LHS->isCanonical() && RHS->isCanonical());
2813 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00002814 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00002815}
2816
Eli Friedman3d815e72008-08-22 00:56:42 +00002817/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00002818/// compatible for assignment from RHS to LHS. This handles validation of any
2819/// protocol qualifiers on the LHS or RHS.
2820///
Eli Friedman3d815e72008-08-22 00:56:42 +00002821bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2822 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00002823 // Verify that the base decls are compatible: the RHS must be a subclass of
2824 // the LHS.
2825 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2826 return false;
2827
2828 // RHS must have a superset of the protocols in the LHS. If the LHS is not
2829 // protocol qualified at all, then we are good.
2830 if (!isa<ObjCQualifiedInterfaceType>(LHS))
2831 return true;
2832
2833 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
2834 // isn't a superset.
2835 if (!isa<ObjCQualifiedInterfaceType>(RHS))
2836 return true; // FIXME: should return false!
2837
2838 // Finally, we must have two protocol-qualified interfaces.
2839 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2840 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00002841
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002842 // All LHS protocols must have a presence on the RHS.
2843 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00002844
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002845 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
2846 LHSPE = LHSP->qual_end();
2847 LHSPI != LHSPE; LHSPI++) {
2848 bool RHSImplementsProtocol = false;
2849
2850 // If the RHS doesn't implement the protocol on the left, the types
2851 // are incompatible.
2852 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
2853 RHSPE = RHSP->qual_end();
2854 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
2855 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
2856 RHSImplementsProtocol = true;
2857 }
2858 // FIXME: For better diagnostics, consider passing back the protocol name.
2859 if (!RHSImplementsProtocol)
2860 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002861 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002862 // The RHS implements all protocols listed on the LHS.
2863 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002864}
2865
Steve Naroff389bf462009-02-12 17:52:19 +00002866bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
2867 // get the "pointed to" types
2868 const PointerType *LHSPT = LHS->getAsPointerType();
2869 const PointerType *RHSPT = RHS->getAsPointerType();
2870
2871 if (!LHSPT || !RHSPT)
2872 return false;
2873
2874 QualType lhptee = LHSPT->getPointeeType();
2875 QualType rhptee = RHSPT->getPointeeType();
2876 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2877 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2878 // ID acts sort of like void* for ObjC interfaces
2879 if (LHSIface && isObjCIdStructType(rhptee))
2880 return true;
2881 if (RHSIface && isObjCIdStructType(lhptee))
2882 return true;
2883 if (!LHSIface || !RHSIface)
2884 return false;
2885 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
2886 canAssignObjCInterfaces(RHSIface, LHSIface);
2887}
2888
Steve Naroffec0550f2007-10-15 20:41:53 +00002889/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2890/// both shall have the identically qualified version of a compatible type.
2891/// C99 6.2.7p1: Two types have compatible types if their types are the
2892/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00002893bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2894 return !mergeTypes(LHS, RHS).isNull();
2895}
2896
2897QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
2898 const FunctionType *lbase = lhs->getAsFunctionType();
2899 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00002900 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2901 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00002902 bool allLTypes = true;
2903 bool allRTypes = true;
2904
2905 // Check return type
2906 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
2907 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00002908 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
2909 allLTypes = false;
2910 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
2911 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00002912
2913 if (lproto && rproto) { // two C99 style function prototypes
2914 unsigned lproto_nargs = lproto->getNumArgs();
2915 unsigned rproto_nargs = rproto->getNumArgs();
2916
2917 // Compatible functions must have the same number of arguments
2918 if (lproto_nargs != rproto_nargs)
2919 return QualType();
2920
2921 // Variadic and non-variadic functions aren't compatible
2922 if (lproto->isVariadic() != rproto->isVariadic())
2923 return QualType();
2924
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002925 if (lproto->getTypeQuals() != rproto->getTypeQuals())
2926 return QualType();
2927
Eli Friedman3d815e72008-08-22 00:56:42 +00002928 // Check argument compatibility
2929 llvm::SmallVector<QualType, 10> types;
2930 for (unsigned i = 0; i < lproto_nargs; i++) {
2931 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
2932 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
2933 QualType argtype = mergeTypes(largtype, rargtype);
2934 if (argtype.isNull()) return QualType();
2935 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00002936 if (getCanonicalType(argtype) != getCanonicalType(largtype))
2937 allLTypes = false;
2938 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
2939 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00002940 }
2941 if (allLTypes) return lhs;
2942 if (allRTypes) return rhs;
2943 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002944 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00002945 }
2946
2947 if (lproto) allRTypes = false;
2948 if (rproto) allLTypes = false;
2949
Douglas Gregor72564e72009-02-26 23:50:07 +00002950 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00002951 if (proto) {
2952 if (proto->isVariadic()) return QualType();
2953 // Check that the types are compatible with the types that
2954 // would result from default argument promotions (C99 6.7.5.3p15).
2955 // The only types actually affected are promotable integer
2956 // types and floats, which would be passed as a different
2957 // type depending on whether the prototype is visible.
2958 unsigned proto_nargs = proto->getNumArgs();
2959 for (unsigned i = 0; i < proto_nargs; ++i) {
2960 QualType argTy = proto->getArgType(i);
2961 if (argTy->isPromotableIntegerType() ||
2962 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
2963 return QualType();
2964 }
2965
2966 if (allLTypes) return lhs;
2967 if (allRTypes) return rhs;
2968 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002969 proto->getNumArgs(), lproto->isVariadic(),
2970 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00002971 }
2972
2973 if (allLTypes) return lhs;
2974 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00002975 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00002976}
2977
2978QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00002979 // C++ [expr]: If an expression initially has the type "reference to T", the
2980 // type is adjusted to "T" prior to any further analysis, the expression
2981 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002982 // expression is an lvalue unless the reference is an rvalue reference and
2983 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00002984 // FIXME: C++ shouldn't be going through here! The rules are different
2985 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002986 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
2987 // shouldn't be going through here!
Eli Friedman3d815e72008-08-22 00:56:42 +00002988 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00002989 LHS = RT->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00002990 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00002991 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00002992
Eli Friedman3d815e72008-08-22 00:56:42 +00002993 QualType LHSCan = getCanonicalType(LHS),
2994 RHSCan = getCanonicalType(RHS);
2995
2996 // If two types are identical, they are compatible.
2997 if (LHSCan == RHSCan)
2998 return LHS;
2999
3000 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003001 // Note that we handle extended qualifiers later, in the
3002 // case for ExtQualType.
3003 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003004 return QualType();
3005
Fariborz Jahanianc8d2e772009-04-15 21:54:48 +00003006 Type::TypeClass LHSClass = LHSCan.getUnqualifiedType()->getTypeClass();
3007 Type::TypeClass RHSClass = RHSCan.getUnqualifiedType()->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003008
Chris Lattner1adb8832008-01-14 05:45:46 +00003009 // We want to consider the two function types to be the same for these
3010 // comparisons, just force one to the other.
3011 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3012 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003013
3014 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003015 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3016 LHSClass = Type::ConstantArray;
3017 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3018 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003019
Nate Begeman213541a2008-04-18 23:10:10 +00003020 // Canonicalize ExtVector -> Vector.
3021 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3022 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003023
Chris Lattnerb0489812008-04-07 06:38:24 +00003024 // Consider qualified interfaces and interfaces the same.
3025 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3026 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00003027
Chris Lattnera36a61f2008-04-07 05:43:21 +00003028 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003029 if (LHSClass != RHSClass) {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003030 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3031 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
Fariborz Jahanianc8d2e772009-04-15 21:54:48 +00003032
Steve Naroffd824c9c2009-04-14 15:11:46 +00003033 // 'id' and 'Class' act sort of like void* for ObjC interfaces
3034 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003035 return LHS;
Steve Naroffd824c9c2009-04-14 15:11:46 +00003036 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003037 return RHS;
3038
Steve Naroffbc76dd02008-12-10 22:14:21 +00003039 // ID is compatible with all qualified id types.
3040 if (LHS->isObjCQualifiedIdType()) {
3041 if (const PointerType *PT = RHS->getAsPointerType()) {
3042 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003043 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003044 return LHS;
3045 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3046 // Unfortunately, this API is part of Sema (which we don't have access
3047 // to. Need to refactor. The following check is insufficient, since we
3048 // need to make sure the class implements the protocol.
3049 if (pType->isObjCInterfaceType())
3050 return LHS;
3051 }
3052 }
3053 if (RHS->isObjCQualifiedIdType()) {
3054 if (const PointerType *PT = LHS->getAsPointerType()) {
3055 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003056 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003057 return RHS;
3058 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3059 // Unfortunately, this API is part of Sema (which we don't have access
3060 // to. Need to refactor. The following check is insufficient, since we
3061 // need to make sure the class implements the protocol.
3062 if (pType->isObjCInterfaceType())
3063 return RHS;
3064 }
3065 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003066 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3067 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003068 if (const EnumType* ETy = LHS->getAsEnumType()) {
3069 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3070 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003071 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003072 if (const EnumType* ETy = RHS->getAsEnumType()) {
3073 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3074 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003075 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003076
Eli Friedman3d815e72008-08-22 00:56:42 +00003077 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003078 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003079
Steve Naroff4a746782008-01-09 22:43:08 +00003080 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003081 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003082#define TYPE(Class, Base)
3083#define ABSTRACT_TYPE(Class, Base)
3084#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3085#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3086#include "clang/AST/TypeNodes.def"
3087 assert(false && "Non-canonical and dependent types shouldn't get here");
3088 return QualType();
3089
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003090 case Type::LValueReference:
3091 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003092 case Type::MemberPointer:
3093 assert(false && "C++ should never be in mergeTypes");
3094 return QualType();
3095
3096 case Type::IncompleteArray:
3097 case Type::VariableArray:
3098 case Type::FunctionProto:
3099 case Type::ExtVector:
3100 case Type::ObjCQualifiedInterface:
3101 assert(false && "Types are eliminated above");
3102 return QualType();
3103
Chris Lattner1adb8832008-01-14 05:45:46 +00003104 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003105 {
3106 // Merge two pointer types, while trying to preserve typedef info
3107 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3108 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3109 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3110 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003111 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3112 return LHS;
3113 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3114 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003115 return getPointerType(ResultType);
3116 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003117 case Type::BlockPointer:
3118 {
3119 // Merge two block pointer types, while trying to preserve typedef info
3120 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3121 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3122 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3123 if (ResultType.isNull()) return QualType();
3124 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3125 return LHS;
3126 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3127 return RHS;
3128 return getBlockPointerType(ResultType);
3129 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003130 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003131 {
3132 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3133 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3134 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3135 return QualType();
3136
3137 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3138 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3139 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3140 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003141 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3142 return LHS;
3143 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3144 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003145 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3146 ArrayType::ArraySizeModifier(), 0);
3147 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3148 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003149 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3150 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003151 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3152 return LHS;
3153 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3154 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003155 if (LVAT) {
3156 // FIXME: This isn't correct! But tricky to implement because
3157 // the array's size has to be the size of LHS, but the type
3158 // has to be different.
3159 return LHS;
3160 }
3161 if (RVAT) {
3162 // FIXME: This isn't correct! But tricky to implement because
3163 // the array's size has to be the size of RHS, but the type
3164 // has to be different.
3165 return RHS;
3166 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003167 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3168 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Chris Lattner61710852008-10-05 17:34:18 +00003169 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003170 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003171 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003172 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003173 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003174 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003175 // FIXME: Why are these compatible?
Steve Naroff389bf462009-02-12 17:52:19 +00003176 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3177 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003178 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003179 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003180 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003181 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003182 case Type::Complex:
3183 // Distinct complex types are incompatible.
3184 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003185 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003186 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003187 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3188 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003189 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003190 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003191 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003192 // FIXME: This should be type compatibility, e.g. whether
3193 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003194 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3195 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3196 if (LHSIface && RHSIface &&
3197 canAssignObjCInterfaces(LHSIface, RHSIface))
3198 return LHS;
3199
Eli Friedman3d815e72008-08-22 00:56:42 +00003200 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003201 }
Steve Naroffbc76dd02008-12-10 22:14:21 +00003202 case Type::ObjCQualifiedId:
3203 // Distinct qualified id's are not compatible.
3204 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003205 case Type::FixedWidthInt:
3206 // Distinct fixed-width integers are not compatible.
3207 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003208 case Type::ExtQual:
3209 // FIXME: ExtQual types can be compatible even if they're not
3210 // identical!
3211 return QualType();
3212 // First attempt at an implementation, but I'm not really sure it's
3213 // right...
3214#if 0
3215 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3216 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3217 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3218 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3219 return QualType();
3220 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3221 LHSBase = QualType(LQual->getBaseType(), 0);
3222 RHSBase = QualType(RQual->getBaseType(), 0);
3223 ResultType = mergeTypes(LHSBase, RHSBase);
3224 if (ResultType.isNull()) return QualType();
3225 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3226 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3227 return LHS;
3228 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3229 return RHS;
3230 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3231 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3232 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3233 return ResultType;
3234#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003235
3236 case Type::TemplateSpecialization:
3237 assert(false && "Dependent types have no size");
3238 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003239 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003240
3241 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003242}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003243
Chris Lattner5426bf62008-04-07 07:01:58 +00003244//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003245// Integer Predicates
3246//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003247
Eli Friedmanad74a752008-06-28 06:23:08 +00003248unsigned ASTContext::getIntWidth(QualType T) {
3249 if (T == BoolTy)
3250 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003251 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3252 return FWIT->getWidth();
3253 }
3254 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003255 return (unsigned)getTypeSize(T);
3256}
3257
3258QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3259 assert(T->isSignedIntegerType() && "Unexpected type");
3260 if (const EnumType* ETy = T->getAsEnumType())
3261 T = ETy->getDecl()->getIntegerType();
3262 const BuiltinType* BTy = T->getAsBuiltinType();
3263 assert (BTy && "Unexpected signed integer type");
3264 switch (BTy->getKind()) {
3265 case BuiltinType::Char_S:
3266 case BuiltinType::SChar:
3267 return UnsignedCharTy;
3268 case BuiltinType::Short:
3269 return UnsignedShortTy;
3270 case BuiltinType::Int:
3271 return UnsignedIntTy;
3272 case BuiltinType::Long:
3273 return UnsignedLongTy;
3274 case BuiltinType::LongLong:
3275 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003276 case BuiltinType::Int128:
3277 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003278 default:
3279 assert(0 && "Unexpected signed integer type");
3280 return QualType();
3281 }
3282}
3283
Douglas Gregor2cf26342009-04-09 22:27:44 +00003284ExternalASTSource::~ExternalASTSource() { }
3285
3286void ExternalASTSource::PrintStats() { }