blob: 1144fcd0d97096ee44684353f9387d7f93715034 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000016#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000017#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000020#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000021#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000023#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000024#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000026#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000028#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000029#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000030#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000031#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000032#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000033#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000034#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000035#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000036#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000037
Chris Lattnerddc135e2006-11-10 06:34:16 +000038using namespace clang;
39
Douglas Gregor9672f922010-07-03 00:47:00 +000040unsigned ASTContext::NumImplicitDefaultConstructors;
41unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000042unsigned ASTContext::NumImplicitCopyConstructors;
43unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000044unsigned ASTContext::NumImplicitMoveConstructors;
45unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000046unsigned ASTContext::NumImplicitCopyAssignmentOperators;
47unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000048unsigned ASTContext::NumImplicitMoveAssignmentOperators;
49unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000050unsigned ASTContext::NumImplicitDestructors;
51unsigned ASTContext::NumImplicitDestructorsDeclared;
52
Steve Naroff0af91202007-04-27 21:51:21 +000053enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000054 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000055};
56
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000057RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000058 if (!CommentsLoaded && ExternalSource) {
59 ExternalSource->ReadComments();
60 CommentsLoaded = true;
61 }
62
63 assert(D);
64
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000065 // User can not attach documentation to implicit declarations.
66 if (D->isImplicit())
67 return NULL;
68
Dmitri Gribenkob2610882012-08-14 17:17:18 +000069 // User can not attach documentation to implicit instantiations.
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000070 // FIXME: all these implicit instantiations shoud be marked as implicit
71 // declarations and get caught by condition above.
Dmitri Gribenkob2610882012-08-14 17:17:18 +000072 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
74 return NULL;
75 }
76
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000077 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
78 if (VD->isStaticDataMember() &&
79 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
80 return NULL;
81 }
82
83 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
84 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
85 return NULL;
86 }
87
88 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
89 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
90 return NULL;
91 }
92
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000093 // TODO: handle comments for function parameters properly.
94 if (isa<ParmVarDecl>(D))
95 return NULL;
96
Dmitri Gribenko34df2202012-07-31 22:37:06 +000097 // TODO: we could look up template parameter documentation in the template
98 // documentation.
99 if (isa<TemplateTypeParmDecl>(D) ||
100 isa<NonTypeTemplateParmDecl>(D) ||
101 isa<TemplateTemplateParmDecl>(D))
102 return NULL;
103
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000104 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000105
106 // If there are no comments anywhere, we won't find anything.
107 if (RawComments.empty())
108 return NULL;
109
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000110 // Find declaration location.
111 // For Objective-C declarations we generally don't expect to have multiple
112 // declarators, thus use declaration starting location as the "declaration
113 // location".
114 // For all other declarations multiple declarators are used quite frequently,
115 // so we use the location of the identifier as the "declaration location".
116 SourceLocation DeclLoc;
117 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000118 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000119 isa<RedeclarableTemplateDecl>(D) ||
120 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000121 DeclLoc = D->getLocStart();
122 else
123 DeclLoc = D->getLocation();
124
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000125 // If the declaration doesn't map directly to a location in a file, we
126 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000127 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
128 return NULL;
129
130 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000131 ArrayRef<RawComment *>::iterator Comment;
132 {
133 // When searching for comments during parsing, the comment we are looking
134 // for is usually among the last two comments we parsed -- check them
135 // first.
136 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
137 BeforeThanCompare<RawComment> Compare(SourceMgr);
138 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
139 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
140 if (!Found && RawComments.size() >= 2) {
141 MaybeBeforeDecl--;
142 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
143 }
144
145 if (Found) {
146 Comment = MaybeBeforeDecl + 1;
147 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
148 &CommentAtDeclLoc, Compare));
149 } else {
150 // Slow path.
151 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
152 &CommentAtDeclLoc, Compare);
153 }
154 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000155
156 // Decompose the location for the declaration and find the beginning of the
157 // file buffer.
158 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
159
160 // First check whether we have a trailing comment.
161 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000162 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000163 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000164 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000165 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000166 // Check that Doxygen trailing comment comes after the declaration, starts
167 // on the same line and in the same file as the declaration.
168 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
169 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
170 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
171 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000172 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000173 }
174 }
175
176 // The comment just after the declaration was not a trailing comment.
177 // Let's look at the previous comment.
178 if (Comment == RawComments.begin())
179 return NULL;
180 --Comment;
181
182 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000183 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000184 return NULL;
185
186 // Decompose the end of the comment.
187 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000188 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000189
190 // If the comment and the declaration aren't in the same file, then they
191 // aren't related.
192 if (DeclLocDecomp.first != CommentEndDecomp.first)
193 return NULL;
194
195 // Get the corresponding buffer.
196 bool Invalid = false;
197 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
198 &Invalid).data();
199 if (Invalid)
200 return NULL;
201
202 // Extract text between the comment and declaration.
203 StringRef Text(Buffer + CommentEndDecomp.second,
204 DeclLocDecomp.second - CommentEndDecomp.second);
205
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000206 // There should be no other declarations or preprocessor directives between
207 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000208 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 return NULL;
210
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000211 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000212}
213
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000214namespace {
215/// If we have a 'templated' declaration for a template, adjust 'D' to
216/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000217/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000218const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000219 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000220 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000221 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000222 return FTD;
223
224 // Nothing to do if function is not an implicit instantiation.
225 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
226 return D;
227
228 // Function is an implicit instantiation of a function template?
229 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
230 return FTD;
231
232 // Function is instantiated from a member definition of a class template?
233 if (const FunctionDecl *MemberDecl =
234 FD->getInstantiatedFromMemberFunction())
235 return MemberDecl;
236
237 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000238 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000239 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
240 // Static data member is instantiated from a member definition of a class
241 // template?
242 if (VD->isStaticDataMember())
243 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
244 return MemberDecl;
245
246 return D;
247 }
248 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
249 // Is this class declaration part of a class template?
250 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
251 return CTD;
252
253 // Class is an implicit instantiation of a class template or partial
254 // specialization?
255 if (const ClassTemplateSpecializationDecl *CTSD =
256 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
257 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
258 return D;
259 llvm::PointerUnion<ClassTemplateDecl *,
260 ClassTemplatePartialSpecializationDecl *>
261 PU = CTSD->getSpecializedTemplateOrPartial();
262 return PU.is<ClassTemplateDecl*>() ?
263 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
264 static_cast<const Decl*>(
265 PU.get<ClassTemplatePartialSpecializationDecl *>());
266 }
267
268 // Class is instantiated from a member definition of a class template?
269 if (const MemberSpecializationInfo *Info =
270 CRD->getMemberSpecializationInfo())
271 return Info->getInstantiatedFrom();
272
273 return D;
274 }
275 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
276 // Enum is instantiated from a member definition of a class template?
277 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
278 return MemberDecl;
279
280 return D;
281 }
282 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000283 return D;
284}
285} // unnamed namespace
286
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000287const RawComment *ASTContext::getRawCommentForAnyRedecl(
288 const Decl *D,
289 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000290 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000291
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000292 // Check whether we have cached a comment for this declaration already.
293 {
294 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
295 RedeclComments.find(D);
296 if (Pos != RedeclComments.end()) {
297 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000298 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
299 if (OriginalDecl)
300 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000301 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000302 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000303 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000304 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000305
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000306 // Search for comments attached to declarations in the redeclaration chain.
307 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000308 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000309 for (Decl::redecl_iterator I = D->redecls_begin(),
310 E = D->redecls_end();
311 I != E; ++I) {
312 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
313 RedeclComments.find(*I);
314 if (Pos != RedeclComments.end()) {
315 const RawCommentAndCacheFlags &Raw = Pos->second;
316 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
317 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000318 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000319 break;
320 }
321 } else {
322 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000323 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000324 RawCommentAndCacheFlags Raw;
325 if (RC) {
326 Raw.setRaw(RC);
327 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
328 } else
329 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000330 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000331 RedeclComments[*I] = Raw;
332 if (RC)
333 break;
334 }
335 }
336
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000337 // If we found a comment, it should be a documentation comment.
338 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000339
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000340 if (OriginalDecl)
341 *OriginalDecl = OriginalDeclForRC;
342
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000343 // Update cache for every declaration in the redeclaration chain.
344 RawCommentAndCacheFlags Raw;
345 Raw.setRaw(RC);
346 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348
349 for (Decl::redecl_iterator I = D->redecls_begin(),
350 E = D->redecls_end();
351 I != E; ++I) {
352 RawCommentAndCacheFlags &R = RedeclComments[*I];
353 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
354 R = Raw;
355 }
356
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000357 return RC;
358}
359
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000360comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000361 D = adjustDeclToTemplate(D);
362 const Decl *Canonical = D->getCanonicalDecl();
363 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
364 ParsedComments.find(Canonical);
365 if (Pos != ParsedComments.end())
366 return Pos->second;
367
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000368 const Decl *OriginalDecl;
369 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000370 if (!RC)
371 return NULL;
372
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000373 // If the RawComment was attached to other redeclaration of this Decl, we
374 // should parse the comment in context of that other Decl. This is important
375 // because comments can contain references to parameter names which can be
376 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000377 if (D != OriginalDecl)
378 return getCommentForDecl(OriginalDecl);
379
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000380 comments::FullComment *FC = RC->parse(*this, D);
381 ParsedComments[Canonical] = FC;
382 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000383}
384
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000385void
386ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
387 TemplateTemplateParmDecl *Parm) {
388 ID.AddInteger(Parm->getDepth());
389 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000390 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000391
392 TemplateParameterList *Params = Parm->getTemplateParameters();
393 ID.AddInteger(Params->size());
394 for (TemplateParameterList::const_iterator P = Params->begin(),
395 PEnd = Params->end();
396 P != PEnd; ++P) {
397 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
398 ID.AddInteger(0);
399 ID.AddBoolean(TTP->isParameterPack());
400 continue;
401 }
402
403 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
404 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000405 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000406 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000407 if (NTTP->isExpandedParameterPack()) {
408 ID.AddBoolean(true);
409 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000410 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
411 QualType T = NTTP->getExpansionType(I);
412 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
413 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000414 } else
415 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000416 continue;
417 }
418
419 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
420 ID.AddInteger(2);
421 Profile(ID, TTP);
422 }
423}
424
425TemplateTemplateParmDecl *
426ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000427 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000428 // Check if we already have a canonical template template parameter.
429 llvm::FoldingSetNodeID ID;
430 CanonicalTemplateTemplateParm::Profile(ID, TTP);
431 void *InsertPos = 0;
432 CanonicalTemplateTemplateParm *Canonical
433 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
434 if (Canonical)
435 return Canonical->getParam();
436
437 // Build a canonical template parameter list.
438 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000439 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000440 CanonParams.reserve(Params->size());
441 for (TemplateParameterList::const_iterator P = Params->begin(),
442 PEnd = Params->end();
443 P != PEnd; ++P) {
444 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
445 CanonParams.push_back(
446 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000447 SourceLocation(),
448 SourceLocation(),
449 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000450 TTP->getIndex(), 0, false,
451 TTP->isParameterPack()));
452 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000453 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
454 QualType T = getCanonicalType(NTTP->getType());
455 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
456 NonTypeTemplateParmDecl *Param;
457 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000458 SmallVector<QualType, 2> ExpandedTypes;
459 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000460 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
461 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
462 ExpandedTInfos.push_back(
463 getTrivialTypeSourceInfo(ExpandedTypes.back()));
464 }
465
466 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000467 SourceLocation(),
468 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000469 NTTP->getDepth(),
470 NTTP->getPosition(), 0,
471 T,
472 TInfo,
473 ExpandedTypes.data(),
474 ExpandedTypes.size(),
475 ExpandedTInfos.data());
476 } else {
477 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000478 SourceLocation(),
479 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000480 NTTP->getDepth(),
481 NTTP->getPosition(), 0,
482 T,
483 NTTP->isParameterPack(),
484 TInfo);
485 }
486 CanonParams.push_back(Param);
487
488 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000489 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
490 cast<TemplateTemplateParmDecl>(*P)));
491 }
492
493 TemplateTemplateParmDecl *CanonTTP
494 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
495 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000496 TTP->getPosition(),
497 TTP->isParameterPack(),
498 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000499 TemplateParameterList::Create(*this, SourceLocation(),
500 SourceLocation(),
501 CanonParams.data(),
502 CanonParams.size(),
503 SourceLocation()));
504
505 // Get the new insert position for the node we care about.
506 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
507 assert(Canonical == 0 && "Shouldn't be in the map!");
508 (void)Canonical;
509
510 // Create the canonical template template parameter entry.
511 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
512 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
513 return CanonTTP;
514}
515
Charles Davis53c59df2010-08-16 03:33:14 +0000516CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000517 if (!LangOpts.CPlusPlus) return 0;
518
Charles Davis6bcb07a2010-08-19 02:18:14 +0000519 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000520 case CXXABI_ARM:
521 return CreateARMCXXABI(*this);
522 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000523 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000524 case CXXABI_Microsoft:
525 return CreateMicrosoftCXXABI(*this);
526 }
David Blaikie8a40f702012-01-17 06:56:22 +0000527 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000528}
529
Douglas Gregore8bbc122011-09-02 00:18:52 +0000530static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000531 const LangOptions &LOpts) {
532 if (LOpts.FakeAddressSpaceMap) {
533 // The fake address space map must have a distinct entry for each
534 // language-specific address space.
535 static const unsigned FakeAddrSpaceMap[] = {
536 1, // opencl_global
537 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000538 3, // opencl_constant
539 4, // cuda_device
540 5, // cuda_constant
541 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000542 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000543 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000544 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000545 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000546 }
547}
548
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000549ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000550 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000551 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000552 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000553 unsigned size_reserve,
554 bool DelayInitialization)
555 : FunctionProtoTypes(this_()),
556 TemplateSpecializationTypes(this_()),
557 DependentTemplateSpecializationTypes(this_()),
558 SubstTemplateTemplateParmPacks(this_()),
559 GlobalNestedNameSpecifier(0),
560 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000561 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000562 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000563 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000564 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000565 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
566 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
567 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000568 NullTypeSourceInfo(QualType()),
569 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000570 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000571 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000572 Idents(idents), Selectors(sels),
573 BuiltinInfo(builtins),
574 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000575 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000576 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000577 LastSDM(0, 0),
578 UniqueBlockByRefTypeID(0)
579{
Mike Stump11289f42009-09-09 15:08:12 +0000580 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000581 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000582
583 if (!DelayInitialization) {
584 assert(t && "No target supplied for ASTContext initialization");
585 InitBuiltinTypes(*t);
586 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000587}
588
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000589ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000590 // Release the DenseMaps associated with DeclContext objects.
591 // FIXME: Is this the ideal solution?
592 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000593
Douglas Gregor5b11d492010-07-25 17:53:33 +0000594 // Call all of the deallocation functions.
595 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
596 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000597
Ted Kremenek076baeb2010-06-08 23:00:58 +0000598 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000599 // because they can contain DenseMaps.
600 for (llvm::DenseMap<const ObjCContainerDecl*,
601 const ASTRecordLayout*>::iterator
602 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
603 // Increment in loop to prevent using deallocated memory.
604 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
605 R->Destroy(*this);
606
Ted Kremenek076baeb2010-06-08 23:00:58 +0000607 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
608 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
609 // Increment in loop to prevent using deallocated memory.
610 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
611 R->Destroy(*this);
612 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000613
614 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
615 AEnd = DeclAttrs.end();
616 A != AEnd; ++A)
617 A->second->~AttrVec();
618}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000619
Douglas Gregor1a809332010-05-23 18:26:36 +0000620void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
621 Deallocations.push_back(std::make_pair(Callback, Data));
622}
623
Mike Stump11289f42009-09-09 15:08:12 +0000624void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000625ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000626 ExternalSource.reset(Source.take());
627}
628
Chris Lattner4eb445d2007-01-26 01:27:23 +0000629void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000630 llvm::errs() << "\n*** AST Context Stats:\n";
631 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000632
Douglas Gregora30d0462009-05-26 14:40:08 +0000633 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000634#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000635#define ABSTRACT_TYPE(Name, Parent)
636#include "clang/AST/TypeNodes.def"
637 0 // Extra
638 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000639
Chris Lattner4eb445d2007-01-26 01:27:23 +0000640 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
641 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000642 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000643 }
644
Douglas Gregora30d0462009-05-26 14:40:08 +0000645 unsigned Idx = 0;
646 unsigned TotalBytes = 0;
647#define TYPE(Name, Parent) \
648 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000649 llvm::errs() << " " << counts[Idx] << " " << #Name \
650 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000651 TotalBytes += counts[Idx] * sizeof(Name##Type); \
652 ++Idx;
653#define ABSTRACT_TYPE(Name, Parent)
654#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000655
Chandler Carruth3c147a72011-07-04 05:32:14 +0000656 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
657
Douglas Gregor7454c562010-07-02 20:37:36 +0000658 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000659 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
660 << NumImplicitDefaultConstructors
661 << " implicit default constructors created\n";
662 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
663 << NumImplicitCopyConstructors
664 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000665 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000666 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
667 << NumImplicitMoveConstructors
668 << " implicit move constructors created\n";
669 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
670 << NumImplicitCopyAssignmentOperators
671 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000672 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000673 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
674 << NumImplicitMoveAssignmentOperators
675 << " implicit move assignment operators created\n";
676 llvm::errs() << NumImplicitDestructorsDeclared << "/"
677 << NumImplicitDestructors
678 << " implicit destructors created\n";
679
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000680 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000681 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000682 ExternalSource->PrintStats();
683 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000684
Douglas Gregor5b11d492010-07-25 17:53:33 +0000685 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000686}
687
Douglas Gregor801c99d2011-08-12 06:49:56 +0000688TypedefDecl *ASTContext::getInt128Decl() const {
689 if (!Int128Decl) {
690 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
691 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
692 getTranslationUnitDecl(),
693 SourceLocation(),
694 SourceLocation(),
695 &Idents.get("__int128_t"),
696 TInfo);
697 }
698
699 return Int128Decl;
700}
701
702TypedefDecl *ASTContext::getUInt128Decl() const {
703 if (!UInt128Decl) {
704 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
705 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
706 getTranslationUnitDecl(),
707 SourceLocation(),
708 SourceLocation(),
709 &Idents.get("__uint128_t"),
710 TInfo);
711 }
712
713 return UInt128Decl;
714}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000715
John McCall48f2d582009-10-23 23:03:21 +0000716void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000717 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000718 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000719 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000720}
721
Douglas Gregore8bbc122011-09-02 00:18:52 +0000722void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
723 assert((!this->Target || this->Target == &Target) &&
724 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000725 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000726
Douglas Gregore8bbc122011-09-02 00:18:52 +0000727 this->Target = &Target;
728
729 ABI.reset(createCXXABI(Target));
730 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
731
Chris Lattner970e54e2006-11-12 00:37:36 +0000732 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000733 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000734
Chris Lattner970e54e2006-11-12 00:37:36 +0000735 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000736 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000737 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000738 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000739 InitBuiltinType(CharTy, BuiltinType::Char_S);
740 else
741 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000742 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000743 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
744 InitBuiltinType(ShortTy, BuiltinType::Short);
745 InitBuiltinType(IntTy, BuiltinType::Int);
746 InitBuiltinType(LongTy, BuiltinType::Long);
747 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000748
Chris Lattner970e54e2006-11-12 00:37:36 +0000749 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000750 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
751 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
752 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
753 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
754 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000755
Chris Lattner970e54e2006-11-12 00:37:36 +0000756 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000757 InitBuiltinType(FloatTy, BuiltinType::Float);
758 InitBuiltinType(DoubleTy, BuiltinType::Double);
759 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000760
Chris Lattnerf122cef2009-04-30 02:43:43 +0000761 // GNU extension, 128-bit integers.
762 InitBuiltinType(Int128Ty, BuiltinType::Int128);
763 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
764
Chris Lattnerad3467e2010-12-25 23:25:43 +0000765 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000766 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000767 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
768 else // -fshort-wchar makes wchar_t be unsigned.
769 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
770 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000771 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000772
James Molloy36365542012-05-04 10:55:22 +0000773 WIntTy = getFromTargetType(Target.getWIntType());
774
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000775 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
776 InitBuiltinType(Char16Ty, BuiltinType::Char16);
777 else // C99
778 Char16Ty = getFromTargetType(Target.getChar16Type());
779
780 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
781 InitBuiltinType(Char32Ty, BuiltinType::Char32);
782 else // C99
783 Char32Ty = getFromTargetType(Target.getChar32Type());
784
Douglas Gregor4619e432008-12-05 23:32:09 +0000785 // Placeholder type for type-dependent expressions whose type is
786 // completely unknown. No code should ever check a type against
787 // DependentTy and users should never see it; however, it is here to
788 // help diagnose failures to properly check for type-dependent
789 // expressions.
790 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000791
John McCall36e7fe32010-10-12 00:20:44 +0000792 // Placeholder type for functions.
793 InitBuiltinType(OverloadTy, BuiltinType::Overload);
794
John McCall0009fcc2011-04-26 20:42:42 +0000795 // Placeholder type for bound members.
796 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
797
John McCall526ab472011-10-25 17:37:35 +0000798 // Placeholder type for pseudo-objects.
799 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
800
John McCall31996342011-04-07 08:22:57 +0000801 // "any" type; useful for debugger-like clients.
802 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
803
John McCall8a6b59a2011-10-17 18:09:15 +0000804 // Placeholder type for unbridged ARC casts.
805 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
806
Chris Lattner970e54e2006-11-12 00:37:36 +0000807 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000808 FloatComplexTy = getComplexType(FloatTy);
809 DoubleComplexTy = getComplexType(DoubleTy);
810 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000811
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000812 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000813 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
814 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000815 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000816
817 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000818 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
819 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000820
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000821 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000822
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000823 // void * type
824 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000825
826 // nullptr type (C++0x 2.14.7)
827 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000828
829 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
830 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000831
832 // Builtin type used to help define __builtin_va_list.
833 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000834}
835
David Blaikie9c902b52011-09-25 23:23:43 +0000836DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000837 return SourceMgr.getDiagnostics();
838}
839
Douglas Gregor561eceb2010-08-30 16:49:28 +0000840AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
841 AttrVec *&Result = DeclAttrs[D];
842 if (!Result) {
843 void *Mem = Allocate(sizeof(AttrVec));
844 Result = new (Mem) AttrVec;
845 }
846
847 return *Result;
848}
849
850/// \brief Erase the attributes corresponding to the given declaration.
851void ASTContext::eraseDeclAttrs(const Decl *D) {
852 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
853 if (Pos != DeclAttrs.end()) {
854 Pos->second->~AttrVec();
855 DeclAttrs.erase(Pos);
856 }
857}
858
Douglas Gregor86d142a2009-10-08 07:24:58 +0000859MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000860ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000861 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000862 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000863 = InstantiatedFromStaticDataMember.find(Var);
864 if (Pos == InstantiatedFromStaticDataMember.end())
865 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000866
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000867 return Pos->second;
868}
869
Mike Stump11289f42009-09-09 15:08:12 +0000870void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000871ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000872 TemplateSpecializationKind TSK,
873 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000874 assert(Inst->isStaticDataMember() && "Not a static data member");
875 assert(Tmpl->isStaticDataMember() && "Not a static data member");
876 assert(!InstantiatedFromStaticDataMember[Inst] &&
877 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000878 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000879 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000880}
881
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000882FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
883 const FunctionDecl *FD){
884 assert(FD && "Specialization is 0");
885 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000886 = ClassScopeSpecializationPattern.find(FD);
887 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000888 return 0;
889
890 return Pos->second;
891}
892
893void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
894 FunctionDecl *Pattern) {
895 assert(FD && "Specialization is 0");
896 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000897 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000898}
899
John McCalle61f2ba2009-11-18 02:36:19 +0000900NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000901ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000902 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000903 = InstantiatedFromUsingDecl.find(UUD);
904 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000905 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000906
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000907 return Pos->second;
908}
909
910void
John McCallb96ec562009-12-04 22:46:56 +0000911ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
912 assert((isa<UsingDecl>(Pattern) ||
913 isa<UnresolvedUsingValueDecl>(Pattern) ||
914 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
915 "pattern decl is not a using decl");
916 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
917 InstantiatedFromUsingDecl[Inst] = Pattern;
918}
919
920UsingShadowDecl *
921ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
922 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
923 = InstantiatedFromUsingShadowDecl.find(Inst);
924 if (Pos == InstantiatedFromUsingShadowDecl.end())
925 return 0;
926
927 return Pos->second;
928}
929
930void
931ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
932 UsingShadowDecl *Pattern) {
933 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
934 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000935}
936
Anders Carlsson5da84842009-09-01 04:26:58 +0000937FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
938 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
939 = InstantiatedFromUnnamedFieldDecl.find(Field);
940 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
941 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000942
Anders Carlsson5da84842009-09-01 04:26:58 +0000943 return Pos->second;
944}
945
946void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
947 FieldDecl *Tmpl) {
948 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
949 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
950 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
951 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000952
Anders Carlsson5da84842009-09-01 04:26:58 +0000953 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
954}
955
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000956bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
957 const FieldDecl *LastFD) const {
958 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000959 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000960}
961
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000962bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
963 const FieldDecl *LastFD) const {
964 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000965 FD->getBitWidthValue(*this) == 0 &&
966 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000967}
968
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000969bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
970 const FieldDecl *LastFD) const {
971 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000972 FD->getBitWidthValue(*this) &&
973 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000974}
975
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000976bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000977 const FieldDecl *LastFD) const {
978 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000979 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000980}
981
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000982bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000983 const FieldDecl *LastFD) const {
984 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000985 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000986}
987
Douglas Gregor832940b2010-03-02 23:58:15 +0000988ASTContext::overridden_cxx_method_iterator
989ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
990 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
991 = OverriddenMethods.find(Method);
992 if (Pos == OverriddenMethods.end())
993 return 0;
994
995 return Pos->second.begin();
996}
997
998ASTContext::overridden_cxx_method_iterator
999ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1000 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1001 = OverriddenMethods.find(Method);
1002 if (Pos == OverriddenMethods.end())
1003 return 0;
1004
1005 return Pos->second.end();
1006}
1007
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001008unsigned
1009ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1010 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1011 = OverriddenMethods.find(Method);
1012 if (Pos == OverriddenMethods.end())
1013 return 0;
1014
1015 return Pos->second.size();
1016}
1017
Douglas Gregor832940b2010-03-02 23:58:15 +00001018void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1019 const CXXMethodDecl *Overridden) {
1020 OverriddenMethods[Method].push_back(Overridden);
1021}
1022
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001023void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1024 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1025 assert(!Import->isFromASTFile() && "Non-local import declaration");
1026 if (!FirstLocalImport) {
1027 FirstLocalImport = Import;
1028 LastLocalImport = Import;
1029 return;
1030 }
1031
1032 LastLocalImport->NextLocalImport = Import;
1033 LastLocalImport = Import;
1034}
1035
Chris Lattner53cfe802007-07-18 17:52:12 +00001036//===----------------------------------------------------------------------===//
1037// Type Sizing and Analysis
1038//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001039
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001040/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1041/// scalar floating point type.
1042const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001043 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001044 assert(BT && "Not a floating point type!");
1045 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001046 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001047 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001048 case BuiltinType::Float: return Target->getFloatFormat();
1049 case BuiltinType::Double: return Target->getDoubleFormat();
1050 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001051 }
1052}
1053
Ken Dyck160146e2010-01-27 17:10:57 +00001054/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001055/// specified decl. Note that bitfields do not have a valid alignment, so
1056/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001057/// If @p RefAsPointee, references are treated like their underlying type
1058/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001059CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001060 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001061
John McCall94268702010-10-08 18:24:19 +00001062 bool UseAlignAttrOnly = false;
1063 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1064 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001065
John McCall94268702010-10-08 18:24:19 +00001066 // __attribute__((aligned)) can increase or decrease alignment
1067 // *except* on a struct or struct member, where it only increases
1068 // alignment unless 'packed' is also specified.
1069 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001070 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001071 // ignore that possibility; Sema should diagnose it.
1072 if (isa<FieldDecl>(D)) {
1073 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1074 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1075 } else {
1076 UseAlignAttrOnly = true;
1077 }
1078 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001079 else if (isa<FieldDecl>(D))
1080 UseAlignAttrOnly =
1081 D->hasAttr<PackedAttr>() ||
1082 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001083
John McCall4e819612011-01-20 07:57:12 +00001084 // If we're using the align attribute only, just ignore everything
1085 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001086 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001087 // do nothing
1088
John McCall94268702010-10-08 18:24:19 +00001089 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001090 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001091 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001092 if (RefAsPointee)
1093 T = RT->getPointeeType();
1094 else
1095 T = getPointerType(RT->getPointeeType());
1096 }
1097 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001098 // Adjust alignments of declarations with array type by the
1099 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001100 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001101 const ArrayType *arrayType;
1102 if (MinWidth && (arrayType = getAsArrayType(T))) {
1103 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001104 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001105 else if (isa<ConstantArrayType>(arrayType) &&
1106 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001107 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001108
John McCall33ddac02011-01-19 10:06:00 +00001109 // Walk through any array types while we're at it.
1110 T = getBaseElementType(arrayType);
1111 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001112 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001113 }
John McCall4e819612011-01-20 07:57:12 +00001114
1115 // Fields can be subject to extra alignment constraints, like if
1116 // the field is packed, the struct is packed, or the struct has a
1117 // a max-field-alignment constraint (#pragma pack). So calculate
1118 // the actual alignment of the field within the struct, and then
1119 // (as we're expected to) constrain that by the alignment of the type.
1120 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1121 // So calculate the alignment of the field.
1122 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1123
1124 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001125 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001126
1127 // Use the GCD of that and the offset within the record.
1128 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1129 if (offset > 0) {
1130 // Alignment is always a power of 2, so the GCD will be a power of 2,
1131 // which means we get to do this crazy thing instead of Euclid's.
1132 uint64_t lowBitOfOffset = offset & (~offset + 1);
1133 if (lowBitOfOffset < fieldAlign)
1134 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1135 }
1136
1137 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001138 }
Chris Lattner68061312009-01-24 21:53:27 +00001139 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001140
Ken Dyckcc56c542011-01-15 18:38:59 +00001141 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001142}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001143
John McCallf1249922012-08-21 04:10:00 +00001144// getTypeInfoDataSizeInChars - Return the size of a type, in
1145// chars. If the type is a record, its data size is returned. This is
1146// the size of the memcpy that's performed when assigning this type
1147// using a trivial copy/move assignment operator.
1148std::pair<CharUnits, CharUnits>
1149ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1150 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1151
1152 // In C++, objects can sometimes be allocated into the tail padding
1153 // of a base-class subobject. We decide whether that's possible
1154 // during class layout, so here we can just trust the layout results.
1155 if (getLangOpts().CPlusPlus) {
1156 if (const RecordType *RT = T->getAs<RecordType>()) {
1157 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1158 sizeAndAlign.first = layout.getDataSize();
1159 }
1160 }
1161
1162 return sizeAndAlign;
1163}
1164
John McCall87fe5d52010-05-20 01:18:31 +00001165std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001166ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001167 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001168 return std::make_pair(toCharUnitsFromBits(Info.first),
1169 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001170}
1171
1172std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001173ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001174 return getTypeInfoInChars(T.getTypePtr());
1175}
1176
Daniel Dunbarc6475872012-03-09 04:12:54 +00001177std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1178 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1179 if (it != MemoizedTypeInfo.end())
1180 return it->second;
1181
1182 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1183 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1184 return Info;
1185}
1186
1187/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1188/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001189///
1190/// FIXME: Pointers into different addr spaces could have different sizes and
1191/// alignment requirements: getPointerInfo should take an AddrSpace, this
1192/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001193std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001194ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001195 uint64_t Width=0;
1196 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001197 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001198#define TYPE(Class, Base)
1199#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001200#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001201#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1202#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001203 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001204
Chris Lattner355332d2007-07-13 22:27:08 +00001205 case Type::FunctionNoProto:
1206 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001207 // GCC extension: alignof(function) = 32 bits
1208 Width = 0;
1209 Align = 32;
1210 break;
1211
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001212 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001213 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001214 Width = 0;
1215 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1216 break;
1217
Steve Naroff5c131802007-08-30 01:06:46 +00001218 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001219 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001220
Chris Lattner37e05872008-03-05 18:54:05 +00001221 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001222 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001223 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1224 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001225 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001226 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001227 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001228 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001229 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001230 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001231 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001232 const VectorType *VT = cast<VectorType>(T);
1233 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1234 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001235 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001236 // If the alignment is not a power of 2, round up to the next power of 2.
1237 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001238 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001239 Align = llvm::NextPowerOf2(Align);
1240 Width = llvm::RoundUpToAlignment(Width, Align);
1241 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001242 // Adjust the alignment based on the target max.
1243 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1244 if (TargetVectorAlign && TargetVectorAlign < Align)
1245 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001246 break;
1247 }
Chris Lattner647fb222007-07-18 18:26:58 +00001248
Chris Lattner7570e9c2008-03-08 08:52:55 +00001249 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001250 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001251 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001252 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001253 // GCC extension: alignof(void) = 8 bits.
1254 Width = 0;
1255 Align = 8;
1256 break;
1257
Chris Lattner6a4f7452007-12-19 19:23:28 +00001258 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001259 Width = Target->getBoolWidth();
1260 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001261 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001262 case BuiltinType::Char_S:
1263 case BuiltinType::Char_U:
1264 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001265 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001266 Width = Target->getCharWidth();
1267 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001268 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001269 case BuiltinType::WChar_S:
1270 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001271 Width = Target->getWCharWidth();
1272 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001273 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001274 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001275 Width = Target->getChar16Width();
1276 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001277 break;
1278 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001279 Width = Target->getChar32Width();
1280 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001281 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001282 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001283 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001284 Width = Target->getShortWidth();
1285 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001286 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001287 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001288 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001289 Width = Target->getIntWidth();
1290 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001291 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001292 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001293 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001294 Width = Target->getLongWidth();
1295 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001296 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001297 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001298 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001299 Width = Target->getLongLongWidth();
1300 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001301 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001302 case BuiltinType::Int128:
1303 case BuiltinType::UInt128:
1304 Width = 128;
1305 Align = 128; // int128_t is 128-bit aligned on all targets.
1306 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001307 case BuiltinType::Half:
1308 Width = Target->getHalfWidth();
1309 Align = Target->getHalfAlign();
1310 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001311 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001312 Width = Target->getFloatWidth();
1313 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001314 break;
1315 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001316 Width = Target->getDoubleWidth();
1317 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001318 break;
1319 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001320 Width = Target->getLongDoubleWidth();
1321 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001322 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001323 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001324 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1325 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001326 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001327 case BuiltinType::ObjCId:
1328 case BuiltinType::ObjCClass:
1329 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001330 Width = Target->getPointerWidth(0);
1331 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001332 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001333 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001334 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001335 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001336 Width = Target->getPointerWidth(0);
1337 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001338 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001339 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001340 unsigned AS = getTargetAddressSpace(
1341 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001342 Width = Target->getPointerWidth(AS);
1343 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001344 break;
1345 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001346 case Type::LValueReference:
1347 case Type::RValueReference: {
1348 // alignof and sizeof should never enter this code path here, so we go
1349 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001350 unsigned AS = getTargetAddressSpace(
1351 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001352 Width = Target->getPointerWidth(AS);
1353 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001354 break;
1355 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001356 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001357 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001358 Width = Target->getPointerWidth(AS);
1359 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001360 break;
1361 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001362 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001363 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001364 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001365 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001366 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001367 Align = PtrDiffInfo.second;
1368 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001369 }
Chris Lattner647fb222007-07-18 18:26:58 +00001370 case Type::Complex: {
1371 // Complex types have the same alignment as their elements, but twice the
1372 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001373 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001374 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001375 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001376 Align = EltInfo.second;
1377 break;
1378 }
John McCall8b07ec22010-05-15 11:32:37 +00001379 case Type::ObjCObject:
1380 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001381 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001382 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001383 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001384 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001385 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001386 break;
1387 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001388 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001389 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001390 const TagType *TT = cast<TagType>(T);
1391
1392 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001393 Width = 8;
1394 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001395 break;
1396 }
Mike Stump11289f42009-09-09 15:08:12 +00001397
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001398 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001399 return getTypeInfo(ET->getDecl()->getIntegerType());
1400
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001401 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001402 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001403 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001404 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001405 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001406 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001407
Chris Lattner63d2b362009-10-22 05:17:15 +00001408 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001409 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1410 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001411
Richard Smith30482bc2011-02-20 03:19:35 +00001412 case Type::Auto: {
1413 const AutoType *A = cast<AutoType>(T);
1414 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001415 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001416 }
1417
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001418 case Type::Paren:
1419 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1420
Douglas Gregoref462e62009-04-30 17:32:17 +00001421 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001422 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001423 std::pair<uint64_t, unsigned> Info
1424 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001425 // If the typedef has an aligned attribute on it, it overrides any computed
1426 // alignment we have. This violates the GCC documentation (which says that
1427 // attribute(aligned) can only round up) but matches its implementation.
1428 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1429 Align = AttrAlign;
1430 else
1431 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001432 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001433 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001434 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001435
1436 case Type::TypeOfExpr:
1437 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1438 .getTypePtr());
1439
1440 case Type::TypeOf:
1441 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1442
Anders Carlsson81df7b82009-06-24 19:06:50 +00001443 case Type::Decltype:
1444 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1445 .getTypePtr());
1446
Alexis Hunte852b102011-05-24 22:41:36 +00001447 case Type::UnaryTransform:
1448 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1449
Abramo Bagnara6150c882010-05-11 21:36:43 +00001450 case Type::Elaborated:
1451 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001452
John McCall81904512011-01-06 01:58:22 +00001453 case Type::Attributed:
1454 return getTypeInfo(
1455 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1456
Richard Smith3f1b5d02011-05-05 21:57:07 +00001457 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001458 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001459 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001460 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1461 // A type alias template specialization may refer to a typedef with the
1462 // aligned attribute on it.
1463 if (TST->isTypeAlias())
1464 return getTypeInfo(TST->getAliasedType().getTypePtr());
1465 else
1466 return getTypeInfo(getCanonicalType(T));
1467 }
1468
Eli Friedman0dfb8892011-10-06 23:00:33 +00001469 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001470 std::pair<uint64_t, unsigned> Info
1471 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1472 Width = Info.first;
1473 Align = Info.second;
1474 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1475 llvm::isPowerOf2_64(Width)) {
1476 // We can potentially perform lock-free atomic operations for this
1477 // type; promote the alignment appropriately.
1478 // FIXME: We could potentially promote the width here as well...
1479 // is that worthwhile? (Non-struct atomic types generally have
1480 // power-of-two size anyway, but structs might not. Requires a bit
1481 // of implementation work to make sure we zero out the extra bits.)
1482 Align = static_cast<unsigned>(Width);
1483 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001484 }
1485
Douglas Gregoref462e62009-04-30 17:32:17 +00001486 }
Mike Stump11289f42009-09-09 15:08:12 +00001487
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001488 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001489 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001490}
1491
Ken Dyckcc56c542011-01-15 18:38:59 +00001492/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1493CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1494 return CharUnits::fromQuantity(BitSize / getCharWidth());
1495}
1496
Ken Dyckb0fcc592011-02-11 01:54:29 +00001497/// toBits - Convert a size in characters to a size in characters.
1498int64_t ASTContext::toBits(CharUnits CharSize) const {
1499 return CharSize.getQuantity() * getCharWidth();
1500}
1501
Ken Dyck8c89d592009-12-22 14:23:30 +00001502/// getTypeSizeInChars - Return the size of the specified type, in characters.
1503/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001504CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001505 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001506}
Jay Foad39c79802011-01-12 09:06:06 +00001507CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001508 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001509}
1510
Ken Dycka6046ab2010-01-26 17:25:18 +00001511/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001512/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001513CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001514 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001515}
Jay Foad39c79802011-01-12 09:06:06 +00001516CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001517 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001518}
1519
Chris Lattnera3402cd2009-01-27 18:08:34 +00001520/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1521/// type for the current target in bits. This can be different than the ABI
1522/// alignment in cases where it is beneficial for performance to overalign
1523/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001524unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001525 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001526
1527 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001528 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001529 T = CT->getElementType().getTypePtr();
1530 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001531 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1532 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001533 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1534
Chris Lattnera3402cd2009-01-27 18:08:34 +00001535 return ABIAlign;
1536}
1537
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001538/// DeepCollectObjCIvars -
1539/// This routine first collects all declared, but not synthesized, ivars in
1540/// super class and then collects all ivars, including those synthesized for
1541/// current class. This routine is used for implementation of current class
1542/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001543///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001544void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1545 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001546 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001547 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1548 DeepCollectObjCIvars(SuperClass, false, Ivars);
1549 if (!leafClass) {
1550 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1551 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001552 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001553 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001554 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001555 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001556 Iv= Iv->getNextIvar())
1557 Ivars.push_back(Iv);
1558 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001559}
1560
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001561/// CollectInheritedProtocols - Collect all protocols in current class and
1562/// those inherited by it.
1563void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001564 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001565 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001566 // We can use protocol_iterator here instead of
1567 // all_referenced_protocol_iterator since we are walking all categories.
1568 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1569 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001570 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001571 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001572 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001573 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001574 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001575 CollectInheritedProtocols(*P, Protocols);
1576 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001577 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001578
1579 // Categories of this Interface.
1580 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1581 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1582 CollectInheritedProtocols(CDeclChain, Protocols);
1583 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1584 while (SD) {
1585 CollectInheritedProtocols(SD, Protocols);
1586 SD = SD->getSuperClass();
1587 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001588 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001589 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001590 PE = OC->protocol_end(); P != PE; ++P) {
1591 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001592 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001593 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1594 PE = Proto->protocol_end(); P != PE; ++P)
1595 CollectInheritedProtocols(*P, Protocols);
1596 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001597 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001598 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1599 PE = OP->protocol_end(); P != PE; ++P) {
1600 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001601 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001602 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1603 PE = Proto->protocol_end(); P != PE; ++P)
1604 CollectInheritedProtocols(*P, Protocols);
1605 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001606 }
1607}
1608
Jay Foad39c79802011-01-12 09:06:06 +00001609unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001610 unsigned count = 0;
1611 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001612 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1613 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001614 count += CDecl->ivar_size();
1615
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001616 // Count ivar defined in this class's implementation. This
1617 // includes synthesized ivars.
1618 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001619 count += ImplDecl->ivar_size();
1620
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001621 return count;
1622}
1623
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001624bool ASTContext::isSentinelNullExpr(const Expr *E) {
1625 if (!E)
1626 return false;
1627
1628 // nullptr_t is always treated as null.
1629 if (E->getType()->isNullPtrType()) return true;
1630
1631 if (E->getType()->isAnyPointerType() &&
1632 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1633 Expr::NPC_ValueDependentIsNull))
1634 return true;
1635
1636 // Unfortunately, __null has type 'int'.
1637 if (isa<GNUNullExpr>(E)) return true;
1638
1639 return false;
1640}
1641
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001642/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1643ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1644 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1645 I = ObjCImpls.find(D);
1646 if (I != ObjCImpls.end())
1647 return cast<ObjCImplementationDecl>(I->second);
1648 return 0;
1649}
1650/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1651ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1652 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1653 I = ObjCImpls.find(D);
1654 if (I != ObjCImpls.end())
1655 return cast<ObjCCategoryImplDecl>(I->second);
1656 return 0;
1657}
1658
1659/// \brief Set the implementation of ObjCInterfaceDecl.
1660void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1661 ObjCImplementationDecl *ImplD) {
1662 assert(IFaceD && ImplD && "Passed null params");
1663 ObjCImpls[IFaceD] = ImplD;
1664}
1665/// \brief Set the implementation of ObjCCategoryDecl.
1666void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1667 ObjCCategoryImplDecl *ImplD) {
1668 assert(CatD && ImplD && "Passed null params");
1669 ObjCImpls[CatD] = ImplD;
1670}
1671
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001672ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1673 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1674 return ID;
1675 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1676 return CD->getClassInterface();
1677 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1678 return IMD->getClassInterface();
1679
1680 return 0;
1681}
1682
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001683/// \brief Get the copy initialization expression of VarDecl,or NULL if
1684/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001685Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001686 assert(VD && "Passed null params");
1687 assert(VD->hasAttr<BlocksAttr>() &&
1688 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001689 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001690 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001691 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1692}
1693
1694/// \brief Set the copy inialization expression of a block var decl.
1695void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1696 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001697 assert(VD->hasAttr<BlocksAttr>() &&
1698 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001699 BlockVarCopyInits[VD] = Init;
1700}
1701
John McCallbcd03502009-12-07 02:54:59 +00001702TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001703 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001704 if (!DataSize)
1705 DataSize = TypeLoc::getFullDataSizeForType(T);
1706 else
1707 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001708 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001709
John McCallbcd03502009-12-07 02:54:59 +00001710 TypeSourceInfo *TInfo =
1711 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1712 new (TInfo) TypeSourceInfo(T);
1713 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001714}
1715
John McCallbcd03502009-12-07 02:54:59 +00001716TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001717 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001718 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001719 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001720 return DI;
1721}
1722
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001723const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001724ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001725 return getObjCLayout(D, 0);
1726}
1727
1728const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001729ASTContext::getASTObjCImplementationLayout(
1730 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001731 return getObjCLayout(D->getClassInterface(), D);
1732}
1733
Chris Lattner983a8bb2007-07-13 22:13:22 +00001734//===----------------------------------------------------------------------===//
1735// Type creation/memoization methods
1736//===----------------------------------------------------------------------===//
1737
Jay Foad39c79802011-01-12 09:06:06 +00001738QualType
John McCall33ddac02011-01-19 10:06:00 +00001739ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1740 unsigned fastQuals = quals.getFastQualifiers();
1741 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001742
1743 // Check if we've already instantiated this type.
1744 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001745 ExtQuals::Profile(ID, baseType, quals);
1746 void *insertPos = 0;
1747 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1748 assert(eq->getQualifiers() == quals);
1749 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001750 }
1751
John McCall33ddac02011-01-19 10:06:00 +00001752 // If the base type is not canonical, make the appropriate canonical type.
1753 QualType canon;
1754 if (!baseType->isCanonicalUnqualified()) {
1755 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001756 canonSplit.Quals.addConsistentQualifiers(quals);
1757 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001758
1759 // Re-find the insert position.
1760 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1761 }
1762
1763 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1764 ExtQualNodes.InsertNode(eq, insertPos);
1765 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001766}
1767
Jay Foad39c79802011-01-12 09:06:06 +00001768QualType
1769ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001770 QualType CanT = getCanonicalType(T);
1771 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001772 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001773
John McCall8ccfcb52009-09-24 19:53:00 +00001774 // If we are composing extended qualifiers together, merge together
1775 // into one ExtQuals node.
1776 QualifierCollector Quals;
1777 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001778
John McCall8ccfcb52009-09-24 19:53:00 +00001779 // If this type already has an address space specified, it cannot get
1780 // another one.
1781 assert(!Quals.hasAddressSpace() &&
1782 "Type cannot be in multiple addr spaces!");
1783 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001784
John McCall8ccfcb52009-09-24 19:53:00 +00001785 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001786}
1787
Chris Lattnerd60183d2009-02-18 22:53:11 +00001788QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001789 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001790 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001791 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001792 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001793
John McCall53fa7142010-12-24 02:08:15 +00001794 if (const PointerType *ptr = T->getAs<PointerType>()) {
1795 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001796 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001797 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1798 return getPointerType(ResultType);
1799 }
1800 }
Mike Stump11289f42009-09-09 15:08:12 +00001801
John McCall8ccfcb52009-09-24 19:53:00 +00001802 // If we are composing extended qualifiers together, merge together
1803 // into one ExtQuals node.
1804 QualifierCollector Quals;
1805 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001806
John McCall8ccfcb52009-09-24 19:53:00 +00001807 // If this type already has an ObjCGC specified, it cannot get
1808 // another one.
1809 assert(!Quals.hasObjCGCAttr() &&
1810 "Type cannot have multiple ObjCGCs!");
1811 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001812
John McCall8ccfcb52009-09-24 19:53:00 +00001813 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001814}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001815
John McCall4f5019e2010-12-19 02:44:49 +00001816const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1817 FunctionType::ExtInfo Info) {
1818 if (T->getExtInfo() == Info)
1819 return T;
1820
1821 QualType Result;
1822 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1823 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1824 } else {
1825 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1826 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1827 EPI.ExtInfo = Info;
1828 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1829 FPT->getNumArgs(), EPI);
1830 }
1831
1832 return cast<FunctionType>(Result.getTypePtr());
1833}
1834
Chris Lattnerc6395932007-06-22 20:56:16 +00001835/// getComplexType - Return the uniqued reference to the type for a complex
1836/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001837QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001838 // Unique pointers, to guarantee there is only one pointer of a particular
1839 // structure.
1840 llvm::FoldingSetNodeID ID;
1841 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001842
Chris Lattnerc6395932007-06-22 20:56:16 +00001843 void *InsertPos = 0;
1844 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1845 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001846
Chris Lattnerc6395932007-06-22 20:56:16 +00001847 // If the pointee type isn't canonical, this won't be a canonical type either,
1848 // so fill in the canonical type field.
1849 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001850 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001851 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001852
Chris Lattnerc6395932007-06-22 20:56:16 +00001853 // Get the new insert position for the node we care about.
1854 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001855 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001856 }
John McCall90d1c2d2009-09-24 23:30:46 +00001857 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001858 Types.push_back(New);
1859 ComplexTypes.InsertNode(New, InsertPos);
1860 return QualType(New, 0);
1861}
1862
Chris Lattner970e54e2006-11-12 00:37:36 +00001863/// getPointerType - Return the uniqued reference to the type for a pointer to
1864/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001865QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001866 // Unique pointers, to guarantee there is only one pointer of a particular
1867 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001868 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001869 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001870
Chris Lattner67521df2007-01-27 01:29:36 +00001871 void *InsertPos = 0;
1872 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001873 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001874
Chris Lattner7ccecb92006-11-12 08:50:50 +00001875 // If the pointee type isn't canonical, this won't be a canonical type either,
1876 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001877 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001878 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001879 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001880
Chris Lattner67521df2007-01-27 01:29:36 +00001881 // Get the new insert position for the node we care about.
1882 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001883 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001884 }
John McCall90d1c2d2009-09-24 23:30:46 +00001885 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001886 Types.push_back(New);
1887 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001888 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001889}
1890
Mike Stump11289f42009-09-09 15:08:12 +00001891/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001892/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001893QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001894 assert(T->isFunctionType() && "block of function types only");
1895 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001896 // structure.
1897 llvm::FoldingSetNodeID ID;
1898 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001899
Steve Naroffec33ed92008-08-27 16:04:49 +00001900 void *InsertPos = 0;
1901 if (BlockPointerType *PT =
1902 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1903 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001904
1905 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001906 // type either so fill in the canonical type field.
1907 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001908 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001909 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001910
Steve Naroffec33ed92008-08-27 16:04:49 +00001911 // Get the new insert position for the node we care about.
1912 BlockPointerType *NewIP =
1913 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001914 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001915 }
John McCall90d1c2d2009-09-24 23:30:46 +00001916 BlockPointerType *New
1917 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001918 Types.push_back(New);
1919 BlockPointerTypes.InsertNode(New, InsertPos);
1920 return QualType(New, 0);
1921}
1922
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001923/// getLValueReferenceType - Return the uniqued reference to the type for an
1924/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001925QualType
1926ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001927 assert(getCanonicalType(T) != OverloadTy &&
1928 "Unresolved overloaded function type");
1929
Bill Wendling3708c182007-05-27 10:15:43 +00001930 // Unique pointers, to guarantee there is only one pointer of a particular
1931 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001932 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001933 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001934
1935 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001936 if (LValueReferenceType *RT =
1937 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001938 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001939
John McCallfc93cf92009-10-22 22:37:11 +00001940 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1941
Bill Wendling3708c182007-05-27 10:15:43 +00001942 // If the referencee type isn't canonical, this won't be a canonical type
1943 // either, so fill in the canonical type field.
1944 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001945 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1946 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1947 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001948
Bill Wendling3708c182007-05-27 10:15:43 +00001949 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001950 LValueReferenceType *NewIP =
1951 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001952 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001953 }
1954
John McCall90d1c2d2009-09-24 23:30:46 +00001955 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001956 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1957 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001958 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001959 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001960
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001961 return QualType(New, 0);
1962}
1963
1964/// getRValueReferenceType - Return the uniqued reference to the type for an
1965/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001966QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001967 // Unique pointers, to guarantee there is only one pointer of a particular
1968 // structure.
1969 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001970 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001971
1972 void *InsertPos = 0;
1973 if (RValueReferenceType *RT =
1974 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1975 return QualType(RT, 0);
1976
John McCallfc93cf92009-10-22 22:37:11 +00001977 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1978
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001979 // If the referencee type isn't canonical, this won't be a canonical type
1980 // either, so fill in the canonical type field.
1981 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001982 if (InnerRef || !T.isCanonical()) {
1983 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1984 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001985
1986 // Get the new insert position for the node we care about.
1987 RValueReferenceType *NewIP =
1988 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001989 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001990 }
1991
John McCall90d1c2d2009-09-24 23:30:46 +00001992 RValueReferenceType *New
1993 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001994 Types.push_back(New);
1995 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001996 return QualType(New, 0);
1997}
1998
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001999/// getMemberPointerType - Return the uniqued reference to the type for a
2000/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002001QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002002 // Unique pointers, to guarantee there is only one pointer of a particular
2003 // structure.
2004 llvm::FoldingSetNodeID ID;
2005 MemberPointerType::Profile(ID, T, Cls);
2006
2007 void *InsertPos = 0;
2008 if (MemberPointerType *PT =
2009 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2010 return QualType(PT, 0);
2011
2012 // If the pointee or class type isn't canonical, this won't be a canonical
2013 // type either, so fill in the canonical type field.
2014 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002015 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002016 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2017
2018 // Get the new insert position for the node we care about.
2019 MemberPointerType *NewIP =
2020 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002021 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002022 }
John McCall90d1c2d2009-09-24 23:30:46 +00002023 MemberPointerType *New
2024 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002025 Types.push_back(New);
2026 MemberPointerTypes.InsertNode(New, InsertPos);
2027 return QualType(New, 0);
2028}
2029
Mike Stump11289f42009-09-09 15:08:12 +00002030/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002031/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002032QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002033 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002034 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002035 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002036 assert((EltTy->isDependentType() ||
2037 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002038 "Constant array of VLAs is illegal!");
2039
Chris Lattnere2df3f92009-05-13 04:12:56 +00002040 // Convert the array size into a canonical width matching the pointer size for
2041 // the target.
2042 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002043 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002044 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002045
Chris Lattner23b7eb62007-06-15 23:05:46 +00002046 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002047 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002048
Chris Lattner36f8e652007-01-27 08:31:04 +00002049 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002050 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002051 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002052 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002053
John McCall33ddac02011-01-19 10:06:00 +00002054 // If the element type isn't canonical or has qualifiers, this won't
2055 // be a canonical type either, so fill in the canonical type field.
2056 QualType Canon;
2057 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2058 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002059 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002060 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002061 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002062
Chris Lattner36f8e652007-01-27 08:31:04 +00002063 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002064 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002065 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002066 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002067 }
Mike Stump11289f42009-09-09 15:08:12 +00002068
John McCall90d1c2d2009-09-24 23:30:46 +00002069 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002070 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002071 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002072 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002073 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002074}
2075
John McCall06549462011-01-18 08:40:38 +00002076/// getVariableArrayDecayedType - Turns the given type, which may be
2077/// variably-modified, into the corresponding type with all the known
2078/// sizes replaced with [*].
2079QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2080 // Vastly most common case.
2081 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002082
John McCall06549462011-01-18 08:40:38 +00002083 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002084
John McCall06549462011-01-18 08:40:38 +00002085 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002086 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002087 switch (ty->getTypeClass()) {
2088#define TYPE(Class, Base)
2089#define ABSTRACT_TYPE(Class, Base)
2090#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2091#include "clang/AST/TypeNodes.def"
2092 llvm_unreachable("didn't desugar past all non-canonical types?");
2093
2094 // These types should never be variably-modified.
2095 case Type::Builtin:
2096 case Type::Complex:
2097 case Type::Vector:
2098 case Type::ExtVector:
2099 case Type::DependentSizedExtVector:
2100 case Type::ObjCObject:
2101 case Type::ObjCInterface:
2102 case Type::ObjCObjectPointer:
2103 case Type::Record:
2104 case Type::Enum:
2105 case Type::UnresolvedUsing:
2106 case Type::TypeOfExpr:
2107 case Type::TypeOf:
2108 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002109 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002110 case Type::DependentName:
2111 case Type::InjectedClassName:
2112 case Type::TemplateSpecialization:
2113 case Type::DependentTemplateSpecialization:
2114 case Type::TemplateTypeParm:
2115 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002116 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002117 case Type::PackExpansion:
2118 llvm_unreachable("type should never be variably-modified");
2119
2120 // These types can be variably-modified but should never need to
2121 // further decay.
2122 case Type::FunctionNoProto:
2123 case Type::FunctionProto:
2124 case Type::BlockPointer:
2125 case Type::MemberPointer:
2126 return type;
2127
2128 // These types can be variably-modified. All these modifications
2129 // preserve structure except as noted by comments.
2130 // TODO: if we ever care about optimizing VLAs, there are no-op
2131 // optimizations available here.
2132 case Type::Pointer:
2133 result = getPointerType(getVariableArrayDecayedType(
2134 cast<PointerType>(ty)->getPointeeType()));
2135 break;
2136
2137 case Type::LValueReference: {
2138 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2139 result = getLValueReferenceType(
2140 getVariableArrayDecayedType(lv->getPointeeType()),
2141 lv->isSpelledAsLValue());
2142 break;
2143 }
2144
2145 case Type::RValueReference: {
2146 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2147 result = getRValueReferenceType(
2148 getVariableArrayDecayedType(lv->getPointeeType()));
2149 break;
2150 }
2151
Eli Friedman0dfb8892011-10-06 23:00:33 +00002152 case Type::Atomic: {
2153 const AtomicType *at = cast<AtomicType>(ty);
2154 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2155 break;
2156 }
2157
John McCall06549462011-01-18 08:40:38 +00002158 case Type::ConstantArray: {
2159 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2160 result = getConstantArrayType(
2161 getVariableArrayDecayedType(cat->getElementType()),
2162 cat->getSize(),
2163 cat->getSizeModifier(),
2164 cat->getIndexTypeCVRQualifiers());
2165 break;
2166 }
2167
2168 case Type::DependentSizedArray: {
2169 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2170 result = getDependentSizedArrayType(
2171 getVariableArrayDecayedType(dat->getElementType()),
2172 dat->getSizeExpr(),
2173 dat->getSizeModifier(),
2174 dat->getIndexTypeCVRQualifiers(),
2175 dat->getBracketsRange());
2176 break;
2177 }
2178
2179 // Turn incomplete types into [*] types.
2180 case Type::IncompleteArray: {
2181 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2182 result = getVariableArrayType(
2183 getVariableArrayDecayedType(iat->getElementType()),
2184 /*size*/ 0,
2185 ArrayType::Normal,
2186 iat->getIndexTypeCVRQualifiers(),
2187 SourceRange());
2188 break;
2189 }
2190
2191 // Turn VLA types into [*] types.
2192 case Type::VariableArray: {
2193 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2194 result = getVariableArrayType(
2195 getVariableArrayDecayedType(vat->getElementType()),
2196 /*size*/ 0,
2197 ArrayType::Star,
2198 vat->getIndexTypeCVRQualifiers(),
2199 vat->getBracketsRange());
2200 break;
2201 }
2202 }
2203
2204 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002205 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002206}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002207
Steve Naroffcadebd02007-08-30 18:14:25 +00002208/// getVariableArrayType - Returns a non-unique reference to the type for a
2209/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002210QualType ASTContext::getVariableArrayType(QualType EltTy,
2211 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002212 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002213 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002214 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002215 // Since we don't unique expressions, it isn't possible to unique VLA's
2216 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002217 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002218
John McCall33ddac02011-01-19 10:06:00 +00002219 // Be sure to pull qualifiers off the element type.
2220 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2221 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002222 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002223 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002224 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002225 }
2226
John McCall90d1c2d2009-09-24 23:30:46 +00002227 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002228 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002229
2230 VariableArrayTypes.push_back(New);
2231 Types.push_back(New);
2232 return QualType(New, 0);
2233}
2234
Douglas Gregor4619e432008-12-05 23:32:09 +00002235/// getDependentSizedArrayType - Returns a non-unique reference to
2236/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002237/// type.
John McCall33ddac02011-01-19 10:06:00 +00002238QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2239 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002240 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002241 unsigned elementTypeQuals,
2242 SourceRange brackets) const {
2243 assert((!numElements || numElements->isTypeDependent() ||
2244 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002245 "Size must be type- or value-dependent!");
2246
John McCall33ddac02011-01-19 10:06:00 +00002247 // Dependently-sized array types that do not have a specified number
2248 // of elements will have their sizes deduced from a dependent
2249 // initializer. We do no canonicalization here at all, which is okay
2250 // because they can't be used in most locations.
2251 if (!numElements) {
2252 DependentSizedArrayType *newType
2253 = new (*this, TypeAlignment)
2254 DependentSizedArrayType(*this, elementType, QualType(),
2255 numElements, ASM, elementTypeQuals,
2256 brackets);
2257 Types.push_back(newType);
2258 return QualType(newType, 0);
2259 }
2260
2261 // Otherwise, we actually build a new type every time, but we
2262 // also build a canonical type.
2263
2264 SplitQualType canonElementType = getCanonicalType(elementType).split();
2265
2266 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002267 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002268 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002269 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002270 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002271
John McCall33ddac02011-01-19 10:06:00 +00002272 // Look for an existing type with these properties.
2273 DependentSizedArrayType *canonTy =
2274 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002275
John McCall33ddac02011-01-19 10:06:00 +00002276 // If we don't have one, build one.
2277 if (!canonTy) {
2278 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002279 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002280 QualType(), numElements, ASM, elementTypeQuals,
2281 brackets);
2282 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2283 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002284 }
2285
John McCall33ddac02011-01-19 10:06:00 +00002286 // Apply qualifiers from the element type to the array.
2287 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002288 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002289
John McCall33ddac02011-01-19 10:06:00 +00002290 // If we didn't need extra canonicalization for the element type,
2291 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002292 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002293 return canon;
2294
2295 // Otherwise, we need to build a type which follows the spelling
2296 // of the element type.
2297 DependentSizedArrayType *sugaredType
2298 = new (*this, TypeAlignment)
2299 DependentSizedArrayType(*this, elementType, canon, numElements,
2300 ASM, elementTypeQuals, brackets);
2301 Types.push_back(sugaredType);
2302 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002303}
2304
John McCall33ddac02011-01-19 10:06:00 +00002305QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002306 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002307 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002308 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002309 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002310
John McCall33ddac02011-01-19 10:06:00 +00002311 void *insertPos = 0;
2312 if (IncompleteArrayType *iat =
2313 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2314 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002315
2316 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002317 // either, so fill in the canonical type field. We also have to pull
2318 // qualifiers off the element type.
2319 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002320
John McCall33ddac02011-01-19 10:06:00 +00002321 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2322 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002323 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002324 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002325 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002326
2327 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002328 IncompleteArrayType *existing =
2329 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2330 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002331 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002332
John McCall33ddac02011-01-19 10:06:00 +00002333 IncompleteArrayType *newType = new (*this, TypeAlignment)
2334 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002335
John McCall33ddac02011-01-19 10:06:00 +00002336 IncompleteArrayTypes.InsertNode(newType, insertPos);
2337 Types.push_back(newType);
2338 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002339}
2340
Steve Naroff91fcddb2007-07-18 18:00:27 +00002341/// getVectorType - Return the unique reference to a vector type of
2342/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002343QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002344 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002345 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002346
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002347 // Check if we've already instantiated a vector of this type.
2348 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002349 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002350
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002351 void *InsertPos = 0;
2352 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2353 return QualType(VTP, 0);
2354
2355 // If the element type isn't canonical, this won't be a canonical type either,
2356 // so fill in the canonical type field.
2357 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002358 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002359 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002360
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002361 // Get the new insert position for the node we care about.
2362 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002363 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002364 }
John McCall90d1c2d2009-09-24 23:30:46 +00002365 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002366 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002367 VectorTypes.InsertNode(New, InsertPos);
2368 Types.push_back(New);
2369 return QualType(New, 0);
2370}
2371
Nate Begemance4d7fc2008-04-18 23:10:10 +00002372/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002373/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002374QualType
2375ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002376 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002377
Steve Naroff91fcddb2007-07-18 18:00:27 +00002378 // Check if we've already instantiated a vector of this type.
2379 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002380 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002381 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002382 void *InsertPos = 0;
2383 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2384 return QualType(VTP, 0);
2385
2386 // If the element type isn't canonical, this won't be a canonical type either,
2387 // so fill in the canonical type field.
2388 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002389 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002390 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002391
Steve Naroff91fcddb2007-07-18 18:00:27 +00002392 // Get the new insert position for the node we care about.
2393 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002394 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002395 }
John McCall90d1c2d2009-09-24 23:30:46 +00002396 ExtVectorType *New = new (*this, TypeAlignment)
2397 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002398 VectorTypes.InsertNode(New, InsertPos);
2399 Types.push_back(New);
2400 return QualType(New, 0);
2401}
2402
Jay Foad39c79802011-01-12 09:06:06 +00002403QualType
2404ASTContext::getDependentSizedExtVectorType(QualType vecType,
2405 Expr *SizeExpr,
2406 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002407 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002408 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002409 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002410
Douglas Gregor352169a2009-07-31 03:54:25 +00002411 void *InsertPos = 0;
2412 DependentSizedExtVectorType *Canon
2413 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2414 DependentSizedExtVectorType *New;
2415 if (Canon) {
2416 // We already have a canonical version of this array type; use it as
2417 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002418 New = new (*this, TypeAlignment)
2419 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2420 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002421 } else {
2422 QualType CanonVecTy = getCanonicalType(vecType);
2423 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002424 New = new (*this, TypeAlignment)
2425 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2426 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002427
2428 DependentSizedExtVectorType *CanonCheck
2429 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2430 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2431 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002432 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2433 } else {
2434 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2435 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002436 New = new (*this, TypeAlignment)
2437 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002438 }
2439 }
Mike Stump11289f42009-09-09 15:08:12 +00002440
Douglas Gregor758a8692009-06-17 21:51:59 +00002441 Types.push_back(New);
2442 return QualType(New, 0);
2443}
2444
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002445/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002446///
Jay Foad39c79802011-01-12 09:06:06 +00002447QualType
2448ASTContext::getFunctionNoProtoType(QualType ResultTy,
2449 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002450 const CallingConv DefaultCC = Info.getCC();
2451 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2452 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002453 // Unique functions, to guarantee there is only one function of a particular
2454 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002455 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002456 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002457
Chris Lattner47955de2007-01-27 08:37:20 +00002458 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002459 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002460 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002461 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002462
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002463 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002464 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002465 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002466 Canonical =
2467 getFunctionNoProtoType(getCanonicalType(ResultTy),
2468 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002469
Chris Lattner47955de2007-01-27 08:37:20 +00002470 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002471 FunctionNoProtoType *NewIP =
2472 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002473 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002474 }
Mike Stump11289f42009-09-09 15:08:12 +00002475
Roman Divacky65b88cd2011-03-01 17:40:53 +00002476 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002477 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002478 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002479 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002480 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002481 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002482}
2483
2484/// getFunctionType - Return a normal function type with a typed argument
2485/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002486QualType
2487ASTContext::getFunctionType(QualType ResultTy,
2488 const QualType *ArgArray, unsigned NumArgs,
2489 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002490 // Unique functions, to guarantee there is only one function of a particular
2491 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002492 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002493 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002494
2495 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002496 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002497 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002498 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002499
2500 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002501 bool isCanonical =
2502 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2503 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002504 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002505 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002506 isCanonical = false;
2507
Roman Divacky65b88cd2011-03-01 17:40:53 +00002508 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2509 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2510 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002511
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002512 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002513 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002514 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002515 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002516 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002517 CanonicalArgs.reserve(NumArgs);
2518 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002519 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002520
John McCalldb40c7f2010-12-14 08:05:40 +00002521 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002522 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002523 CanonicalEPI.ExceptionSpecType = EST_None;
2524 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002525 CanonicalEPI.ExtInfo
2526 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2527
Chris Lattner76a00cf2008-04-06 22:59:24 +00002528 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002529 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002530 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002531
Chris Lattnerfd4de792007-01-27 01:15:32 +00002532 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002533 FunctionProtoType *NewIP =
2534 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002535 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002536 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002537
John McCall31168b02011-06-15 23:02:42 +00002538 // FunctionProtoType objects are allocated with extra bytes after
2539 // them for three variable size arrays at the end:
2540 // - parameter types
2541 // - exception types
2542 // - consumed-arguments flags
2543 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002544 // expression, or information used to resolve the exception
2545 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002546 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002547 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002548 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002549 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002550 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002551 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002552 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002553 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002554 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2555 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002556 }
John McCall31168b02011-06-15 23:02:42 +00002557 if (EPI.ConsumedArguments)
2558 Size += NumArgs * sizeof(bool);
2559
John McCalldb40c7f2010-12-14 08:05:40 +00002560 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002561 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2562 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002563 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002564 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002565 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002566 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002567}
Chris Lattneref51c202006-11-10 07:17:23 +00002568
John McCalle78aac42010-03-10 03:28:59 +00002569#ifndef NDEBUG
2570static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2571 if (!isa<CXXRecordDecl>(D)) return false;
2572 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2573 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2574 return true;
2575 if (RD->getDescribedClassTemplate() &&
2576 !isa<ClassTemplateSpecializationDecl>(RD))
2577 return true;
2578 return false;
2579}
2580#endif
2581
2582/// getInjectedClassNameType - Return the unique reference to the
2583/// injected class name type for the specified templated declaration.
2584QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002585 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002586 assert(NeedsInjectedClassNameType(Decl));
2587 if (Decl->TypeForDecl) {
2588 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002589 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002590 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2591 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2592 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2593 } else {
John McCall424cec92011-01-19 06:33:43 +00002594 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002595 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002596 Decl->TypeForDecl = newType;
2597 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002598 }
2599 return QualType(Decl->TypeForDecl, 0);
2600}
2601
Douglas Gregor83a586e2008-04-13 21:07:44 +00002602/// getTypeDeclType - Return the unique reference to the type for the
2603/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002604QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002605 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002606 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002607
Richard Smithdda56e42011-04-15 14:24:37 +00002608 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002609 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002610
John McCall96f0b5f2010-03-10 06:48:02 +00002611 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2612 "Template type parameter types are always available.");
2613
John McCall81e38502010-02-16 03:57:14 +00002614 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002615 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002616 "struct/union has previous declaration");
2617 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002618 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002619 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002620 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002621 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002622 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002623 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002624 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002625 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2626 Decl->TypeForDecl = newType;
2627 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002628 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002629 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002630
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002631 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002632}
2633
Chris Lattner32d920b2007-01-26 02:01:53 +00002634/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002635/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002636QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002637ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2638 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002639 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002640
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002641 if (Canonical.isNull())
2642 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002643 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002644 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002645 Decl->TypeForDecl = newType;
2646 Types.push_back(newType);
2647 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002648}
2649
Jay Foad39c79802011-01-12 09:06:06 +00002650QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002651 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2652
Douglas Gregorec9fd132012-01-14 16:38:05 +00002653 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002654 if (PrevDecl->TypeForDecl)
2655 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2656
John McCall424cec92011-01-19 06:33:43 +00002657 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2658 Decl->TypeForDecl = newType;
2659 Types.push_back(newType);
2660 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002661}
2662
Jay Foad39c79802011-01-12 09:06:06 +00002663QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002664 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2665
Douglas Gregorec9fd132012-01-14 16:38:05 +00002666 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002667 if (PrevDecl->TypeForDecl)
2668 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2669
John McCall424cec92011-01-19 06:33:43 +00002670 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2671 Decl->TypeForDecl = newType;
2672 Types.push_back(newType);
2673 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002674}
2675
John McCall81904512011-01-06 01:58:22 +00002676QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2677 QualType modifiedType,
2678 QualType equivalentType) {
2679 llvm::FoldingSetNodeID id;
2680 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2681
2682 void *insertPos = 0;
2683 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2684 if (type) return QualType(type, 0);
2685
2686 QualType canon = getCanonicalType(equivalentType);
2687 type = new (*this, TypeAlignment)
2688 AttributedType(canon, attrKind, modifiedType, equivalentType);
2689
2690 Types.push_back(type);
2691 AttributedTypes.InsertNode(type, insertPos);
2692
2693 return QualType(type, 0);
2694}
2695
2696
John McCallcebee162009-10-18 09:09:24 +00002697/// \brief Retrieve a substitution-result type.
2698QualType
2699ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002700 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002701 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002702 && "replacement types must always be canonical");
2703
2704 llvm::FoldingSetNodeID ID;
2705 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2706 void *InsertPos = 0;
2707 SubstTemplateTypeParmType *SubstParm
2708 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2709
2710 if (!SubstParm) {
2711 SubstParm = new (*this, TypeAlignment)
2712 SubstTemplateTypeParmType(Parm, Replacement);
2713 Types.push_back(SubstParm);
2714 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2715 }
2716
2717 return QualType(SubstParm, 0);
2718}
2719
Douglas Gregorada4b792011-01-14 02:55:32 +00002720/// \brief Retrieve a
2721QualType ASTContext::getSubstTemplateTypeParmPackType(
2722 const TemplateTypeParmType *Parm,
2723 const TemplateArgument &ArgPack) {
2724#ifndef NDEBUG
2725 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2726 PEnd = ArgPack.pack_end();
2727 P != PEnd; ++P) {
2728 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2729 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2730 }
2731#endif
2732
2733 llvm::FoldingSetNodeID ID;
2734 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2735 void *InsertPos = 0;
2736 if (SubstTemplateTypeParmPackType *SubstParm
2737 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2738 return QualType(SubstParm, 0);
2739
2740 QualType Canon;
2741 if (!Parm->isCanonicalUnqualified()) {
2742 Canon = getCanonicalType(QualType(Parm, 0));
2743 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2744 ArgPack);
2745 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2746 }
2747
2748 SubstTemplateTypeParmPackType *SubstParm
2749 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2750 ArgPack);
2751 Types.push_back(SubstParm);
2752 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2753 return QualType(SubstParm, 0);
2754}
2755
Douglas Gregoreff93e02009-02-05 23:33:38 +00002756/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002757/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002758/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002759QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002760 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002761 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002762 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002763 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002764 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002765 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002766 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2767
2768 if (TypeParm)
2769 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002770
Chandler Carruth08836322011-05-01 00:51:33 +00002771 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002772 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002773 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002774
2775 TemplateTypeParmType *TypeCheck
2776 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2777 assert(!TypeCheck && "Template type parameter canonical type broken");
2778 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002779 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002780 TypeParm = new (*this, TypeAlignment)
2781 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002782
2783 Types.push_back(TypeParm);
2784 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2785
2786 return QualType(TypeParm, 0);
2787}
2788
John McCalle78aac42010-03-10 03:28:59 +00002789TypeSourceInfo *
2790ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2791 SourceLocation NameLoc,
2792 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002793 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002794 assert(!Name.getAsDependentTemplateName() &&
2795 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002796 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002797
2798 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2799 TemplateSpecializationTypeLoc TL
2800 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002801 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002802 TL.setTemplateNameLoc(NameLoc);
2803 TL.setLAngleLoc(Args.getLAngleLoc());
2804 TL.setRAngleLoc(Args.getRAngleLoc());
2805 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2806 TL.setArgLocInfo(i, Args[i].getLocInfo());
2807 return DI;
2808}
2809
Mike Stump11289f42009-09-09 15:08:12 +00002810QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002811ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002812 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002813 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002814 assert(!Template.getAsDependentTemplateName() &&
2815 "No dependent template names here!");
2816
John McCall6b51f282009-11-23 01:53:49 +00002817 unsigned NumArgs = Args.size();
2818
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002819 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002820 ArgVec.reserve(NumArgs);
2821 for (unsigned i = 0; i != NumArgs; ++i)
2822 ArgVec.push_back(Args[i].getArgument());
2823
John McCall2408e322010-04-27 00:57:59 +00002824 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002825 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002826}
2827
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002828#ifndef NDEBUG
2829static bool hasAnyPackExpansions(const TemplateArgument *Args,
2830 unsigned NumArgs) {
2831 for (unsigned I = 0; I != NumArgs; ++I)
2832 if (Args[I].isPackExpansion())
2833 return true;
2834
2835 return true;
2836}
2837#endif
2838
John McCall0ad16662009-10-29 08:12:44 +00002839QualType
2840ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002841 const TemplateArgument *Args,
2842 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002843 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002844 assert(!Template.getAsDependentTemplateName() &&
2845 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002846 // Look through qualified template names.
2847 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2848 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002849
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002850 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002851 Template.getAsTemplateDecl() &&
2852 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002853 QualType CanonType;
2854 if (!Underlying.isNull())
2855 CanonType = getCanonicalType(Underlying);
2856 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002857 // We can get here with an alias template when the specialization contains
2858 // a pack expansion that does not match up with a parameter pack.
2859 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2860 "Caller must compute aliased type");
2861 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002862 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2863 NumArgs);
2864 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002865
Douglas Gregora8e02e72009-07-28 23:00:59 +00002866 // Allocate the (non-canonical) template specialization type, but don't
2867 // try to unique it: these types typically have location information that
2868 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002869 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2870 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002871 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002872 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002873 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002874 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2875 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002876
Douglas Gregor8bf42052009-02-09 18:46:07 +00002877 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002878 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002879}
2880
Mike Stump11289f42009-09-09 15:08:12 +00002881QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002882ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2883 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002884 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002885 assert(!Template.getAsDependentTemplateName() &&
2886 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002887
Douglas Gregore29139c2011-03-03 17:04:51 +00002888 // Look through qualified template names.
2889 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2890 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002891
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002892 // Build the canonical template specialization type.
2893 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002894 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002895 CanonArgs.reserve(NumArgs);
2896 for (unsigned I = 0; I != NumArgs; ++I)
2897 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2898
2899 // Determine whether this canonical template specialization type already
2900 // exists.
2901 llvm::FoldingSetNodeID ID;
2902 TemplateSpecializationType::Profile(ID, CanonTemplate,
2903 CanonArgs.data(), NumArgs, *this);
2904
2905 void *InsertPos = 0;
2906 TemplateSpecializationType *Spec
2907 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2908
2909 if (!Spec) {
2910 // Allocate a new canonical template specialization type.
2911 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2912 sizeof(TemplateArgument) * NumArgs),
2913 TypeAlignment);
2914 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2915 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002916 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002917 Types.push_back(Spec);
2918 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2919 }
2920
2921 assert(Spec->isDependentType() &&
2922 "Non-dependent template-id type must have a canonical type");
2923 return QualType(Spec, 0);
2924}
2925
2926QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002927ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2928 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002929 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002930 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002931 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002932
2933 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002934 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002935 if (T)
2936 return QualType(T, 0);
2937
Douglas Gregorc42075a2010-02-04 18:10:26 +00002938 QualType Canon = NamedType;
2939 if (!Canon.isCanonical()) {
2940 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002941 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2942 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002943 (void)CheckT;
2944 }
2945
Abramo Bagnara6150c882010-05-11 21:36:43 +00002946 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002947 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002948 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002949 return QualType(T, 0);
2950}
2951
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002952QualType
Jay Foad39c79802011-01-12 09:06:06 +00002953ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002954 llvm::FoldingSetNodeID ID;
2955 ParenType::Profile(ID, InnerType);
2956
2957 void *InsertPos = 0;
2958 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2959 if (T)
2960 return QualType(T, 0);
2961
2962 QualType Canon = InnerType;
2963 if (!Canon.isCanonical()) {
2964 Canon = getCanonicalType(InnerType);
2965 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2966 assert(!CheckT && "Paren canonical type broken");
2967 (void)CheckT;
2968 }
2969
2970 T = new (*this) ParenType(InnerType, Canon);
2971 Types.push_back(T);
2972 ParenTypes.InsertNode(T, InsertPos);
2973 return QualType(T, 0);
2974}
2975
Douglas Gregor02085352010-03-31 20:19:30 +00002976QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2977 NestedNameSpecifier *NNS,
2978 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002979 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002980 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2981
2982 if (Canon.isNull()) {
2983 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002984 ElaboratedTypeKeyword CanonKeyword = Keyword;
2985 if (Keyword == ETK_None)
2986 CanonKeyword = ETK_Typename;
2987
2988 if (CanonNNS != NNS || CanonKeyword != Keyword)
2989 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002990 }
2991
2992 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002993 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002994
2995 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002996 DependentNameType *T
2997 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002998 if (T)
2999 return QualType(T, 0);
3000
Douglas Gregor02085352010-03-31 20:19:30 +00003001 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003002 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003003 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003004 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003005}
3006
Mike Stump11289f42009-09-09 15:08:12 +00003007QualType
John McCallc392f372010-06-11 00:33:02 +00003008ASTContext::getDependentTemplateSpecializationType(
3009 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003010 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003011 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003012 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003013 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003014 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003015 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3016 ArgCopy.push_back(Args[I].getArgument());
3017 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3018 ArgCopy.size(),
3019 ArgCopy.data());
3020}
3021
3022QualType
3023ASTContext::getDependentTemplateSpecializationType(
3024 ElaboratedTypeKeyword Keyword,
3025 NestedNameSpecifier *NNS,
3026 const IdentifierInfo *Name,
3027 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003028 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003029 assert((!NNS || NNS->isDependent()) &&
3030 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003031
Douglas Gregorc42075a2010-02-04 18:10:26 +00003032 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003033 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3034 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003035
3036 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003037 DependentTemplateSpecializationType *T
3038 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003039 if (T)
3040 return QualType(T, 0);
3041
John McCallc392f372010-06-11 00:33:02 +00003042 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003043
John McCallc392f372010-06-11 00:33:02 +00003044 ElaboratedTypeKeyword CanonKeyword = Keyword;
3045 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3046
3047 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003048 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003049 for (unsigned I = 0; I != NumArgs; ++I) {
3050 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3051 if (!CanonArgs[I].structurallyEquals(Args[I]))
3052 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003053 }
3054
John McCallc392f372010-06-11 00:33:02 +00003055 QualType Canon;
3056 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3057 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3058 Name, NumArgs,
3059 CanonArgs.data());
3060
3061 // Find the insert position again.
3062 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3063 }
3064
3065 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3066 sizeof(TemplateArgument) * NumArgs),
3067 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003068 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003069 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003070 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003071 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003072 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003073}
3074
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003075QualType ASTContext::getPackExpansionType(QualType Pattern,
3076 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003077 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003078 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003079
3080 assert(Pattern->containsUnexpandedParameterPack() &&
3081 "Pack expansions must expand one or more parameter packs");
3082 void *InsertPos = 0;
3083 PackExpansionType *T
3084 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3085 if (T)
3086 return QualType(T, 0);
3087
3088 QualType Canon;
3089 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003090 Canon = getCanonicalType(Pattern);
3091 // The canonical type might not contain an unexpanded parameter pack, if it
3092 // contains an alias template specialization which ignores one of its
3093 // parameters.
3094 if (Canon->containsUnexpandedParameterPack()) {
3095 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003096
Richard Smith68eea502012-07-16 00:20:35 +00003097 // Find the insert position again, in case we inserted an element into
3098 // PackExpansionTypes and invalidated our insert position.
3099 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3100 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003101 }
3102
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003103 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003104 Types.push_back(T);
3105 PackExpansionTypes.InsertNode(T, InsertPos);
3106 return QualType(T, 0);
3107}
3108
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003109/// CmpProtocolNames - Comparison predicate for sorting protocols
3110/// alphabetically.
3111static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3112 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003113 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003114}
3115
John McCall8b07ec22010-05-15 11:32:37 +00003116static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003117 unsigned NumProtocols) {
3118 if (NumProtocols == 0) return true;
3119
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003120 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3121 return false;
3122
John McCallfc93cf92009-10-22 22:37:11 +00003123 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003124 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3125 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003126 return false;
3127 return true;
3128}
3129
3130static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003131 unsigned &NumProtocols) {
3132 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003133
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003134 // Sort protocols, keyed by name.
3135 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3136
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003137 // Canonicalize.
3138 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3139 Protocols[I] = Protocols[I]->getCanonicalDecl();
3140
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003141 // Remove duplicates.
3142 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3143 NumProtocols = ProtocolsEnd-Protocols;
3144}
3145
John McCall8b07ec22010-05-15 11:32:37 +00003146QualType ASTContext::getObjCObjectType(QualType BaseType,
3147 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003148 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003149 // If the base type is an interface and there aren't any protocols
3150 // to add, then the interface type will do just fine.
3151 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3152 return BaseType;
3153
3154 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003155 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003156 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003157 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003158 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3159 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003160
John McCall8b07ec22010-05-15 11:32:37 +00003161 // Build the canonical type, which has the canonical base type and
3162 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003163 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003164 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3165 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3166 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003167 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003168 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003169 unsigned UniqueCount = NumProtocols;
3170
John McCallfc93cf92009-10-22 22:37:11 +00003171 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003172 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3173 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003174 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003175 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3176 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003177 }
3178
3179 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003180 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3181 }
3182
3183 unsigned Size = sizeof(ObjCObjectTypeImpl);
3184 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3185 void *Mem = Allocate(Size, TypeAlignment);
3186 ObjCObjectTypeImpl *T =
3187 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3188
3189 Types.push_back(T);
3190 ObjCObjectTypes.InsertNode(T, InsertPos);
3191 return QualType(T, 0);
3192}
3193
3194/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3195/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003196QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003197 llvm::FoldingSetNodeID ID;
3198 ObjCObjectPointerType::Profile(ID, ObjectT);
3199
3200 void *InsertPos = 0;
3201 if (ObjCObjectPointerType *QT =
3202 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3203 return QualType(QT, 0);
3204
3205 // Find the canonical object type.
3206 QualType Canonical;
3207 if (!ObjectT.isCanonical()) {
3208 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3209
3210 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003211 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3212 }
3213
Douglas Gregorf85bee62010-02-08 22:59:26 +00003214 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003215 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3216 ObjCObjectPointerType *QType =
3217 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003218
Steve Narofffb4330f2009-06-17 22:40:22 +00003219 Types.push_back(QType);
3220 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003221 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003222}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003223
Douglas Gregor1c283312010-08-11 12:19:30 +00003224/// getObjCInterfaceType - Return the unique reference to the type for the
3225/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003226QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3227 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003228 if (Decl->TypeForDecl)
3229 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003230
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003231 if (PrevDecl) {
3232 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3233 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3234 return QualType(PrevDecl->TypeForDecl, 0);
3235 }
3236
Douglas Gregor7671e532011-12-16 16:34:57 +00003237 // Prefer the definition, if there is one.
3238 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3239 Decl = Def;
3240
Douglas Gregor1c283312010-08-11 12:19:30 +00003241 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3242 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3243 Decl->TypeForDecl = T;
3244 Types.push_back(T);
3245 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003246}
3247
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003248/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3249/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003250/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003251/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003252/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003253QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003254 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003255 if (tofExpr->isTypeDependent()) {
3256 llvm::FoldingSetNodeID ID;
3257 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003258
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003259 void *InsertPos = 0;
3260 DependentTypeOfExprType *Canon
3261 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3262 if (Canon) {
3263 // We already have a "canonical" version of an identical, dependent
3264 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003265 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003266 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003267 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003268 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003269 Canon
3270 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003271 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3272 toe = Canon;
3273 }
3274 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003275 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003276 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003277 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003278 Types.push_back(toe);
3279 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003280}
3281
Steve Naroffa773cd52007-08-01 18:02:17 +00003282/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3283/// TypeOfType AST's. The only motivation to unique these nodes would be
3284/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003285/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003286/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003287QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003288 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003289 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003290 Types.push_back(tot);
3291 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003292}
3293
Anders Carlssonad6bd352009-06-24 21:24:56 +00003294
Anders Carlsson81df7b82009-06-24 19:06:50 +00003295/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3296/// DecltypeType AST's. The only motivation to unique these nodes would be
3297/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003298/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003299/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003300QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003301 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003302
3303 // C++0x [temp.type]p2:
3304 // If an expression e involves a template parameter, decltype(e) denotes a
3305 // unique dependent type. Two such decltype-specifiers refer to the same
3306 // type only if their expressions are equivalent (14.5.6.1).
3307 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003308 llvm::FoldingSetNodeID ID;
3309 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003310
Douglas Gregora21f6c32009-07-30 23:36:40 +00003311 void *InsertPos = 0;
3312 DependentDecltypeType *Canon
3313 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3314 if (Canon) {
3315 // We already have a "canonical" version of an equivalent, dependent
3316 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003317 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003318 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003319 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003320 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003321 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003322 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3323 dt = Canon;
3324 }
3325 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003326 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3327 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003328 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003329 Types.push_back(dt);
3330 return QualType(dt, 0);
3331}
3332
Alexis Hunte852b102011-05-24 22:41:36 +00003333/// getUnaryTransformationType - We don't unique these, since the memory
3334/// savings are minimal and these are rare.
3335QualType ASTContext::getUnaryTransformType(QualType BaseType,
3336 QualType UnderlyingType,
3337 UnaryTransformType::UTTKind Kind)
3338 const {
3339 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003340 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3341 Kind,
3342 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003343 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003344 Types.push_back(Ty);
3345 return QualType(Ty, 0);
3346}
3347
Richard Smithb2bc2e62011-02-21 20:05:19 +00003348/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003349QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003350 void *InsertPos = 0;
3351 if (!DeducedType.isNull()) {
3352 // Look in the folding set for an existing type.
3353 llvm::FoldingSetNodeID ID;
3354 AutoType::Profile(ID, DeducedType);
3355 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3356 return QualType(AT, 0);
3357 }
3358
3359 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3360 Types.push_back(AT);
3361 if (InsertPos)
3362 AutoTypes.InsertNode(AT, InsertPos);
3363 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003364}
3365
Eli Friedman0dfb8892011-10-06 23:00:33 +00003366/// getAtomicType - Return the uniqued reference to the atomic type for
3367/// the given value type.
3368QualType ASTContext::getAtomicType(QualType T) const {
3369 // Unique pointers, to guarantee there is only one pointer of a particular
3370 // structure.
3371 llvm::FoldingSetNodeID ID;
3372 AtomicType::Profile(ID, T);
3373
3374 void *InsertPos = 0;
3375 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3376 return QualType(AT, 0);
3377
3378 // If the atomic value type isn't canonical, this won't be a canonical type
3379 // either, so fill in the canonical type field.
3380 QualType Canonical;
3381 if (!T.isCanonical()) {
3382 Canonical = getAtomicType(getCanonicalType(T));
3383
3384 // Get the new insert position for the node we care about.
3385 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3386 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3387 }
3388 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3389 Types.push_back(New);
3390 AtomicTypes.InsertNode(New, InsertPos);
3391 return QualType(New, 0);
3392}
3393
Richard Smith02e85f32011-04-14 22:09:26 +00003394/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3395QualType ASTContext::getAutoDeductType() const {
3396 if (AutoDeductTy.isNull())
3397 AutoDeductTy = getAutoType(QualType());
3398 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3399 return AutoDeductTy;
3400}
3401
3402/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3403QualType ASTContext::getAutoRRefDeductType() const {
3404 if (AutoRRefDeductTy.isNull())
3405 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3406 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3407 return AutoRRefDeductTy;
3408}
3409
Chris Lattnerfb072462007-01-23 05:45:31 +00003410/// getTagDeclType - Return the unique reference to the type for the
3411/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003412QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003413 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003414 // FIXME: What is the design on getTagDeclType when it requires casting
3415 // away const? mutable?
3416 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003417}
3418
Mike Stump11289f42009-09-09 15:08:12 +00003419/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3420/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3421/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003422CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003423 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003424}
Chris Lattnerfb072462007-01-23 05:45:31 +00003425
Hans Wennborg27541db2011-10-27 08:29:09 +00003426/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3427CanQualType ASTContext::getIntMaxType() const {
3428 return getFromTargetType(Target->getIntMaxType());
3429}
3430
3431/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3432CanQualType ASTContext::getUIntMaxType() const {
3433 return getFromTargetType(Target->getUIntMaxType());
3434}
3435
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003436/// getSignedWCharType - Return the type of "signed wchar_t".
3437/// Used when in C++, as a GCC extension.
3438QualType ASTContext::getSignedWCharType() const {
3439 // FIXME: derive from "Target" ?
3440 return WCharTy;
3441}
3442
3443/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3444/// Used when in C++, as a GCC extension.
3445QualType ASTContext::getUnsignedWCharType() const {
3446 // FIXME: derive from "Target" ?
3447 return UnsignedIntTy;
3448}
3449
Hans Wennborg27541db2011-10-27 08:29:09 +00003450/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003451/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3452QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003453 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003454}
3455
Chris Lattnera21ad802008-04-02 05:18:44 +00003456//===----------------------------------------------------------------------===//
3457// Type Operators
3458//===----------------------------------------------------------------------===//
3459
Jay Foad39c79802011-01-12 09:06:06 +00003460CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003461 // Push qualifiers into arrays, and then discard any remaining
3462 // qualifiers.
3463 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003464 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003465 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003466 QualType Result;
3467 if (isa<ArrayType>(Ty)) {
3468 Result = getArrayDecayedType(QualType(Ty,0));
3469 } else if (isa<FunctionType>(Ty)) {
3470 Result = getPointerType(QualType(Ty, 0));
3471 } else {
3472 Result = QualType(Ty, 0);
3473 }
3474
3475 return CanQualType::CreateUnsafe(Result);
3476}
3477
John McCall6c9dd522011-01-18 07:41:22 +00003478QualType ASTContext::getUnqualifiedArrayType(QualType type,
3479 Qualifiers &quals) {
3480 SplitQualType splitType = type.getSplitUnqualifiedType();
3481
3482 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3483 // the unqualified desugared type and then drops it on the floor.
3484 // We then have to strip that sugar back off with
3485 // getUnqualifiedDesugaredType(), which is silly.
3486 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003487 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003488
3489 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003490 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003491 quals = splitType.Quals;
3492 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003493 }
3494
John McCall6c9dd522011-01-18 07:41:22 +00003495 // Otherwise, recurse on the array's element type.
3496 QualType elementType = AT->getElementType();
3497 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3498
3499 // If that didn't change the element type, AT has no qualifiers, so we
3500 // can just use the results in splitType.
3501 if (elementType == unqualElementType) {
3502 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003503 quals = splitType.Quals;
3504 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003505 }
3506
3507 // Otherwise, add in the qualifiers from the outermost type, then
3508 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003509 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003510
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003511 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003512 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003513 CAT->getSizeModifier(), 0);
3514 }
3515
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003516 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003517 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003518 }
3519
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003520 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003521 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003522 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003523 VAT->getSizeModifier(),
3524 VAT->getIndexTypeCVRQualifiers(),
3525 VAT->getBracketsRange());
3526 }
3527
3528 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003529 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003530 DSAT->getSizeModifier(), 0,
3531 SourceRange());
3532}
3533
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003534/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3535/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3536/// they point to and return true. If T1 and T2 aren't pointer types
3537/// or pointer-to-member types, or if they are not similar at this
3538/// level, returns false and leaves T1 and T2 unchanged. Top-level
3539/// qualifiers on T1 and T2 are ignored. This function will typically
3540/// be called in a loop that successively "unwraps" pointer and
3541/// pointer-to-member types to compare them at each level.
3542bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3543 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3544 *T2PtrType = T2->getAs<PointerType>();
3545 if (T1PtrType && T2PtrType) {
3546 T1 = T1PtrType->getPointeeType();
3547 T2 = T2PtrType->getPointeeType();
3548 return true;
3549 }
3550
3551 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3552 *T2MPType = T2->getAs<MemberPointerType>();
3553 if (T1MPType && T2MPType &&
3554 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3555 QualType(T2MPType->getClass(), 0))) {
3556 T1 = T1MPType->getPointeeType();
3557 T2 = T2MPType->getPointeeType();
3558 return true;
3559 }
3560
David Blaikiebbafb8a2012-03-11 07:00:24 +00003561 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003562 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3563 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3564 if (T1OPType && T2OPType) {
3565 T1 = T1OPType->getPointeeType();
3566 T2 = T2OPType->getPointeeType();
3567 return true;
3568 }
3569 }
3570
3571 // FIXME: Block pointers, too?
3572
3573 return false;
3574}
3575
Jay Foad39c79802011-01-12 09:06:06 +00003576DeclarationNameInfo
3577ASTContext::getNameForTemplate(TemplateName Name,
3578 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003579 switch (Name.getKind()) {
3580 case TemplateName::QualifiedTemplate:
3581 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003582 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003583 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3584 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003585
John McCalld9dfe3a2011-06-30 08:33:18 +00003586 case TemplateName::OverloadedTemplate: {
3587 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3588 // DNInfo work in progress: CHECKME: what about DNLoc?
3589 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3590 }
3591
3592 case TemplateName::DependentTemplate: {
3593 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003594 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003595 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003596 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3597 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003598 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003599 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3600 // DNInfo work in progress: FIXME: source locations?
3601 DeclarationNameLoc DNLoc;
3602 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3603 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3604 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003605 }
3606 }
3607
John McCalld9dfe3a2011-06-30 08:33:18 +00003608 case TemplateName::SubstTemplateTemplateParm: {
3609 SubstTemplateTemplateParmStorage *subst
3610 = Name.getAsSubstTemplateTemplateParm();
3611 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3612 NameLoc);
3613 }
3614
3615 case TemplateName::SubstTemplateTemplateParmPack: {
3616 SubstTemplateTemplateParmPackStorage *subst
3617 = Name.getAsSubstTemplateTemplateParmPack();
3618 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3619 NameLoc);
3620 }
3621 }
3622
3623 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003624}
3625
Jay Foad39c79802011-01-12 09:06:06 +00003626TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003627 switch (Name.getKind()) {
3628 case TemplateName::QualifiedTemplate:
3629 case TemplateName::Template: {
3630 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003631 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003632 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003633 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3634
3635 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003636 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003637 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003638
John McCalld9dfe3a2011-06-30 08:33:18 +00003639 case TemplateName::OverloadedTemplate:
3640 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003641
John McCalld9dfe3a2011-06-30 08:33:18 +00003642 case TemplateName::DependentTemplate: {
3643 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3644 assert(DTN && "Non-dependent template names must refer to template decls.");
3645 return DTN->CanonicalTemplateName;
3646 }
3647
3648 case TemplateName::SubstTemplateTemplateParm: {
3649 SubstTemplateTemplateParmStorage *subst
3650 = Name.getAsSubstTemplateTemplateParm();
3651 return getCanonicalTemplateName(subst->getReplacement());
3652 }
3653
3654 case TemplateName::SubstTemplateTemplateParmPack: {
3655 SubstTemplateTemplateParmPackStorage *subst
3656 = Name.getAsSubstTemplateTemplateParmPack();
3657 TemplateTemplateParmDecl *canonParameter
3658 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3659 TemplateArgument canonArgPack
3660 = getCanonicalTemplateArgument(subst->getArgumentPack());
3661 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3662 }
3663 }
3664
3665 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003666}
3667
Douglas Gregoradee3e32009-11-11 23:06:43 +00003668bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3669 X = getCanonicalTemplateName(X);
3670 Y = getCanonicalTemplateName(Y);
3671 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3672}
3673
Mike Stump11289f42009-09-09 15:08:12 +00003674TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003675ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003676 switch (Arg.getKind()) {
3677 case TemplateArgument::Null:
3678 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003679
Douglas Gregora8e02e72009-07-28 23:00:59 +00003680 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003681 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003682
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003683 case TemplateArgument::Declaration: {
3684 if (Decl *D = Arg.getAsDecl())
3685 return TemplateArgument(D->getCanonicalDecl());
3686 return TemplateArgument((Decl*)0);
3687 }
Mike Stump11289f42009-09-09 15:08:12 +00003688
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003689 case TemplateArgument::Template:
3690 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003691
3692 case TemplateArgument::TemplateExpansion:
3693 return TemplateArgument(getCanonicalTemplateName(
3694 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003695 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003696
Douglas Gregora8e02e72009-07-28 23:00:59 +00003697 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003698 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003699
Douglas Gregora8e02e72009-07-28 23:00:59 +00003700 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003701 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003702
Douglas Gregora8e02e72009-07-28 23:00:59 +00003703 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003704 if (Arg.pack_size() == 0)
3705 return Arg;
3706
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003707 TemplateArgument *CanonArgs
3708 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003709 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003710 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003711 AEnd = Arg.pack_end();
3712 A != AEnd; (void)++A, ++Idx)
3713 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003714
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003715 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003716 }
3717 }
3718
3719 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003720 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003721}
3722
Douglas Gregor333489b2009-03-27 23:10:48 +00003723NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003724ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003725 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003726 return 0;
3727
3728 switch (NNS->getKind()) {
3729 case NestedNameSpecifier::Identifier:
3730 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003731 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003732 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3733 NNS->getAsIdentifier());
3734
3735 case NestedNameSpecifier::Namespace:
3736 // A namespace is canonical; build a nested-name-specifier with
3737 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003738 return NestedNameSpecifier::Create(*this, 0,
3739 NNS->getAsNamespace()->getOriginalNamespace());
3740
3741 case NestedNameSpecifier::NamespaceAlias:
3742 // A namespace is canonical; build a nested-name-specifier with
3743 // this namespace and no prefix.
3744 return NestedNameSpecifier::Create(*this, 0,
3745 NNS->getAsNamespaceAlias()->getNamespace()
3746 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003747
3748 case NestedNameSpecifier::TypeSpec:
3749 case NestedNameSpecifier::TypeSpecWithTemplate: {
3750 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003751
3752 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3753 // break it apart into its prefix and identifier, then reconsititute those
3754 // as the canonical nested-name-specifier. This is required to canonicalize
3755 // a dependent nested-name-specifier involving typedefs of dependent-name
3756 // types, e.g.,
3757 // typedef typename T::type T1;
3758 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003759 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3760 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003761 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003762
Eli Friedman5358a0a2012-03-03 04:09:56 +00003763 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3764 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3765 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003766 return NestedNameSpecifier::Create(*this, 0, false,
3767 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003768 }
3769
3770 case NestedNameSpecifier::Global:
3771 // The global specifier is canonical and unique.
3772 return NNS;
3773 }
3774
David Blaikie8a40f702012-01-17 06:56:22 +00003775 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003776}
3777
Chris Lattner7adf0762008-08-04 07:31:14 +00003778
Jay Foad39c79802011-01-12 09:06:06 +00003779const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003780 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003781 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003782 // Handle the common positive case fast.
3783 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3784 return AT;
3785 }
Mike Stump11289f42009-09-09 15:08:12 +00003786
John McCall8ccfcb52009-09-24 19:53:00 +00003787 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003788 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003789 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003790
John McCall8ccfcb52009-09-24 19:53:00 +00003791 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003792 // implements C99 6.7.3p8: "If the specification of an array type includes
3793 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003794
Chris Lattner7adf0762008-08-04 07:31:14 +00003795 // If we get here, we either have type qualifiers on the type, or we have
3796 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003797 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003798
John McCall33ddac02011-01-19 10:06:00 +00003799 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003800 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003801
Chris Lattner7adf0762008-08-04 07:31:14 +00003802 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003803 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003804 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003805 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003806
Chris Lattner7adf0762008-08-04 07:31:14 +00003807 // Otherwise, we have an array and we have qualifiers on it. Push the
3808 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003809 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003810
Chris Lattner7adf0762008-08-04 07:31:14 +00003811 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3812 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3813 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003814 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003815 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3816 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3817 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003818 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003819
Mike Stump11289f42009-09-09 15:08:12 +00003820 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003821 = dyn_cast<DependentSizedArrayType>(ATy))
3822 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003823 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003824 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003825 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003826 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003827 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003828
Chris Lattner7adf0762008-08-04 07:31:14 +00003829 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003830 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003831 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003832 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003833 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003834 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003835}
3836
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003837QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003838 // C99 6.7.5.3p7:
3839 // A declaration of a parameter as "array of type" shall be
3840 // adjusted to "qualified pointer to type", where the type
3841 // qualifiers (if any) are those specified within the [ and ] of
3842 // the array type derivation.
3843 if (T->isArrayType())
3844 return getArrayDecayedType(T);
3845
3846 // C99 6.7.5.3p8:
3847 // A declaration of a parameter as "function returning type"
3848 // shall be adjusted to "pointer to function returning type", as
3849 // in 6.3.2.1.
3850 if (T->isFunctionType())
3851 return getPointerType(T);
3852
3853 return T;
3854}
3855
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003856QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003857 T = getVariableArrayDecayedType(T);
3858 T = getAdjustedParameterType(T);
3859 return T.getUnqualifiedType();
3860}
3861
Chris Lattnera21ad802008-04-02 05:18:44 +00003862/// getArrayDecayedType - Return the properly qualified result of decaying the
3863/// specified array type to a pointer. This operation is non-trivial when
3864/// handling typedefs etc. The canonical type of "T" must be an array type,
3865/// this returns a pointer to a properly qualified element of the array.
3866///
3867/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003868QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003869 // Get the element type with 'getAsArrayType' so that we don't lose any
3870 // typedefs in the element type of the array. This also handles propagation
3871 // of type qualifiers from the array type into the element type if present
3872 // (C99 6.7.3p8).
3873 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3874 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003875
Chris Lattner7adf0762008-08-04 07:31:14 +00003876 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003877
3878 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003879 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003880}
3881
John McCall33ddac02011-01-19 10:06:00 +00003882QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3883 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003884}
3885
John McCall33ddac02011-01-19 10:06:00 +00003886QualType ASTContext::getBaseElementType(QualType type) const {
3887 Qualifiers qs;
3888 while (true) {
3889 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003890 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003891 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003892
John McCall33ddac02011-01-19 10:06:00 +00003893 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003894 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003895 }
Mike Stump11289f42009-09-09 15:08:12 +00003896
John McCall33ddac02011-01-19 10:06:00 +00003897 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003898}
3899
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003900/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003901uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003902ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3903 uint64_t ElementCount = 1;
3904 do {
3905 ElementCount *= CA->getSize().getZExtValue();
3906 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3907 } while (CA);
3908 return ElementCount;
3909}
3910
Steve Naroff0af91202007-04-27 21:51:21 +00003911/// getFloatingRank - Return a relative rank for floating point types.
3912/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003913static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003914 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003915 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003916
John McCall9dd450b2009-09-21 23:43:11 +00003917 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3918 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003919 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003920 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003921 case BuiltinType::Float: return FloatRank;
3922 case BuiltinType::Double: return DoubleRank;
3923 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003924 }
3925}
3926
Mike Stump11289f42009-09-09 15:08:12 +00003927/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3928/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003929/// 'typeDomain' is a real floating point or complex type.
3930/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003931QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3932 QualType Domain) const {
3933 FloatingRank EltRank = getFloatingRank(Size);
3934 if (Domain->isComplexType()) {
3935 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003936 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003937 case FloatRank: return FloatComplexTy;
3938 case DoubleRank: return DoubleComplexTy;
3939 case LongDoubleRank: return LongDoubleComplexTy;
3940 }
Steve Naroff0af91202007-04-27 21:51:21 +00003941 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003942
3943 assert(Domain->isRealFloatingType() && "Unknown domain!");
3944 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003945 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003946 case FloatRank: return FloatTy;
3947 case DoubleRank: return DoubleTy;
3948 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003949 }
David Blaikief47fa302012-01-17 02:30:50 +00003950 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003951}
3952
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003953/// getFloatingTypeOrder - Compare the rank of the two specified floating
3954/// point types, ignoring the domain of the type (i.e. 'double' ==
3955/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003956/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003957int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003958 FloatingRank LHSR = getFloatingRank(LHS);
3959 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003960
Chris Lattnerb90739d2008-04-06 23:38:49 +00003961 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003962 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003963 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003964 return 1;
3965 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003966}
3967
Chris Lattner76a00cf2008-04-06 22:59:24 +00003968/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3969/// routine will assert if passed a built-in type that isn't an integer or enum,
3970/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003971unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003972 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003973
Chris Lattner76a00cf2008-04-06 22:59:24 +00003974 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003975 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003976 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003977 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003978 case BuiltinType::Char_S:
3979 case BuiltinType::Char_U:
3980 case BuiltinType::SChar:
3981 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003982 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003983 case BuiltinType::Short:
3984 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003985 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003986 case BuiltinType::Int:
3987 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003988 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003989 case BuiltinType::Long:
3990 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003991 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003992 case BuiltinType::LongLong:
3993 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003994 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003995 case BuiltinType::Int128:
3996 case BuiltinType::UInt128:
3997 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003998 }
3999}
4000
Eli Friedman629ffb92009-08-20 04:21:42 +00004001/// \brief Whether this is a promotable bitfield reference according
4002/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4003///
4004/// \returns the type this bit-field will promote to, or NULL if no
4005/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004006QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004007 if (E->isTypeDependent() || E->isValueDependent())
4008 return QualType();
4009
Eli Friedman629ffb92009-08-20 04:21:42 +00004010 FieldDecl *Field = E->getBitField();
4011 if (!Field)
4012 return QualType();
4013
4014 QualType FT = Field->getType();
4015
Richard Smithcaf33902011-10-10 18:28:20 +00004016 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004017 uint64_t IntSize = getTypeSize(IntTy);
4018 // GCC extension compatibility: if the bit-field size is less than or equal
4019 // to the size of int, it gets promoted no matter what its type is.
4020 // For instance, unsigned long bf : 4 gets promoted to signed int.
4021 if (BitWidth < IntSize)
4022 return IntTy;
4023
4024 if (BitWidth == IntSize)
4025 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4026
4027 // Types bigger than int are not subject to promotions, and therefore act
4028 // like the base type.
4029 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4030 // is ridiculous.
4031 return QualType();
4032}
4033
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004034/// getPromotedIntegerType - Returns the type that Promotable will
4035/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4036/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004037QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004038 assert(!Promotable.isNull());
4039 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004040 if (const EnumType *ET = Promotable->getAs<EnumType>())
4041 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004042
4043 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4044 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4045 // (3.9.1) can be converted to a prvalue of the first of the following
4046 // types that can represent all the values of its underlying type:
4047 // int, unsigned int, long int, unsigned long int, long long int, or
4048 // unsigned long long int [...]
4049 // FIXME: Is there some better way to compute this?
4050 if (BT->getKind() == BuiltinType::WChar_S ||
4051 BT->getKind() == BuiltinType::WChar_U ||
4052 BT->getKind() == BuiltinType::Char16 ||
4053 BT->getKind() == BuiltinType::Char32) {
4054 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4055 uint64_t FromSize = getTypeSize(BT);
4056 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4057 LongLongTy, UnsignedLongLongTy };
4058 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4059 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4060 if (FromSize < ToSize ||
4061 (FromSize == ToSize &&
4062 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4063 return PromoteTypes[Idx];
4064 }
4065 llvm_unreachable("char type should fit into long long");
4066 }
4067 }
4068
4069 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004070 if (Promotable->isSignedIntegerType())
4071 return IntTy;
4072 uint64_t PromotableSize = getTypeSize(Promotable);
4073 uint64_t IntSize = getTypeSize(IntTy);
4074 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4075 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4076}
4077
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004078/// \brief Recurses in pointer/array types until it finds an objc retainable
4079/// type and returns its ownership.
4080Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4081 while (!T.isNull()) {
4082 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4083 return T.getObjCLifetime();
4084 if (T->isArrayType())
4085 T = getBaseElementType(T);
4086 else if (const PointerType *PT = T->getAs<PointerType>())
4087 T = PT->getPointeeType();
4088 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004089 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004090 else
4091 break;
4092 }
4093
4094 return Qualifiers::OCL_None;
4095}
4096
Mike Stump11289f42009-09-09 15:08:12 +00004097/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004098/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004099/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004100int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004101 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4102 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004103 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004104
Chris Lattner76a00cf2008-04-06 22:59:24 +00004105 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4106 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004107
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004108 unsigned LHSRank = getIntegerRank(LHSC);
4109 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004110
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004111 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4112 if (LHSRank == RHSRank) return 0;
4113 return LHSRank > RHSRank ? 1 : -1;
4114 }
Mike Stump11289f42009-09-09 15:08:12 +00004115
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004116 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4117 if (LHSUnsigned) {
4118 // If the unsigned [LHS] type is larger, return it.
4119 if (LHSRank >= RHSRank)
4120 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004121
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004122 // If the signed type can represent all values of the unsigned type, it
4123 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004124 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004125 return -1;
4126 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004127
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004128 // If the unsigned [RHS] type is larger, return it.
4129 if (RHSRank >= LHSRank)
4130 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004131
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004132 // If the signed type can represent all values of the unsigned type, it
4133 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004134 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004135 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004136}
Anders Carlsson98f07902007-08-17 05:31:46 +00004137
Anders Carlsson6d417272009-11-14 21:45:58 +00004138static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004139CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4140 DeclContext *DC, IdentifierInfo *Id) {
4141 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004142 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004143 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004144 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004145 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004146}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004147
Mike Stump11289f42009-09-09 15:08:12 +00004148// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004149QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004150 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004151 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004152 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004153 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004154 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004155
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004156 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004157
Anders Carlsson98f07902007-08-17 05:31:46 +00004158 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004159 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004160 // int flags;
4161 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004162 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004163 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004164 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004165 FieldTypes[3] = LongTy;
4166
Anders Carlsson98f07902007-08-17 05:31:46 +00004167 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004168 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004169 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004170 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004171 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004172 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004173 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004174 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004175 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004176 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004177 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004178 }
4179
Douglas Gregord5058122010-02-11 01:19:42 +00004180 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004181 }
Mike Stump11289f42009-09-09 15:08:12 +00004182
Anders Carlsson98f07902007-08-17 05:31:46 +00004183 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004184}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004185
Douglas Gregor512b0772009-04-23 22:29:11 +00004186void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004187 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004188 assert(Rec && "Invalid CFConstantStringType");
4189 CFConstantStringTypeDecl = Rec->getDecl();
4190}
4191
Jay Foad39c79802011-01-12 09:06:06 +00004192QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004193 if (BlockDescriptorType)
4194 return getTagDeclType(BlockDescriptorType);
4195
4196 RecordDecl *T;
4197 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004198 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004199 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004200 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004201
4202 QualType FieldTypes[] = {
4203 UnsignedLongTy,
4204 UnsignedLongTy,
4205 };
4206
4207 const char *FieldNames[] = {
4208 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004209 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004210 };
4211
4212 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004213 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004214 SourceLocation(),
4215 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004216 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004217 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004218 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004219 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004220 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004221 T->addDecl(Field);
4222 }
4223
Douglas Gregord5058122010-02-11 01:19:42 +00004224 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004225
4226 BlockDescriptorType = T;
4227
4228 return getTagDeclType(BlockDescriptorType);
4229}
4230
Jay Foad39c79802011-01-12 09:06:06 +00004231QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004232 if (BlockDescriptorExtendedType)
4233 return getTagDeclType(BlockDescriptorExtendedType);
4234
4235 RecordDecl *T;
4236 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004237 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004238 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004239 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004240
4241 QualType FieldTypes[] = {
4242 UnsignedLongTy,
4243 UnsignedLongTy,
4244 getPointerType(VoidPtrTy),
4245 getPointerType(VoidPtrTy)
4246 };
4247
4248 const char *FieldNames[] = {
4249 "reserved",
4250 "Size",
4251 "CopyFuncPtr",
4252 "DestroyFuncPtr"
4253 };
4254
4255 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004256 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004257 SourceLocation(),
4258 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004259 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004260 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004261 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004262 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004263 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004264 T->addDecl(Field);
4265 }
4266
Douglas Gregord5058122010-02-11 01:19:42 +00004267 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004268
4269 BlockDescriptorExtendedType = T;
4270
4271 return getTagDeclType(BlockDescriptorExtendedType);
4272}
4273
Jay Foad39c79802011-01-12 09:06:06 +00004274bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004275 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004276 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004277 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004278 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4279 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004280 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004281
4282 }
4283 }
Mike Stump94967902009-10-21 18:16:27 +00004284 return false;
4285}
4286
Jay Foad39c79802011-01-12 09:06:06 +00004287QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004288ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004289 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004290 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004291 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004292 // unsigned int __flags;
4293 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004294 // void *__copy_helper; // as needed
4295 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004296 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004297 // } *
4298
Mike Stump94967902009-10-21 18:16:27 +00004299 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4300
4301 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004302 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004303 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4304 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004305 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004306 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004307 T->startDefinition();
4308 QualType Int32Ty = IntTy;
4309 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4310 QualType FieldTypes[] = {
4311 getPointerType(VoidPtrTy),
4312 getPointerType(getTagDeclType(T)),
4313 Int32Ty,
4314 Int32Ty,
4315 getPointerType(VoidPtrTy),
4316 getPointerType(VoidPtrTy),
4317 Ty
4318 };
4319
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004320 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004321 "__isa",
4322 "__forwarding",
4323 "__flags",
4324 "__size",
4325 "__copy_helper",
4326 "__destroy_helper",
4327 DeclName,
4328 };
4329
4330 for (size_t i = 0; i < 7; ++i) {
4331 if (!HasCopyAndDispose && i >=4 && i <= 5)
4332 continue;
4333 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004334 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004335 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004336 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004337 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004338 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004339 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004340 T->addDecl(Field);
4341 }
4342
Douglas Gregord5058122010-02-11 01:19:42 +00004343 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004344
4345 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004346}
4347
Douglas Gregorbab8a962011-09-08 01:46:34 +00004348TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4349 if (!ObjCInstanceTypeDecl)
4350 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4351 getTranslationUnitDecl(),
4352 SourceLocation(),
4353 SourceLocation(),
4354 &Idents.get("instancetype"),
4355 getTrivialTypeSourceInfo(getObjCIdType()));
4356 return ObjCInstanceTypeDecl;
4357}
4358
Anders Carlsson18acd442007-10-29 06:33:42 +00004359// This returns true if a type has been typedefed to BOOL:
4360// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004361static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004362 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004363 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4364 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004365
Anders Carlssond8499822007-10-29 05:01:08 +00004366 return false;
4367}
4368
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004369/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004370/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004371CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004372 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4373 return CharUnits::Zero();
4374
Ken Dyck40775002010-01-11 17:06:35 +00004375 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004376
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004377 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004378 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004379 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004380 // Treat arrays as pointers, since that's how they're passed in.
4381 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004382 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004383 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004384}
4385
4386static inline
4387std::string charUnitsToString(const CharUnits &CU) {
4388 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004389}
4390
John McCall351762c2011-02-07 10:33:21 +00004391/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004392/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004393std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4394 std::string S;
4395
David Chisnall950a9512009-11-17 19:33:30 +00004396 const BlockDecl *Decl = Expr->getBlockDecl();
4397 QualType BlockTy =
4398 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4399 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004400 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004401 // Compute size of all parameters.
4402 // Start with computing size of a pointer in number of bytes.
4403 // FIXME: There might(should) be a better way of doing this computation!
4404 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004405 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4406 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004407 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004408 E = Decl->param_end(); PI != E; ++PI) {
4409 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004410 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004411 if (sz.isZero())
4412 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004413 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004414 ParmOffset += sz;
4415 }
4416 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004417 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004418 // Block pointer and offset.
4419 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004420
4421 // Argument types.
4422 ParmOffset = PtrSize;
4423 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4424 Decl->param_end(); PI != E; ++PI) {
4425 ParmVarDecl *PVDecl = *PI;
4426 QualType PType = PVDecl->getOriginalType();
4427 if (const ArrayType *AT =
4428 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4429 // Use array's original type only if it has known number of
4430 // elements.
4431 if (!isa<ConstantArrayType>(AT))
4432 PType = PVDecl->getType();
4433 } else if (PType->isFunctionType())
4434 PType = PVDecl->getType();
4435 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004436 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004437 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004438 }
John McCall351762c2011-02-07 10:33:21 +00004439
4440 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004441}
4442
Douglas Gregora9d84932011-05-27 01:19:52 +00004443bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004444 std::string& S) {
4445 // Encode result type.
4446 getObjCEncodingForType(Decl->getResultType(), S);
4447 CharUnits ParmOffset;
4448 // Compute size of all parameters.
4449 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4450 E = Decl->param_end(); PI != E; ++PI) {
4451 QualType PType = (*PI)->getType();
4452 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004453 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004454 continue;
4455
David Chisnall50e4eba2010-12-30 14:05:53 +00004456 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004457 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004458 ParmOffset += sz;
4459 }
4460 S += charUnitsToString(ParmOffset);
4461 ParmOffset = CharUnits::Zero();
4462
4463 // Argument types.
4464 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4465 E = Decl->param_end(); PI != E; ++PI) {
4466 ParmVarDecl *PVDecl = *PI;
4467 QualType PType = PVDecl->getOriginalType();
4468 if (const ArrayType *AT =
4469 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4470 // Use array's original type only if it has known number of
4471 // elements.
4472 if (!isa<ConstantArrayType>(AT))
4473 PType = PVDecl->getType();
4474 } else if (PType->isFunctionType())
4475 PType = PVDecl->getType();
4476 getObjCEncodingForType(PType, S);
4477 S += charUnitsToString(ParmOffset);
4478 ParmOffset += getObjCEncodingTypeSize(PType);
4479 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004480
4481 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004482}
4483
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004484/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4485/// method parameter or return type. If Extended, include class names and
4486/// block object types.
4487void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4488 QualType T, std::string& S,
4489 bool Extended) const {
4490 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4491 getObjCEncodingForTypeQualifier(QT, S);
4492 // Encode parameter type.
4493 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4494 true /*OutermostType*/,
4495 false /*EncodingProperty*/,
4496 false /*StructField*/,
4497 Extended /*EncodeBlockParameters*/,
4498 Extended /*EncodeClassNames*/);
4499}
4500
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004501/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004502/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004503bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004504 std::string& S,
4505 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004506 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004507 // Encode return type.
4508 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4509 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004510 // Compute size of all parameters.
4511 // Start with computing size of a pointer in number of bytes.
4512 // FIXME: There might(should) be a better way of doing this computation!
4513 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004514 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004515 // The first two arguments (self and _cmd) are pointers; account for
4516 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004517 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004518 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004519 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004520 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004521 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004522 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004523 continue;
4524
Ken Dyck40775002010-01-11 17:06:35 +00004525 assert (sz.isPositive() &&
4526 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004527 ParmOffset += sz;
4528 }
Ken Dyck40775002010-01-11 17:06:35 +00004529 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004530 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004531 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004532
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004533 // Argument types.
4534 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004535 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004536 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004537 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004538 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004539 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004540 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4541 // Use array's original type only if it has known number of
4542 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004543 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004544 PType = PVDecl->getType();
4545 } else if (PType->isFunctionType())
4546 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004547 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4548 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004549 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004550 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004551 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004552
4553 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004554}
4555
Daniel Dunbar4932b362008-08-28 04:38:10 +00004556/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004557/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004558/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4559/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004560/// Property attributes are stored as a comma-delimited C string. The simple
4561/// attributes readonly and bycopy are encoded as single characters. The
4562/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4563/// encoded as single characters, followed by an identifier. Property types
4564/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004565/// these attributes are defined by the following enumeration:
4566/// @code
4567/// enum PropertyAttributes {
4568/// kPropertyReadOnly = 'R', // property is read-only.
4569/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4570/// kPropertyByref = '&', // property is a reference to the value last assigned
4571/// kPropertyDynamic = 'D', // property is dynamic
4572/// kPropertyGetter = 'G', // followed by getter selector name
4573/// kPropertySetter = 'S', // followed by setter selector name
4574/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004575/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004576/// kPropertyWeak = 'W' // 'weak' property
4577/// kPropertyStrong = 'P' // property GC'able
4578/// kPropertyNonAtomic = 'N' // property non-atomic
4579/// };
4580/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004581void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004582 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004583 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004584 // Collect information from the property implementation decl(s).
4585 bool Dynamic = false;
4586 ObjCPropertyImplDecl *SynthesizePID = 0;
4587
4588 // FIXME: Duplicated code due to poor abstraction.
4589 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004590 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004591 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4592 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004593 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004594 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004595 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004596 if (PID->getPropertyDecl() == PD) {
4597 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4598 Dynamic = true;
4599 } else {
4600 SynthesizePID = PID;
4601 }
4602 }
4603 }
4604 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004605 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004606 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004607 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004608 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004609 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004610 if (PID->getPropertyDecl() == PD) {
4611 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4612 Dynamic = true;
4613 } else {
4614 SynthesizePID = PID;
4615 }
4616 }
Mike Stump11289f42009-09-09 15:08:12 +00004617 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004618 }
4619 }
4620
4621 // FIXME: This is not very efficient.
4622 S = "T";
4623
4624 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004625 // GCC has some special rules regarding encoding of properties which
4626 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004627 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004628 true /* outermost type */,
4629 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004630
4631 if (PD->isReadOnly()) {
4632 S += ",R";
4633 } else {
4634 switch (PD->getSetterKind()) {
4635 case ObjCPropertyDecl::Assign: break;
4636 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004637 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004638 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004639 }
4640 }
4641
4642 // It really isn't clear at all what this means, since properties
4643 // are "dynamic by default".
4644 if (Dynamic)
4645 S += ",D";
4646
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004647 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4648 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004649
Daniel Dunbar4932b362008-08-28 04:38:10 +00004650 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4651 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004652 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004653 }
4654
4655 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4656 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004657 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004658 }
4659
4660 if (SynthesizePID) {
4661 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4662 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004663 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004664 }
4665
4666 // FIXME: OBJCGC: weak & strong
4667}
4668
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004669/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004670/// Another legacy compatibility encoding: 32-bit longs are encoded as
4671/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004672/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4673///
4674void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004675 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004676 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004677 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004678 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004679 else
Jay Foad39c79802011-01-12 09:06:06 +00004680 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004681 PointeeTy = IntTy;
4682 }
4683 }
4684}
4685
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004686void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004687 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004688 // We follow the behavior of gcc, expanding structures which are
4689 // directly pointed to, and expanding embedded structures. Note that
4690 // these rules are sufficient to prevent recursive encoding of the
4691 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004692 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004693 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004694}
4695
David Chisnallb190a2c2010-06-04 01:10:52 +00004696static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4697 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004698 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004699 case BuiltinType::Void: return 'v';
4700 case BuiltinType::Bool: return 'B';
4701 case BuiltinType::Char_U:
4702 case BuiltinType::UChar: return 'C';
4703 case BuiltinType::UShort: return 'S';
4704 case BuiltinType::UInt: return 'I';
4705 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004706 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004707 case BuiltinType::UInt128: return 'T';
4708 case BuiltinType::ULongLong: return 'Q';
4709 case BuiltinType::Char_S:
4710 case BuiltinType::SChar: return 'c';
4711 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004712 case BuiltinType::WChar_S:
4713 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004714 case BuiltinType::Int: return 'i';
4715 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004716 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004717 case BuiltinType::LongLong: return 'q';
4718 case BuiltinType::Int128: return 't';
4719 case BuiltinType::Float: return 'f';
4720 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004721 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004722 }
4723}
4724
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004725static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4726 EnumDecl *Enum = ET->getDecl();
4727
4728 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4729 if (!Enum->isFixed())
4730 return 'i';
4731
4732 // The encoding of a fixed enum type matches its fixed underlying type.
4733 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4734}
4735
Jay Foad39c79802011-01-12 09:06:06 +00004736static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004737 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004738 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004739 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004740 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4741 // The GNU runtime requires more information; bitfields are encoded as b,
4742 // then the offset (in bits) of the first element, then the type of the
4743 // bitfield, then the size in bits. For example, in this structure:
4744 //
4745 // struct
4746 // {
4747 // int integer;
4748 // int flags:2;
4749 // };
4750 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4751 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4752 // information is not especially sensible, but we're stuck with it for
4753 // compatibility with GCC, although providing it breaks anything that
4754 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004755 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004756 const RecordDecl *RD = FD->getParent();
4757 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004758 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004759 if (const EnumType *ET = T->getAs<EnumType>())
4760 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004761 else
Jay Foad39c79802011-01-12 09:06:06 +00004762 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004763 }
Richard Smithcaf33902011-10-10 18:28:20 +00004764 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004765}
4766
Daniel Dunbar07d07852009-10-18 21:17:35 +00004767// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004768void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4769 bool ExpandPointedToStructures,
4770 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004771 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004772 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004773 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004774 bool StructField,
4775 bool EncodeBlockParameters,
4776 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004777 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004778 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004779 return EncodeBitField(this, S, T, FD);
4780 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004781 return;
4782 }
Mike Stump11289f42009-09-09 15:08:12 +00004783
John McCall9dd450b2009-09-21 23:43:11 +00004784 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004785 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004786 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004787 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004788 return;
4789 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004790
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004791 // encoding for pointer or r3eference types.
4792 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004793 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004794 if (PT->isObjCSelType()) {
4795 S += ':';
4796 return;
4797 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004798 PointeeTy = PT->getPointeeType();
4799 }
4800 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4801 PointeeTy = RT->getPointeeType();
4802 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004803 bool isReadOnly = false;
4804 // For historical/compatibility reasons, the read-only qualifier of the
4805 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4806 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004807 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004808 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004809 if (OutermostType && T.isConstQualified()) {
4810 isReadOnly = true;
4811 S += 'r';
4812 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004813 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004814 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004815 while (P->getAs<PointerType>())
4816 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004817 if (P.isConstQualified()) {
4818 isReadOnly = true;
4819 S += 'r';
4820 }
4821 }
4822 if (isReadOnly) {
4823 // Another legacy compatibility encoding. Some ObjC qualifier and type
4824 // combinations need to be rearranged.
4825 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004826 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004827 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004828 }
Mike Stump11289f42009-09-09 15:08:12 +00004829
Anders Carlssond8499822007-10-29 05:01:08 +00004830 if (PointeeTy->isCharType()) {
4831 // char pointer types should be encoded as '*' unless it is a
4832 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004833 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004834 S += '*';
4835 return;
4836 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004837 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004838 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4839 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4840 S += '#';
4841 return;
4842 }
4843 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4844 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4845 S += '@';
4846 return;
4847 }
4848 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004849 }
Anders Carlssond8499822007-10-29 05:01:08 +00004850 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004851 getLegacyIntegralTypeEncoding(PointeeTy);
4852
Mike Stump11289f42009-09-09 15:08:12 +00004853 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004854 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004855 return;
4856 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004857
Chris Lattnere7cabb92009-07-13 00:10:46 +00004858 if (const ArrayType *AT =
4859 // Ignore type qualifiers etc.
4860 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004861 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004862 // Incomplete arrays are encoded as a pointer to the array element.
4863 S += '^';
4864
Mike Stump11289f42009-09-09 15:08:12 +00004865 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004866 false, ExpandStructures, FD);
4867 } else {
4868 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004869
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004870 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4871 if (getTypeSize(CAT->getElementType()) == 0)
4872 S += '0';
4873 else
4874 S += llvm::utostr(CAT->getSize().getZExtValue());
4875 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004876 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004877 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4878 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004879 S += '0';
4880 }
Mike Stump11289f42009-09-09 15:08:12 +00004881
4882 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004883 false, ExpandStructures, FD);
4884 S += ']';
4885 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004886 return;
4887 }
Mike Stump11289f42009-09-09 15:08:12 +00004888
John McCall9dd450b2009-09-21 23:43:11 +00004889 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004890 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004891 return;
4892 }
Mike Stump11289f42009-09-09 15:08:12 +00004893
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004894 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004895 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004896 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004897 // Anonymous structures print as '?'
4898 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4899 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004900 if (ClassTemplateSpecializationDecl *Spec
4901 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4902 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4903 std::string TemplateArgsStr
4904 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004905 TemplateArgs.data(),
4906 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004907 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004908
4909 S += TemplateArgsStr;
4910 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004911 } else {
4912 S += '?';
4913 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004914 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004915 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004916 if (!RDecl->isUnion()) {
4917 getObjCEncodingForStructureImpl(RDecl, S, FD);
4918 } else {
4919 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4920 FieldEnd = RDecl->field_end();
4921 Field != FieldEnd; ++Field) {
4922 if (FD) {
4923 S += '"';
4924 S += Field->getNameAsString();
4925 S += '"';
4926 }
Mike Stump11289f42009-09-09 15:08:12 +00004927
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004928 // Special case bit-fields.
4929 if (Field->isBitField()) {
4930 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004931 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004932 } else {
4933 QualType qt = Field->getType();
4934 getLegacyIntegralTypeEncoding(qt);
4935 getObjCEncodingForTypeImpl(qt, S, false, true,
4936 FD, /*OutermostType*/false,
4937 /*EncodingProperty*/false,
4938 /*StructField*/true);
4939 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004940 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004941 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004942 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004943 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004944 return;
4945 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004946
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004947 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004948 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004949 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004950 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004951 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004952 return;
4953 }
Mike Stump11289f42009-09-09 15:08:12 +00004954
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004955 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004956 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004957 if (EncodeBlockParameters) {
4958 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4959
4960 S += '<';
4961 // Block return type
4962 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4963 ExpandPointedToStructures, ExpandStructures,
4964 FD,
4965 false /* OutermostType */,
4966 EncodingProperty,
4967 false /* StructField */,
4968 EncodeBlockParameters,
4969 EncodeClassNames);
4970 // Block self
4971 S += "@?";
4972 // Block parameters
4973 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4974 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4975 E = FPT->arg_type_end(); I && (I != E); ++I) {
4976 getObjCEncodingForTypeImpl(*I, S,
4977 ExpandPointedToStructures,
4978 ExpandStructures,
4979 FD,
4980 false /* OutermostType */,
4981 EncodingProperty,
4982 false /* StructField */,
4983 EncodeBlockParameters,
4984 EncodeClassNames);
4985 }
4986 }
4987 S += '>';
4988 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004989 return;
4990 }
Mike Stump11289f42009-09-09 15:08:12 +00004991
John McCall8b07ec22010-05-15 11:32:37 +00004992 // Ignore protocol qualifiers when mangling at this level.
4993 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4994 T = OT->getBaseType();
4995
John McCall8ccfcb52009-09-24 19:53:00 +00004996 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004997 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004998 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004999 S += '{';
5000 const IdentifierInfo *II = OI->getIdentifier();
5001 S += II->getName();
5002 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005003 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005004 DeepCollectObjCIvars(OI, true, Ivars);
5005 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005006 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005007 if (Field->isBitField())
5008 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005009 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005010 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005011 }
5012 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005013 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005014 }
Mike Stump11289f42009-09-09 15:08:12 +00005015
John McCall9dd450b2009-09-21 23:43:11 +00005016 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005017 if (OPT->isObjCIdType()) {
5018 S += '@';
5019 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005020 }
Mike Stump11289f42009-09-09 15:08:12 +00005021
Steve Narofff0c86112009-10-28 22:03:49 +00005022 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5023 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5024 // Since this is a binary compatibility issue, need to consult with runtime
5025 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005026 S += '#';
5027 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005028 }
Mike Stump11289f42009-09-09 15:08:12 +00005029
Chris Lattnere7cabb92009-07-13 00:10:46 +00005030 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005031 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005032 ExpandPointedToStructures,
5033 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005034 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005035 // Note that we do extended encoding of protocol qualifer list
5036 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005037 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005038 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5039 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005040 S += '<';
5041 S += (*I)->getNameAsString();
5042 S += '>';
5043 }
5044 S += '"';
5045 }
5046 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005047 }
Mike Stump11289f42009-09-09 15:08:12 +00005048
Chris Lattnere7cabb92009-07-13 00:10:46 +00005049 QualType PointeeTy = OPT->getPointeeType();
5050 if (!EncodingProperty &&
5051 isa<TypedefType>(PointeeTy.getTypePtr())) {
5052 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005053 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005054 // {...};
5055 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005056 getObjCEncodingForTypeImpl(PointeeTy, S,
5057 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00005058 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005059 return;
5060 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005061
5062 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005063 if (OPT->getInterfaceDecl() &&
5064 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005065 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005066 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005067 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5068 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005069 S += '<';
5070 S += (*I)->getNameAsString();
5071 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005072 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005073 S += '"';
5074 }
5075 return;
5076 }
Mike Stump11289f42009-09-09 15:08:12 +00005077
John McCalla9e6e8d2010-05-17 23:56:34 +00005078 // gcc just blithely ignores member pointers.
5079 // TODO: maybe there should be a mangling for these
5080 if (T->getAs<MemberPointerType>())
5081 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005082
5083 if (T->isVectorType()) {
5084 // This matches gcc's encoding, even though technically it is
5085 // insufficient.
5086 // FIXME. We should do a better job than gcc.
5087 return;
5088 }
5089
David Blaikie83d382b2011-09-23 05:06:16 +00005090 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00005091}
5092
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005093void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5094 std::string &S,
5095 const FieldDecl *FD,
5096 bool includeVBases) const {
5097 assert(RDecl && "Expected non-null RecordDecl");
5098 assert(!RDecl->isUnion() && "Should not be called for unions");
5099 if (!RDecl->getDefinition())
5100 return;
5101
5102 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5103 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5104 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5105
5106 if (CXXRec) {
5107 for (CXXRecordDecl::base_class_iterator
5108 BI = CXXRec->bases_begin(),
5109 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5110 if (!BI->isVirtual()) {
5111 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005112 if (base->isEmpty())
5113 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005114 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005115 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5116 std::make_pair(offs, base));
5117 }
5118 }
5119 }
5120
5121 unsigned i = 0;
5122 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5123 FieldEnd = RDecl->field_end();
5124 Field != FieldEnd; ++Field, ++i) {
5125 uint64_t offs = layout.getFieldOffset(i);
5126 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005127 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005128 }
5129
5130 if (CXXRec && includeVBases) {
5131 for (CXXRecordDecl::base_class_iterator
5132 BI = CXXRec->vbases_begin(),
5133 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5134 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005135 if (base->isEmpty())
5136 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005137 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005138 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5139 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5140 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005141 }
5142 }
5143
5144 CharUnits size;
5145 if (CXXRec) {
5146 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5147 } else {
5148 size = layout.getSize();
5149 }
5150
5151 uint64_t CurOffs = 0;
5152 std::multimap<uint64_t, NamedDecl *>::iterator
5153 CurLayObj = FieldOrBaseOffsets.begin();
5154
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005155 if (CXXRec && CXXRec->isDynamicClass() &&
5156 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005157 if (FD) {
5158 S += "\"_vptr$";
5159 std::string recname = CXXRec->getNameAsString();
5160 if (recname.empty()) recname = "?";
5161 S += recname;
5162 S += '"';
5163 }
5164 S += "^^?";
5165 CurOffs += getTypeSize(VoidPtrTy);
5166 }
5167
5168 if (!RDecl->hasFlexibleArrayMember()) {
5169 // Mark the end of the structure.
5170 uint64_t offs = toBits(size);
5171 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5172 std::make_pair(offs, (NamedDecl*)0));
5173 }
5174
5175 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5176 assert(CurOffs <= CurLayObj->first);
5177
5178 if (CurOffs < CurLayObj->first) {
5179 uint64_t padding = CurLayObj->first - CurOffs;
5180 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5181 // packing/alignment of members is different that normal, in which case
5182 // the encoding will be out-of-sync with the real layout.
5183 // If the runtime switches to just consider the size of types without
5184 // taking into account alignment, we could make padding explicit in the
5185 // encoding (e.g. using arrays of chars). The encoding strings would be
5186 // longer then though.
5187 CurOffs += padding;
5188 }
5189
5190 NamedDecl *dcl = CurLayObj->second;
5191 if (dcl == 0)
5192 break; // reached end of structure.
5193
5194 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5195 // We expand the bases without their virtual bases since those are going
5196 // in the initial structure. Note that this differs from gcc which
5197 // expands virtual bases each time one is encountered in the hierarchy,
5198 // making the encoding type bigger than it really is.
5199 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005200 assert(!base->isEmpty());
5201 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005202 } else {
5203 FieldDecl *field = cast<FieldDecl>(dcl);
5204 if (FD) {
5205 S += '"';
5206 S += field->getNameAsString();
5207 S += '"';
5208 }
5209
5210 if (field->isBitField()) {
5211 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005212 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005213 } else {
5214 QualType qt = field->getType();
5215 getLegacyIntegralTypeEncoding(qt);
5216 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5217 /*OutermostType*/false,
5218 /*EncodingProperty*/false,
5219 /*StructField*/true);
5220 CurOffs += getTypeSize(field->getType());
5221 }
5222 }
5223 }
5224}
5225
Mike Stump11289f42009-09-09 15:08:12 +00005226void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005227 std::string& S) const {
5228 if (QT & Decl::OBJC_TQ_In)
5229 S += 'n';
5230 if (QT & Decl::OBJC_TQ_Inout)
5231 S += 'N';
5232 if (QT & Decl::OBJC_TQ_Out)
5233 S += 'o';
5234 if (QT & Decl::OBJC_TQ_Bycopy)
5235 S += 'O';
5236 if (QT & Decl::OBJC_TQ_Byref)
5237 S += 'R';
5238 if (QT & Decl::OBJC_TQ_Oneway)
5239 S += 'V';
5240}
5241
Douglas Gregor3ea72692011-08-12 05:46:01 +00005242TypedefDecl *ASTContext::getObjCIdDecl() const {
5243 if (!ObjCIdDecl) {
5244 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5245 T = getObjCObjectPointerType(T);
5246 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5247 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5248 getTranslationUnitDecl(),
5249 SourceLocation(), SourceLocation(),
5250 &Idents.get("id"), IdInfo);
5251 }
5252
5253 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005254}
5255
Douglas Gregor52e02802011-08-12 06:17:30 +00005256TypedefDecl *ASTContext::getObjCSelDecl() const {
5257 if (!ObjCSelDecl) {
5258 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5259 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5260 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5261 getTranslationUnitDecl(),
5262 SourceLocation(), SourceLocation(),
5263 &Idents.get("SEL"), SelInfo);
5264 }
5265 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005266}
5267
Douglas Gregor0a586182011-08-12 05:59:41 +00005268TypedefDecl *ASTContext::getObjCClassDecl() const {
5269 if (!ObjCClassDecl) {
5270 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5271 T = getObjCObjectPointerType(T);
5272 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5273 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5274 getTranslationUnitDecl(),
5275 SourceLocation(), SourceLocation(),
5276 &Idents.get("Class"), ClassInfo);
5277 }
5278
5279 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005280}
5281
Douglas Gregord53ae832012-01-17 18:09:05 +00005282ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5283 if (!ObjCProtocolClassDecl) {
5284 ObjCProtocolClassDecl
5285 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5286 SourceLocation(),
5287 &Idents.get("Protocol"),
5288 /*PrevDecl=*/0,
5289 SourceLocation(), true);
5290 }
5291
5292 return ObjCProtocolClassDecl;
5293}
5294
Meador Inge5d3fb222012-06-16 03:34:49 +00005295//===----------------------------------------------------------------------===//
5296// __builtin_va_list Construction Functions
5297//===----------------------------------------------------------------------===//
5298
5299static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5300 // typedef char* __builtin_va_list;
5301 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5302 TypeSourceInfo *TInfo
5303 = Context->getTrivialTypeSourceInfo(CharPtrType);
5304
5305 TypedefDecl *VaListTypeDecl
5306 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5307 Context->getTranslationUnitDecl(),
5308 SourceLocation(), SourceLocation(),
5309 &Context->Idents.get("__builtin_va_list"),
5310 TInfo);
5311 return VaListTypeDecl;
5312}
5313
5314static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5315 // typedef void* __builtin_va_list;
5316 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5317 TypeSourceInfo *TInfo
5318 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5319
5320 TypedefDecl *VaListTypeDecl
5321 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5322 Context->getTranslationUnitDecl(),
5323 SourceLocation(), SourceLocation(),
5324 &Context->Idents.get("__builtin_va_list"),
5325 TInfo);
5326 return VaListTypeDecl;
5327}
5328
5329static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5330 // typedef struct __va_list_tag {
5331 RecordDecl *VaListTagDecl;
5332
5333 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5334 Context->getTranslationUnitDecl(),
5335 &Context->Idents.get("__va_list_tag"));
5336 VaListTagDecl->startDefinition();
5337
5338 const size_t NumFields = 5;
5339 QualType FieldTypes[NumFields];
5340 const char *FieldNames[NumFields];
5341
5342 // unsigned char gpr;
5343 FieldTypes[0] = Context->UnsignedCharTy;
5344 FieldNames[0] = "gpr";
5345
5346 // unsigned char fpr;
5347 FieldTypes[1] = Context->UnsignedCharTy;
5348 FieldNames[1] = "fpr";
5349
5350 // unsigned short reserved;
5351 FieldTypes[2] = Context->UnsignedShortTy;
5352 FieldNames[2] = "reserved";
5353
5354 // void* overflow_arg_area;
5355 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5356 FieldNames[3] = "overflow_arg_area";
5357
5358 // void* reg_save_area;
5359 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5360 FieldNames[4] = "reg_save_area";
5361
5362 // Create fields
5363 for (unsigned i = 0; i < NumFields; ++i) {
5364 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5365 SourceLocation(),
5366 SourceLocation(),
5367 &Context->Idents.get(FieldNames[i]),
5368 FieldTypes[i], /*TInfo=*/0,
5369 /*BitWidth=*/0,
5370 /*Mutable=*/false,
5371 ICIS_NoInit);
5372 Field->setAccess(AS_public);
5373 VaListTagDecl->addDecl(Field);
5374 }
5375 VaListTagDecl->completeDefinition();
5376 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005377 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005378
5379 // } __va_list_tag;
5380 TypedefDecl *VaListTagTypedefDecl
5381 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5382 Context->getTranslationUnitDecl(),
5383 SourceLocation(), SourceLocation(),
5384 &Context->Idents.get("__va_list_tag"),
5385 Context->getTrivialTypeSourceInfo(VaListTagType));
5386 QualType VaListTagTypedefType =
5387 Context->getTypedefType(VaListTagTypedefDecl);
5388
5389 // typedef __va_list_tag __builtin_va_list[1];
5390 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5391 QualType VaListTagArrayType
5392 = Context->getConstantArrayType(VaListTagTypedefType,
5393 Size, ArrayType::Normal, 0);
5394 TypeSourceInfo *TInfo
5395 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5396 TypedefDecl *VaListTypedefDecl
5397 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5398 Context->getTranslationUnitDecl(),
5399 SourceLocation(), SourceLocation(),
5400 &Context->Idents.get("__builtin_va_list"),
5401 TInfo);
5402
5403 return VaListTypedefDecl;
5404}
5405
5406static TypedefDecl *
5407CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5408 // typedef struct __va_list_tag {
5409 RecordDecl *VaListTagDecl;
5410 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5411 Context->getTranslationUnitDecl(),
5412 &Context->Idents.get("__va_list_tag"));
5413 VaListTagDecl->startDefinition();
5414
5415 const size_t NumFields = 4;
5416 QualType FieldTypes[NumFields];
5417 const char *FieldNames[NumFields];
5418
5419 // unsigned gp_offset;
5420 FieldTypes[0] = Context->UnsignedIntTy;
5421 FieldNames[0] = "gp_offset";
5422
5423 // unsigned fp_offset;
5424 FieldTypes[1] = Context->UnsignedIntTy;
5425 FieldNames[1] = "fp_offset";
5426
5427 // void* overflow_arg_area;
5428 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5429 FieldNames[2] = "overflow_arg_area";
5430
5431 // void* reg_save_area;
5432 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5433 FieldNames[3] = "reg_save_area";
5434
5435 // Create fields
5436 for (unsigned i = 0; i < NumFields; ++i) {
5437 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5438 VaListTagDecl,
5439 SourceLocation(),
5440 SourceLocation(),
5441 &Context->Idents.get(FieldNames[i]),
5442 FieldTypes[i], /*TInfo=*/0,
5443 /*BitWidth=*/0,
5444 /*Mutable=*/false,
5445 ICIS_NoInit);
5446 Field->setAccess(AS_public);
5447 VaListTagDecl->addDecl(Field);
5448 }
5449 VaListTagDecl->completeDefinition();
5450 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005451 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005452
5453 // } __va_list_tag;
5454 TypedefDecl *VaListTagTypedefDecl
5455 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5456 Context->getTranslationUnitDecl(),
5457 SourceLocation(), SourceLocation(),
5458 &Context->Idents.get("__va_list_tag"),
5459 Context->getTrivialTypeSourceInfo(VaListTagType));
5460 QualType VaListTagTypedefType =
5461 Context->getTypedefType(VaListTagTypedefDecl);
5462
5463 // typedef __va_list_tag __builtin_va_list[1];
5464 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5465 QualType VaListTagArrayType
5466 = Context->getConstantArrayType(VaListTagTypedefType,
5467 Size, ArrayType::Normal,0);
5468 TypeSourceInfo *TInfo
5469 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5470 TypedefDecl *VaListTypedefDecl
5471 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5472 Context->getTranslationUnitDecl(),
5473 SourceLocation(), SourceLocation(),
5474 &Context->Idents.get("__builtin_va_list"),
5475 TInfo);
5476
5477 return VaListTypedefDecl;
5478}
5479
5480static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5481 // typedef int __builtin_va_list[4];
5482 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5483 QualType IntArrayType
5484 = Context->getConstantArrayType(Context->IntTy,
5485 Size, ArrayType::Normal, 0);
5486 TypedefDecl *VaListTypedefDecl
5487 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5488 Context->getTranslationUnitDecl(),
5489 SourceLocation(), SourceLocation(),
5490 &Context->Idents.get("__builtin_va_list"),
5491 Context->getTrivialTypeSourceInfo(IntArrayType));
5492
5493 return VaListTypedefDecl;
5494}
5495
5496static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5497 TargetInfo::BuiltinVaListKind Kind) {
5498 switch (Kind) {
5499 case TargetInfo::CharPtrBuiltinVaList:
5500 return CreateCharPtrBuiltinVaListDecl(Context);
5501 case TargetInfo::VoidPtrBuiltinVaList:
5502 return CreateVoidPtrBuiltinVaListDecl(Context);
5503 case TargetInfo::PowerABIBuiltinVaList:
5504 return CreatePowerABIBuiltinVaListDecl(Context);
5505 case TargetInfo::X86_64ABIBuiltinVaList:
5506 return CreateX86_64ABIBuiltinVaListDecl(Context);
5507 case TargetInfo::PNaClABIBuiltinVaList:
5508 return CreatePNaClABIBuiltinVaListDecl(Context);
5509 }
5510
5511 llvm_unreachable("Unhandled __builtin_va_list type kind");
5512}
5513
5514TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5515 if (!BuiltinVaListDecl)
5516 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5517
5518 return BuiltinVaListDecl;
5519}
5520
Meador Ingecfb60902012-07-01 15:57:25 +00005521QualType ASTContext::getVaListTagType() const {
5522 // Force the creation of VaListTagTy by building the __builtin_va_list
5523 // declaration.
5524 if (VaListTagTy.isNull())
5525 (void) getBuiltinVaListDecl();
5526
5527 return VaListTagTy;
5528}
5529
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005530void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005531 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005532 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005533
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005534 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005535}
5536
John McCalld28ae272009-12-02 08:04:21 +00005537/// \brief Retrieve the template name that corresponds to a non-empty
5538/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005539TemplateName
5540ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5541 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005542 unsigned size = End - Begin;
5543 assert(size > 1 && "set is not overloaded!");
5544
5545 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5546 size * sizeof(FunctionTemplateDecl*));
5547 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5548
5549 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005550 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005551 NamedDecl *D = *I;
5552 assert(isa<FunctionTemplateDecl>(D) ||
5553 (isa<UsingShadowDecl>(D) &&
5554 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5555 *Storage++ = D;
5556 }
5557
5558 return TemplateName(OT);
5559}
5560
Douglas Gregordc572a32009-03-30 22:58:21 +00005561/// \brief Retrieve the template name that represents a qualified
5562/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005563TemplateName
5564ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5565 bool TemplateKeyword,
5566 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005567 assert(NNS && "Missing nested-name-specifier in qualified template name");
5568
Douglas Gregorc42075a2010-02-04 18:10:26 +00005569 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005570 llvm::FoldingSetNodeID ID;
5571 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5572
5573 void *InsertPos = 0;
5574 QualifiedTemplateName *QTN =
5575 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5576 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005577 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5578 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005579 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5580 }
5581
5582 return TemplateName(QTN);
5583}
5584
5585/// \brief Retrieve the template name that represents a dependent
5586/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005587TemplateName
5588ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5589 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005590 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005591 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005592
5593 llvm::FoldingSetNodeID ID;
5594 DependentTemplateName::Profile(ID, NNS, Name);
5595
5596 void *InsertPos = 0;
5597 DependentTemplateName *QTN =
5598 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5599
5600 if (QTN)
5601 return TemplateName(QTN);
5602
5603 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5604 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005605 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5606 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00005607 } else {
5608 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00005609 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5610 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005611 DependentTemplateName *CheckQTN =
5612 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5613 assert(!CheckQTN && "Dependent type name canonicalization broken");
5614 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005615 }
5616
5617 DependentTemplateNames.InsertNode(QTN, InsertPos);
5618 return TemplateName(QTN);
5619}
5620
Douglas Gregor71395fa2009-11-04 00:56:37 +00005621/// \brief Retrieve the template name that represents a dependent
5622/// template name such as \c MetaFun::template operator+.
5623TemplateName
5624ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005625 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005626 assert((!NNS || NNS->isDependent()) &&
5627 "Nested name specifier must be dependent");
5628
5629 llvm::FoldingSetNodeID ID;
5630 DependentTemplateName::Profile(ID, NNS, Operator);
5631
5632 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005633 DependentTemplateName *QTN
5634 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005635
5636 if (QTN)
5637 return TemplateName(QTN);
5638
5639 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5640 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005641 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5642 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005643 } else {
5644 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00005645 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5646 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005647
5648 DependentTemplateName *CheckQTN
5649 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5650 assert(!CheckQTN && "Dependent template name canonicalization broken");
5651 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005652 }
5653
5654 DependentTemplateNames.InsertNode(QTN, InsertPos);
5655 return TemplateName(QTN);
5656}
5657
Douglas Gregor5590be02011-01-15 06:45:20 +00005658TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005659ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5660 TemplateName replacement) const {
5661 llvm::FoldingSetNodeID ID;
5662 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5663
5664 void *insertPos = 0;
5665 SubstTemplateTemplateParmStorage *subst
5666 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5667
5668 if (!subst) {
5669 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5670 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5671 }
5672
5673 return TemplateName(subst);
5674}
5675
5676TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005677ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5678 const TemplateArgument &ArgPack) const {
5679 ASTContext &Self = const_cast<ASTContext &>(*this);
5680 llvm::FoldingSetNodeID ID;
5681 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5682
5683 void *InsertPos = 0;
5684 SubstTemplateTemplateParmPackStorage *Subst
5685 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5686
5687 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005688 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005689 ArgPack.pack_size(),
5690 ArgPack.pack_begin());
5691 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5692 }
5693
5694 return TemplateName(Subst);
5695}
5696
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005697/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005698/// TargetInfo, produce the corresponding type. The unsigned @p Type
5699/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005700CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005701 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005702 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005703 case TargetInfo::SignedShort: return ShortTy;
5704 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5705 case TargetInfo::SignedInt: return IntTy;
5706 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5707 case TargetInfo::SignedLong: return LongTy;
5708 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5709 case TargetInfo::SignedLongLong: return LongLongTy;
5710 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5711 }
5712
David Blaikie83d382b2011-09-23 05:06:16 +00005713 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005714}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005715
5716//===----------------------------------------------------------------------===//
5717// Type Predicates.
5718//===----------------------------------------------------------------------===//
5719
Fariborz Jahanian96207692009-02-18 21:49:28 +00005720/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5721/// garbage collection attribute.
5722///
John McCall553d45a2011-01-12 00:34:59 +00005723Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005724 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005725 return Qualifiers::GCNone;
5726
David Blaikiebbafb8a2012-03-11 07:00:24 +00005727 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005728 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5729
5730 // Default behaviour under objective-C's gc is for ObjC pointers
5731 // (or pointers to them) be treated as though they were declared
5732 // as __strong.
5733 if (GCAttrs == Qualifiers::GCNone) {
5734 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5735 return Qualifiers::Strong;
5736 else if (Ty->isPointerType())
5737 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5738 } else {
5739 // It's not valid to set GC attributes on anything that isn't a
5740 // pointer.
5741#ifndef NDEBUG
5742 QualType CT = Ty->getCanonicalTypeInternal();
5743 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5744 CT = AT->getElementType();
5745 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5746#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005747 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005748 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005749}
5750
Chris Lattner49af6a42008-04-07 06:51:04 +00005751//===----------------------------------------------------------------------===//
5752// Type Compatibility Testing
5753//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005754
Mike Stump11289f42009-09-09 15:08:12 +00005755/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005756/// compatible.
5757static bool areCompatVectorTypes(const VectorType *LHS,
5758 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005759 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005760 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005761 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005762}
5763
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005764bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5765 QualType SecondVec) {
5766 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5767 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5768
5769 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5770 return true;
5771
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005772 // Treat Neon vector types and most AltiVec vector types as if they are the
5773 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005774 const VectorType *First = FirstVec->getAs<VectorType>();
5775 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005776 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005777 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005778 First->getVectorKind() != VectorType::AltiVecPixel &&
5779 First->getVectorKind() != VectorType::AltiVecBool &&
5780 Second->getVectorKind() != VectorType::AltiVecPixel &&
5781 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005782 return true;
5783
5784 return false;
5785}
5786
Steve Naroff8e6aee52009-07-23 01:01:38 +00005787//===----------------------------------------------------------------------===//
5788// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5789//===----------------------------------------------------------------------===//
5790
5791/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5792/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005793bool
5794ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5795 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005796 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005797 return true;
5798 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5799 E = rProto->protocol_end(); PI != E; ++PI)
5800 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5801 return true;
5802 return false;
5803}
5804
Steve Naroff8e6aee52009-07-23 01:01:38 +00005805/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5806/// return true if lhs's protocols conform to rhs's protocol; false
5807/// otherwise.
5808bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5809 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5810 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5811 return false;
5812}
5813
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005814/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5815/// Class<p1, ...>.
5816bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5817 QualType rhs) {
5818 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5819 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5820 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5821
5822 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5823 E = lhsQID->qual_end(); I != E; ++I) {
5824 bool match = false;
5825 ObjCProtocolDecl *lhsProto = *I;
5826 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5827 E = rhsOPT->qual_end(); J != E; ++J) {
5828 ObjCProtocolDecl *rhsProto = *J;
5829 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5830 match = true;
5831 break;
5832 }
5833 }
5834 if (!match)
5835 return false;
5836 }
5837 return true;
5838}
5839
Steve Naroff8e6aee52009-07-23 01:01:38 +00005840/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5841/// ObjCQualifiedIDType.
5842bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5843 bool compare) {
5844 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005845 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005846 lhs->isObjCIdType() || lhs->isObjCClassType())
5847 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005848 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005849 rhs->isObjCIdType() || rhs->isObjCClassType())
5850 return true;
5851
5852 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005853 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005854
Steve Naroff8e6aee52009-07-23 01:01:38 +00005855 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005856
Steve Naroff8e6aee52009-07-23 01:01:38 +00005857 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005858 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005859 // make sure we check the class hierarchy.
5860 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5861 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5862 E = lhsQID->qual_end(); I != E; ++I) {
5863 // when comparing an id<P> on lhs with a static type on rhs,
5864 // see if static class implements all of id's protocols, directly or
5865 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005866 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005867 return false;
5868 }
5869 }
5870 // If there are no qualifiers and no interface, we have an 'id'.
5871 return true;
5872 }
Mike Stump11289f42009-09-09 15:08:12 +00005873 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005874 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5875 E = lhsQID->qual_end(); I != E; ++I) {
5876 ObjCProtocolDecl *lhsProto = *I;
5877 bool match = false;
5878
5879 // when comparing an id<P> on lhs with a static type on rhs,
5880 // see if static class implements all of id's protocols, directly or
5881 // through its super class and categories.
5882 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5883 E = rhsOPT->qual_end(); J != E; ++J) {
5884 ObjCProtocolDecl *rhsProto = *J;
5885 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5886 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5887 match = true;
5888 break;
5889 }
5890 }
Mike Stump11289f42009-09-09 15:08:12 +00005891 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005892 // make sure we check the class hierarchy.
5893 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5894 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5895 E = lhsQID->qual_end(); I != E; ++I) {
5896 // when comparing an id<P> on lhs with a static type on rhs,
5897 // see if static class implements all of id's protocols, directly or
5898 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005899 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005900 match = true;
5901 break;
5902 }
5903 }
5904 }
5905 if (!match)
5906 return false;
5907 }
Mike Stump11289f42009-09-09 15:08:12 +00005908
Steve Naroff8e6aee52009-07-23 01:01:38 +00005909 return true;
5910 }
Mike Stump11289f42009-09-09 15:08:12 +00005911
Steve Naroff8e6aee52009-07-23 01:01:38 +00005912 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5913 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5914
Mike Stump11289f42009-09-09 15:08:12 +00005915 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005916 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005917 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005918 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5919 E = lhsOPT->qual_end(); I != E; ++I) {
5920 ObjCProtocolDecl *lhsProto = *I;
5921 bool match = false;
5922
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005923 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005924 // see if static class implements all of id's protocols, directly or
5925 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005926 // First, lhs protocols in the qualifier list must be found, direct
5927 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005928 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5929 E = rhsQID->qual_end(); J != E; ++J) {
5930 ObjCProtocolDecl *rhsProto = *J;
5931 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5932 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5933 match = true;
5934 break;
5935 }
5936 }
5937 if (!match)
5938 return false;
5939 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005940
5941 // Static class's protocols, or its super class or category protocols
5942 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5943 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5944 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5945 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5946 // This is rather dubious but matches gcc's behavior. If lhs has
5947 // no type qualifier and its class has no static protocol(s)
5948 // assume that it is mismatch.
5949 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5950 return false;
5951 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5952 LHSInheritedProtocols.begin(),
5953 E = LHSInheritedProtocols.end(); I != E; ++I) {
5954 bool match = false;
5955 ObjCProtocolDecl *lhsProto = (*I);
5956 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5957 E = rhsQID->qual_end(); J != E; ++J) {
5958 ObjCProtocolDecl *rhsProto = *J;
5959 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5960 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5961 match = true;
5962 break;
5963 }
5964 }
5965 if (!match)
5966 return false;
5967 }
5968 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005969 return true;
5970 }
5971 return false;
5972}
5973
Eli Friedman47f77112008-08-22 00:56:42 +00005974/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005975/// compatible for assignment from RHS to LHS. This handles validation of any
5976/// protocol qualifiers on the LHS or RHS.
5977///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005978bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5979 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005980 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5981 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5982
Steve Naroff1329fa02009-07-15 18:40:39 +00005983 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005984 if (LHS->isObjCUnqualifiedIdOrClass() ||
5985 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005986 return true;
5987
John McCall8b07ec22010-05-15 11:32:37 +00005988 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005989 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5990 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005991 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005992
5993 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5994 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5995 QualType(RHSOPT,0));
5996
John McCall8b07ec22010-05-15 11:32:37 +00005997 // If we have 2 user-defined types, fall into that path.
5998 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005999 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006000
Steve Naroff8e6aee52009-07-23 01:01:38 +00006001 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006002}
6003
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006004/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006005/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006006/// arguments in block literals. When passed as arguments, passing 'A*' where
6007/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6008/// not OK. For the return type, the opposite is not OK.
6009bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6010 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006011 const ObjCObjectPointerType *RHSOPT,
6012 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006013 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006014 return true;
6015
6016 if (LHSOPT->isObjCBuiltinType()) {
6017 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6018 }
6019
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006020 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006021 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6022 QualType(RHSOPT,0),
6023 false);
6024
6025 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6026 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6027 if (LHS && RHS) { // We have 2 user-defined types.
6028 if (LHS != RHS) {
6029 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006030 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006031 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006032 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006033 }
6034 else
6035 return true;
6036 }
6037 return false;
6038}
6039
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006040/// getIntersectionOfProtocols - This routine finds the intersection of set
6041/// of protocols inherited from two distinct objective-c pointer objects.
6042/// It is used to build composite qualifier list of the composite type of
6043/// the conditional expression involving two objective-c pointer objects.
6044static
6045void getIntersectionOfProtocols(ASTContext &Context,
6046 const ObjCObjectPointerType *LHSOPT,
6047 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006048 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006049
John McCall8b07ec22010-05-15 11:32:37 +00006050 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6051 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6052 assert(LHS->getInterface() && "LHS must have an interface base");
6053 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006054
6055 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6056 unsigned LHSNumProtocols = LHS->getNumProtocols();
6057 if (LHSNumProtocols > 0)
6058 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6059 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006060 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006061 Context.CollectInheritedProtocols(LHS->getInterface(),
6062 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006063 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6064 LHSInheritedProtocols.end());
6065 }
6066
6067 unsigned RHSNumProtocols = RHS->getNumProtocols();
6068 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006069 ObjCProtocolDecl **RHSProtocols =
6070 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006071 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6072 if (InheritedProtocolSet.count(RHSProtocols[i]))
6073 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006074 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006075 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006076 Context.CollectInheritedProtocols(RHS->getInterface(),
6077 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006078 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6079 RHSInheritedProtocols.begin(),
6080 E = RHSInheritedProtocols.end(); I != E; ++I)
6081 if (InheritedProtocolSet.count((*I)))
6082 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006083 }
6084}
6085
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006086/// areCommonBaseCompatible - Returns common base class of the two classes if
6087/// one found. Note that this is O'2 algorithm. But it will be called as the
6088/// last type comparison in a ?-exp of ObjC pointer types before a
6089/// warning is issued. So, its invokation is extremely rare.
6090QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006091 const ObjCObjectPointerType *Lptr,
6092 const ObjCObjectPointerType *Rptr) {
6093 const ObjCObjectType *LHS = Lptr->getObjectType();
6094 const ObjCObjectType *RHS = Rptr->getObjectType();
6095 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6096 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006097 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006098 return QualType();
6099
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006100 do {
John McCall8b07ec22010-05-15 11:32:37 +00006101 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006102 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006103 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006104 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6105
6106 QualType Result = QualType(LHS, 0);
6107 if (!Protocols.empty())
6108 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6109 Result = getObjCObjectPointerType(Result);
6110 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006111 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006112 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006113
6114 return QualType();
6115}
6116
John McCall8b07ec22010-05-15 11:32:37 +00006117bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6118 const ObjCObjectType *RHS) {
6119 assert(LHS->getInterface() && "LHS is not an interface type");
6120 assert(RHS->getInterface() && "RHS is not an interface type");
6121
Chris Lattner49af6a42008-04-07 06:51:04 +00006122 // Verify that the base decls are compatible: the RHS must be a subclass of
6123 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006124 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006125 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006126
Chris Lattner49af6a42008-04-07 06:51:04 +00006127 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6128 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006129 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006130 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006131
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006132 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6133 // more detailed analysis is required.
6134 if (RHS->getNumProtocols() == 0) {
6135 // OK, if LHS is a superclass of RHS *and*
6136 // this superclass is assignment compatible with LHS.
6137 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006138 bool IsSuperClass =
6139 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6140 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006141 // OK if conversion of LHS to SuperClass results in narrowing of types
6142 // ; i.e., SuperClass may implement at least one of the protocols
6143 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6144 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6145 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006146 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006147 // If super class has no protocols, it is not a match.
6148 if (SuperClassInheritedProtocols.empty())
6149 return false;
6150
6151 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6152 LHSPE = LHS->qual_end();
6153 LHSPI != LHSPE; LHSPI++) {
6154 bool SuperImplementsProtocol = false;
6155 ObjCProtocolDecl *LHSProto = (*LHSPI);
6156
6157 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6158 SuperClassInheritedProtocols.begin(),
6159 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6160 ObjCProtocolDecl *SuperClassProto = (*I);
6161 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6162 SuperImplementsProtocol = true;
6163 break;
6164 }
6165 }
6166 if (!SuperImplementsProtocol)
6167 return false;
6168 }
6169 return true;
6170 }
6171 return false;
6172 }
Mike Stump11289f42009-09-09 15:08:12 +00006173
John McCall8b07ec22010-05-15 11:32:37 +00006174 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6175 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006176 LHSPI != LHSPE; LHSPI++) {
6177 bool RHSImplementsProtocol = false;
6178
6179 // If the RHS doesn't implement the protocol on the left, the types
6180 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006181 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6182 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006183 RHSPI != RHSPE; RHSPI++) {
6184 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006185 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006186 break;
6187 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006188 }
6189 // FIXME: For better diagnostics, consider passing back the protocol name.
6190 if (!RHSImplementsProtocol)
6191 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006192 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006193 // The RHS implements all protocols listed on the LHS.
6194 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006195}
6196
Steve Naroffb7605152009-02-12 17:52:19 +00006197bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6198 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006199 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6200 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006201
Steve Naroff7cae42b2009-07-10 23:34:53 +00006202 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006203 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006204
6205 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6206 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006207}
6208
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006209bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6210 return canAssignObjCInterfaces(
6211 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6212 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6213}
6214
Mike Stump11289f42009-09-09 15:08:12 +00006215/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006216/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006217/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006218/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006219bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6220 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006221 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006222 return hasSameType(LHS, RHS);
6223
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006224 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006225}
6226
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006227bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006228 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006229}
6230
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006231bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6232 return !mergeTypes(LHS, RHS, true).isNull();
6233}
6234
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006235/// mergeTransparentUnionType - if T is a transparent union type and a member
6236/// of T is compatible with SubType, return the merged type, else return
6237/// QualType()
6238QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6239 bool OfBlockPointer,
6240 bool Unqualified) {
6241 if (const RecordType *UT = T->getAsUnionType()) {
6242 RecordDecl *UD = UT->getDecl();
6243 if (UD->hasAttr<TransparentUnionAttr>()) {
6244 for (RecordDecl::field_iterator it = UD->field_begin(),
6245 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006246 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006247 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6248 if (!MT.isNull())
6249 return MT;
6250 }
6251 }
6252 }
6253
6254 return QualType();
6255}
6256
6257/// mergeFunctionArgumentTypes - merge two types which appear as function
6258/// argument types
6259QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6260 bool OfBlockPointer,
6261 bool Unqualified) {
6262 // GNU extension: two types are compatible if they appear as a function
6263 // argument, one of the types is a transparent union type and the other
6264 // type is compatible with a union member
6265 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6266 Unqualified);
6267 if (!lmerge.isNull())
6268 return lmerge;
6269
6270 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6271 Unqualified);
6272 if (!rmerge.isNull())
6273 return rmerge;
6274
6275 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6276}
6277
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006278QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006279 bool OfBlockPointer,
6280 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006281 const FunctionType *lbase = lhs->getAs<FunctionType>();
6282 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006283 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6284 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006285 bool allLTypes = true;
6286 bool allRTypes = true;
6287
6288 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006289 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006290 if (OfBlockPointer) {
6291 QualType RHS = rbase->getResultType();
6292 QualType LHS = lbase->getResultType();
6293 bool UnqualifiedResult = Unqualified;
6294 if (!UnqualifiedResult)
6295 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006296 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006297 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006298 else
John McCall8c6b56f2010-12-15 01:06:38 +00006299 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6300 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006301 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006302
6303 if (Unqualified)
6304 retType = retType.getUnqualifiedType();
6305
6306 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6307 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6308 if (Unqualified) {
6309 LRetType = LRetType.getUnqualifiedType();
6310 RRetType = RRetType.getUnqualifiedType();
6311 }
6312
6313 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006314 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006315 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006316 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006317
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006318 // FIXME: double check this
6319 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6320 // rbase->getRegParmAttr() != 0 &&
6321 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006322 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6323 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006324
Douglas Gregor8c940862010-01-18 17:14:39 +00006325 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006326 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006327 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006328
John McCall8c6b56f2010-12-15 01:06:38 +00006329 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006330 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6331 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006332 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6333 return QualType();
6334
John McCall31168b02011-06-15 23:02:42 +00006335 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6336 return QualType();
6337
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006338 // functypes which return are preferred over those that do not.
6339 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6340 allLTypes = false;
6341 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6342 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006343 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6344 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006345
John McCall31168b02011-06-15 23:02:42 +00006346 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006347
Eli Friedman47f77112008-08-22 00:56:42 +00006348 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006349 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6350 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006351 unsigned lproto_nargs = lproto->getNumArgs();
6352 unsigned rproto_nargs = rproto->getNumArgs();
6353
6354 // Compatible functions must have the same number of arguments
6355 if (lproto_nargs != rproto_nargs)
6356 return QualType();
6357
6358 // Variadic and non-variadic functions aren't compatible
6359 if (lproto->isVariadic() != rproto->isVariadic())
6360 return QualType();
6361
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006362 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6363 return QualType();
6364
Fariborz Jahanian97676972011-09-28 21:52:05 +00006365 if (LangOpts.ObjCAutoRefCount &&
6366 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6367 return QualType();
6368
Eli Friedman47f77112008-08-22 00:56:42 +00006369 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006370 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006371 for (unsigned i = 0; i < lproto_nargs; i++) {
6372 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6373 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006374 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6375 OfBlockPointer,
6376 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006377 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006378
6379 if (Unqualified)
6380 argtype = argtype.getUnqualifiedType();
6381
Eli Friedman47f77112008-08-22 00:56:42 +00006382 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006383 if (Unqualified) {
6384 largtype = largtype.getUnqualifiedType();
6385 rargtype = rargtype.getUnqualifiedType();
6386 }
6387
Chris Lattner465fa322008-10-05 17:34:18 +00006388 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6389 allLTypes = false;
6390 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6391 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006392 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006393
Eli Friedman47f77112008-08-22 00:56:42 +00006394 if (allLTypes) return lhs;
6395 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006396
6397 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6398 EPI.ExtInfo = einfo;
6399 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006400 }
6401
6402 if (lproto) allRTypes = false;
6403 if (rproto) allLTypes = false;
6404
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006405 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006406 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006407 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006408 if (proto->isVariadic()) return QualType();
6409 // Check that the types are compatible with the types that
6410 // would result from default argument promotions (C99 6.7.5.3p15).
6411 // The only types actually affected are promotable integer
6412 // types and floats, which would be passed as a different
6413 // type depending on whether the prototype is visible.
6414 unsigned proto_nargs = proto->getNumArgs();
6415 for (unsigned i = 0; i < proto_nargs; ++i) {
6416 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006417
6418 // Look at the promotion type of enum types, since that is the type used
6419 // to pass enum values.
6420 if (const EnumType *Enum = argTy->getAs<EnumType>())
6421 argTy = Enum->getDecl()->getPromotionType();
6422
Eli Friedman47f77112008-08-22 00:56:42 +00006423 if (argTy->isPromotableIntegerType() ||
6424 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6425 return QualType();
6426 }
6427
6428 if (allLTypes) return lhs;
6429 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006430
6431 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6432 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006433 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006434 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006435 }
6436
6437 if (allLTypes) return lhs;
6438 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006439 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006440}
6441
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006442QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006443 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006444 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006445 // C++ [expr]: If an expression initially has the type "reference to T", the
6446 // type is adjusted to "T" prior to any further analysis, the expression
6447 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006448 // expression is an lvalue unless the reference is an rvalue reference and
6449 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006450 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6451 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006452
6453 if (Unqualified) {
6454 LHS = LHS.getUnqualifiedType();
6455 RHS = RHS.getUnqualifiedType();
6456 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006457
Eli Friedman47f77112008-08-22 00:56:42 +00006458 QualType LHSCan = getCanonicalType(LHS),
6459 RHSCan = getCanonicalType(RHS);
6460
6461 // If two types are identical, they are compatible.
6462 if (LHSCan == RHSCan)
6463 return LHS;
6464
John McCall8ccfcb52009-09-24 19:53:00 +00006465 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006466 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6467 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006468 if (LQuals != RQuals) {
6469 // If any of these qualifiers are different, we have a type
6470 // mismatch.
6471 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006472 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6473 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006474 return QualType();
6475
6476 // Exactly one GC qualifier difference is allowed: __strong is
6477 // okay if the other type has no GC qualifier but is an Objective
6478 // C object pointer (i.e. implicitly strong by default). We fix
6479 // this by pretending that the unqualified type was actually
6480 // qualified __strong.
6481 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6482 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6483 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6484
6485 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6486 return QualType();
6487
6488 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6489 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6490 }
6491 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6492 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6493 }
Eli Friedman47f77112008-08-22 00:56:42 +00006494 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006495 }
6496
6497 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006498
Eli Friedmandcca6332009-06-01 01:22:52 +00006499 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6500 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006501
Chris Lattnerfd652912008-01-14 05:45:46 +00006502 // We want to consider the two function types to be the same for these
6503 // comparisons, just force one to the other.
6504 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6505 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006506
6507 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006508 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6509 LHSClass = Type::ConstantArray;
6510 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6511 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006512
John McCall8b07ec22010-05-15 11:32:37 +00006513 // ObjCInterfaces are just specialized ObjCObjects.
6514 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6515 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6516
Nate Begemance4d7fc2008-04-18 23:10:10 +00006517 // Canonicalize ExtVector -> Vector.
6518 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6519 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006520
Chris Lattner95554662008-04-07 05:43:21 +00006521 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006522 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006523 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006524 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006525 // Compatibility is based on the underlying type, not the promotion
6526 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006527 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006528 QualType TINT = ETy->getDecl()->getIntegerType();
6529 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006530 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006531 }
John McCall9dd450b2009-09-21 23:43:11 +00006532 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006533 QualType TINT = ETy->getDecl()->getIntegerType();
6534 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006535 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006536 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006537 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006538 if (OfBlockPointer && !BlockReturnType) {
6539 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6540 return LHS;
6541 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6542 return RHS;
6543 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006544
Eli Friedman47f77112008-08-22 00:56:42 +00006545 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006546 }
Eli Friedman47f77112008-08-22 00:56:42 +00006547
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006548 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006549 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006550#define TYPE(Class, Base)
6551#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006552#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006553#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6554#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6555#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006556 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006557
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006558 case Type::LValueReference:
6559 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006560 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006561 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006562
John McCall8b07ec22010-05-15 11:32:37 +00006563 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006564 case Type::IncompleteArray:
6565 case Type::VariableArray:
6566 case Type::FunctionProto:
6567 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006568 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006569
Chris Lattnerfd652912008-01-14 05:45:46 +00006570 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006571 {
6572 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006573 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6574 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006575 if (Unqualified) {
6576 LHSPointee = LHSPointee.getUnqualifiedType();
6577 RHSPointee = RHSPointee.getUnqualifiedType();
6578 }
6579 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6580 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006581 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006582 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006583 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006584 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006585 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006586 return getPointerType(ResultType);
6587 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006588 case Type::BlockPointer:
6589 {
6590 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006591 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6592 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006593 if (Unqualified) {
6594 LHSPointee = LHSPointee.getUnqualifiedType();
6595 RHSPointee = RHSPointee.getUnqualifiedType();
6596 }
6597 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6598 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006599 if (ResultType.isNull()) return QualType();
6600 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6601 return LHS;
6602 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6603 return RHS;
6604 return getBlockPointerType(ResultType);
6605 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006606 case Type::Atomic:
6607 {
6608 // Merge two pointer types, while trying to preserve typedef info
6609 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6610 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6611 if (Unqualified) {
6612 LHSValue = LHSValue.getUnqualifiedType();
6613 RHSValue = RHSValue.getUnqualifiedType();
6614 }
6615 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6616 Unqualified);
6617 if (ResultType.isNull()) return QualType();
6618 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6619 return LHS;
6620 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6621 return RHS;
6622 return getAtomicType(ResultType);
6623 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006624 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006625 {
6626 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6627 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6628 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6629 return QualType();
6630
6631 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6632 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006633 if (Unqualified) {
6634 LHSElem = LHSElem.getUnqualifiedType();
6635 RHSElem = RHSElem.getUnqualifiedType();
6636 }
6637
6638 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006639 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006640 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6641 return LHS;
6642 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6643 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006644 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6645 ArrayType::ArraySizeModifier(), 0);
6646 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6647 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006648 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6649 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006650 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6651 return LHS;
6652 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6653 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006654 if (LVAT) {
6655 // FIXME: This isn't correct! But tricky to implement because
6656 // the array's size has to be the size of LHS, but the type
6657 // has to be different.
6658 return LHS;
6659 }
6660 if (RVAT) {
6661 // FIXME: This isn't correct! But tricky to implement because
6662 // the array's size has to be the size of RHS, but the type
6663 // has to be different.
6664 return RHS;
6665 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006666 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6667 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006668 return getIncompleteArrayType(ResultType,
6669 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006670 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006671 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006672 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006673 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006674 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006675 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006676 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006677 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006678 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006679 case Type::Complex:
6680 // Distinct complex types are incompatible.
6681 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006682 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006683 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006684 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6685 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006686 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006687 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006688 case Type::ObjCObject: {
6689 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006690 // FIXME: This should be type compatibility, e.g. whether
6691 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006692 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6693 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6694 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006695 return LHS;
6696
Eli Friedman47f77112008-08-22 00:56:42 +00006697 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006698 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006699 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006700 if (OfBlockPointer) {
6701 if (canAssignObjCInterfacesInBlockPointer(
6702 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006703 RHS->getAs<ObjCObjectPointerType>(),
6704 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006705 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006706 return QualType();
6707 }
John McCall9dd450b2009-09-21 23:43:11 +00006708 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6709 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006710 return LHS;
6711
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006712 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006713 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006714 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006715
David Blaikie8a40f702012-01-17 06:56:22 +00006716 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006717}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006718
Fariborz Jahanian97676972011-09-28 21:52:05 +00006719bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6720 const FunctionProtoType *FromFunctionType,
6721 const FunctionProtoType *ToFunctionType) {
6722 if (FromFunctionType->hasAnyConsumedArgs() !=
6723 ToFunctionType->hasAnyConsumedArgs())
6724 return false;
6725 FunctionProtoType::ExtProtoInfo FromEPI =
6726 FromFunctionType->getExtProtoInfo();
6727 FunctionProtoType::ExtProtoInfo ToEPI =
6728 ToFunctionType->getExtProtoInfo();
6729 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6730 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6731 ArgIdx != NumArgs; ++ArgIdx) {
6732 if (FromEPI.ConsumedArguments[ArgIdx] !=
6733 ToEPI.ConsumedArguments[ArgIdx])
6734 return false;
6735 }
6736 return true;
6737}
6738
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006739/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6740/// 'RHS' attributes and returns the merged version; including for function
6741/// return types.
6742QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6743 QualType LHSCan = getCanonicalType(LHS),
6744 RHSCan = getCanonicalType(RHS);
6745 // If two types are identical, they are compatible.
6746 if (LHSCan == RHSCan)
6747 return LHS;
6748 if (RHSCan->isFunctionType()) {
6749 if (!LHSCan->isFunctionType())
6750 return QualType();
6751 QualType OldReturnType =
6752 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6753 QualType NewReturnType =
6754 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6755 QualType ResReturnType =
6756 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6757 if (ResReturnType.isNull())
6758 return QualType();
6759 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6760 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6761 // In either case, use OldReturnType to build the new function type.
6762 const FunctionType *F = LHS->getAs<FunctionType>();
6763 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006764 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6765 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006766 QualType ResultType
6767 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006768 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006769 return ResultType;
6770 }
6771 }
6772 return QualType();
6773 }
6774
6775 // If the qualifiers are different, the types can still be merged.
6776 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6777 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6778 if (LQuals != RQuals) {
6779 // If any of these qualifiers are different, we have a type mismatch.
6780 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6781 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6782 return QualType();
6783
6784 // Exactly one GC qualifier difference is allowed: __strong is
6785 // okay if the other type has no GC qualifier but is an Objective
6786 // C object pointer (i.e. implicitly strong by default). We fix
6787 // this by pretending that the unqualified type was actually
6788 // qualified __strong.
6789 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6790 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6791 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6792
6793 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6794 return QualType();
6795
6796 if (GC_L == Qualifiers::Strong)
6797 return LHS;
6798 if (GC_R == Qualifiers::Strong)
6799 return RHS;
6800 return QualType();
6801 }
6802
6803 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6804 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6805 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6806 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6807 if (ResQT == LHSBaseQT)
6808 return LHS;
6809 if (ResQT == RHSBaseQT)
6810 return RHS;
6811 }
6812 return QualType();
6813}
6814
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006815//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006816// Integer Predicates
6817//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006818
Jay Foad39c79802011-01-12 09:06:06 +00006819unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006820 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006821 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006822 if (T->isBooleanType())
6823 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006824 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006825 return (unsigned)getTypeSize(T);
6826}
6827
6828QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006829 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006830
6831 // Turn <4 x signed int> -> <4 x unsigned int>
6832 if (const VectorType *VTy = T->getAs<VectorType>())
6833 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006834 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006835
6836 // For enums, we return the unsigned version of the base type.
6837 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006838 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006839
6840 const BuiltinType *BTy = T->getAs<BuiltinType>();
6841 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006842 switch (BTy->getKind()) {
6843 case BuiltinType::Char_S:
6844 case BuiltinType::SChar:
6845 return UnsignedCharTy;
6846 case BuiltinType::Short:
6847 return UnsignedShortTy;
6848 case BuiltinType::Int:
6849 return UnsignedIntTy;
6850 case BuiltinType::Long:
6851 return UnsignedLongTy;
6852 case BuiltinType::LongLong:
6853 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006854 case BuiltinType::Int128:
6855 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006856 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006857 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006858 }
6859}
6860
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006861ASTMutationListener::~ASTMutationListener() { }
6862
Chris Lattnerecd79c62009-06-14 00:45:47 +00006863
6864//===----------------------------------------------------------------------===//
6865// Builtin Type Computation
6866//===----------------------------------------------------------------------===//
6867
6868/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006869/// pointer over the consumed characters. This returns the resultant type. If
6870/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6871/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6872/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006873///
6874/// RequiresICE is filled in on return to indicate whether the value is required
6875/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006876static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006877 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006878 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006879 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006880 // Modifiers.
6881 int HowLong = 0;
6882 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006883 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006884
Chris Lattnerdc226c22010-10-01 22:42:38 +00006885 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006886 bool Done = false;
6887 while (!Done) {
6888 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006889 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006890 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006891 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006892 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006893 case 'S':
6894 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6895 assert(!Signed && "Can't use 'S' modifier multiple times!");
6896 Signed = true;
6897 break;
6898 case 'U':
6899 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6900 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6901 Unsigned = true;
6902 break;
6903 case 'L':
6904 assert(HowLong <= 2 && "Can't have LLLL modifier");
6905 ++HowLong;
6906 break;
6907 }
6908 }
6909
6910 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006911
Chris Lattnerecd79c62009-06-14 00:45:47 +00006912 // Read the base type.
6913 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006914 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006915 case 'v':
6916 assert(HowLong == 0 && !Signed && !Unsigned &&
6917 "Bad modifiers used with 'v'!");
6918 Type = Context.VoidTy;
6919 break;
6920 case 'f':
6921 assert(HowLong == 0 && !Signed && !Unsigned &&
6922 "Bad modifiers used with 'f'!");
6923 Type = Context.FloatTy;
6924 break;
6925 case 'd':
6926 assert(HowLong < 2 && !Signed && !Unsigned &&
6927 "Bad modifiers used with 'd'!");
6928 if (HowLong)
6929 Type = Context.LongDoubleTy;
6930 else
6931 Type = Context.DoubleTy;
6932 break;
6933 case 's':
6934 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6935 if (Unsigned)
6936 Type = Context.UnsignedShortTy;
6937 else
6938 Type = Context.ShortTy;
6939 break;
6940 case 'i':
6941 if (HowLong == 3)
6942 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6943 else if (HowLong == 2)
6944 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6945 else if (HowLong == 1)
6946 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6947 else
6948 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6949 break;
6950 case 'c':
6951 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6952 if (Signed)
6953 Type = Context.SignedCharTy;
6954 else if (Unsigned)
6955 Type = Context.UnsignedCharTy;
6956 else
6957 Type = Context.CharTy;
6958 break;
6959 case 'b': // boolean
6960 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6961 Type = Context.BoolTy;
6962 break;
6963 case 'z': // size_t.
6964 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6965 Type = Context.getSizeType();
6966 break;
6967 case 'F':
6968 Type = Context.getCFConstantStringType();
6969 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006970 case 'G':
6971 Type = Context.getObjCIdType();
6972 break;
6973 case 'H':
6974 Type = Context.getObjCSelType();
6975 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006976 case 'a':
6977 Type = Context.getBuiltinVaListType();
6978 assert(!Type.isNull() && "builtin va list type not initialized!");
6979 break;
6980 case 'A':
6981 // This is a "reference" to a va_list; however, what exactly
6982 // this means depends on how va_list is defined. There are two
6983 // different kinds of va_list: ones passed by value, and ones
6984 // passed by reference. An example of a by-value va_list is
6985 // x86, where va_list is a char*. An example of by-ref va_list
6986 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6987 // we want this argument to be a char*&; for x86-64, we want
6988 // it to be a __va_list_tag*.
6989 Type = Context.getBuiltinVaListType();
6990 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006991 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006992 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006993 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006994 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006995 break;
6996 case 'V': {
6997 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006998 unsigned NumElements = strtoul(Str, &End, 10);
6999 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007000 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007001
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007002 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7003 RequiresICE, false);
7004 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007005
7006 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007007 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007008 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007009 break;
7010 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007011 case 'E': {
7012 char *End;
7013
7014 unsigned NumElements = strtoul(Str, &End, 10);
7015 assert(End != Str && "Missing vector size");
7016
7017 Str = End;
7018
7019 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7020 false);
7021 Type = Context.getExtVectorType(ElementType, NumElements);
7022 break;
7023 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007024 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007025 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7026 false);
7027 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007028 Type = Context.getComplexType(ElementType);
7029 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007030 }
7031 case 'Y' : {
7032 Type = Context.getPointerDiffType();
7033 break;
7034 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007035 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007036 Type = Context.getFILEType();
7037 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007038 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007039 return QualType();
7040 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007041 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007042 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007043 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007044 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007045 else
7046 Type = Context.getjmp_bufType();
7047
Mike Stump2adb4da2009-07-28 23:47:15 +00007048 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007049 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007050 return QualType();
7051 }
7052 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007053 case 'K':
7054 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7055 Type = Context.getucontext_tType();
7056
7057 if (Type.isNull()) {
7058 Error = ASTContext::GE_Missing_ucontext;
7059 return QualType();
7060 }
7061 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007062 }
Mike Stump11289f42009-09-09 15:08:12 +00007063
Chris Lattnerdc226c22010-10-01 22:42:38 +00007064 // If there are modifiers and if we're allowed to parse them, go for it.
7065 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007066 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007067 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007068 default: Done = true; --Str; break;
7069 case '*':
7070 case '&': {
7071 // Both pointers and references can have their pointee types
7072 // qualified with an address space.
7073 char *End;
7074 unsigned AddrSpace = strtoul(Str, &End, 10);
7075 if (End != Str && AddrSpace != 0) {
7076 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7077 Str = End;
7078 }
7079 if (c == '*')
7080 Type = Context.getPointerType(Type);
7081 else
7082 Type = Context.getLValueReferenceType(Type);
7083 break;
7084 }
7085 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7086 case 'C':
7087 Type = Type.withConst();
7088 break;
7089 case 'D':
7090 Type = Context.getVolatileType(Type);
7091 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007092 case 'R':
7093 Type = Type.withRestrict();
7094 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007095 }
7096 }
Chris Lattner84733392010-10-01 07:13:18 +00007097
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007098 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007099 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007100
Chris Lattnerecd79c62009-06-14 00:45:47 +00007101 return Type;
7102}
7103
7104/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007105QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007106 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007107 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007108 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007109
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007110 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007111
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007112 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007113 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007114 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7115 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007116 if (Error != GE_None)
7117 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007118
7119 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7120
Chris Lattnerecd79c62009-06-14 00:45:47 +00007121 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007122 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007123 if (Error != GE_None)
7124 return QualType();
7125
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007126 // If this argument is required to be an IntegerConstantExpression and the
7127 // caller cares, fill in the bitmask we return.
7128 if (RequiresICE && IntegerConstantArgs)
7129 *IntegerConstantArgs |= 1 << ArgTypes.size();
7130
Chris Lattnerecd79c62009-06-14 00:45:47 +00007131 // Do array -> pointer decay. The builtin should use the decayed type.
7132 if (Ty->isArrayType())
7133 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007134
Chris Lattnerecd79c62009-06-14 00:45:47 +00007135 ArgTypes.push_back(Ty);
7136 }
7137
7138 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7139 "'.' should only occur at end of builtin type list!");
7140
John McCall991eb4b2010-12-21 00:44:39 +00007141 FunctionType::ExtInfo EI;
7142 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7143
7144 bool Variadic = (TypeStr[0] == '.');
7145
7146 // We really shouldn't be making a no-proto type here, especially in C++.
7147 if (ArgTypes.empty() && Variadic)
7148 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007149
John McCalldb40c7f2010-12-14 08:05:40 +00007150 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007151 EPI.ExtInfo = EI;
7152 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007153
7154 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007155}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007156
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007157GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7158 GVALinkage External = GVA_StrongExternal;
7159
7160 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007161 switch (L) {
7162 case NoLinkage:
7163 case InternalLinkage:
7164 case UniqueExternalLinkage:
7165 return GVA_Internal;
7166
7167 case ExternalLinkage:
7168 switch (FD->getTemplateSpecializationKind()) {
7169 case TSK_Undeclared:
7170 case TSK_ExplicitSpecialization:
7171 External = GVA_StrongExternal;
7172 break;
7173
7174 case TSK_ExplicitInstantiationDefinition:
7175 return GVA_ExplicitTemplateInstantiation;
7176
7177 case TSK_ExplicitInstantiationDeclaration:
7178 case TSK_ImplicitInstantiation:
7179 External = GVA_TemplateInstantiation;
7180 break;
7181 }
7182 }
7183
7184 if (!FD->isInlined())
7185 return External;
7186
David Blaikiebbafb8a2012-03-11 07:00:24 +00007187 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007188 // GNU or C99 inline semantics. Determine whether this symbol should be
7189 // externally visible.
7190 if (FD->isInlineDefinitionExternallyVisible())
7191 return External;
7192
7193 // C99 inline semantics, where the symbol is not externally visible.
7194 return GVA_C99Inline;
7195 }
7196
7197 // C++0x [temp.explicit]p9:
7198 // [ Note: The intent is that an inline function that is the subject of
7199 // an explicit instantiation declaration will still be implicitly
7200 // instantiated when used so that the body can be considered for
7201 // inlining, but that no out-of-line copy of the inline function would be
7202 // generated in the translation unit. -- end note ]
7203 if (FD->getTemplateSpecializationKind()
7204 == TSK_ExplicitInstantiationDeclaration)
7205 return GVA_C99Inline;
7206
7207 return GVA_CXXInline;
7208}
7209
7210GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7211 // If this is a static data member, compute the kind of template
7212 // specialization. Otherwise, this variable is not part of a
7213 // template.
7214 TemplateSpecializationKind TSK = TSK_Undeclared;
7215 if (VD->isStaticDataMember())
7216 TSK = VD->getTemplateSpecializationKind();
7217
7218 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007219 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007220 VD->getType()->getLinkage() == UniqueExternalLinkage)
7221 L = UniqueExternalLinkage;
7222
7223 switch (L) {
7224 case NoLinkage:
7225 case InternalLinkage:
7226 case UniqueExternalLinkage:
7227 return GVA_Internal;
7228
7229 case ExternalLinkage:
7230 switch (TSK) {
7231 case TSK_Undeclared:
7232 case TSK_ExplicitSpecialization:
7233 return GVA_StrongExternal;
7234
7235 case TSK_ExplicitInstantiationDeclaration:
7236 llvm_unreachable("Variable should not be instantiated");
7237 // Fall through to treat this like any other instantiation.
7238
7239 case TSK_ExplicitInstantiationDefinition:
7240 return GVA_ExplicitTemplateInstantiation;
7241
7242 case TSK_ImplicitInstantiation:
7243 return GVA_TemplateInstantiation;
7244 }
7245 }
7246
David Blaikie8a40f702012-01-17 06:56:22 +00007247 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007248}
7249
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007250bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007251 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7252 if (!VD->isFileVarDecl())
7253 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007254 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007255 return false;
7256
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007257 // Weak references don't produce any output by themselves.
7258 if (D->hasAttr<WeakRefAttr>())
7259 return false;
7260
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007261 // Aliases and used decls are required.
7262 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7263 return true;
7264
7265 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7266 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007267 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007268 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007269
7270 // Constructors and destructors are required.
7271 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7272 return true;
7273
7274 // The key function for a class is required.
7275 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7276 const CXXRecordDecl *RD = MD->getParent();
7277 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7278 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7279 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7280 return true;
7281 }
7282 }
7283
7284 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7285
7286 // static, static inline, always_inline, and extern inline functions can
7287 // always be deferred. Normal inline functions can be deferred in C99/C++.
7288 // Implicit template instantiations can also be deferred in C++.
7289 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007290 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007291 return false;
7292 return true;
7293 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007294
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007295 const VarDecl *VD = cast<VarDecl>(D);
7296 assert(VD->isFileVarDecl() && "Expected file scoped var");
7297
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007298 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7299 return false;
7300
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007301 // Structs that have non-trivial constructors or destructors are required.
7302
7303 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007304 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007305 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7306 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007307 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7308 RD->hasTrivialCopyConstructor() &&
7309 RD->hasTrivialMoveConstructor() &&
7310 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007311 return true;
7312 }
7313 }
7314
7315 GVALinkage L = GetGVALinkageForVariable(VD);
7316 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7317 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7318 return false;
7319 }
7320
7321 return true;
7322}
Charles Davis53c59df2010-08-16 03:33:14 +00007323
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007324CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007325 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007326 return ABI->getDefaultMethodCallConv(isVariadic);
7327}
7328
7329CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7330 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7331 return CC_Default;
7332 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007333}
7334
Jay Foad39c79802011-01-12 09:06:06 +00007335bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007336 // Pass through to the C++ ABI object
7337 return ABI->isNearlyEmpty(RD);
7338}
7339
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007340MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007341 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007342 case CXXABI_ARM:
7343 case CXXABI_Itanium:
7344 return createItaniumMangleContext(*this, getDiagnostics());
7345 case CXXABI_Microsoft:
7346 return createMicrosoftMangleContext(*this, getDiagnostics());
7347 }
David Blaikie83d382b2011-09-23 05:06:16 +00007348 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007349}
7350
Charles Davis53c59df2010-08-16 03:33:14 +00007351CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007352
7353size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007354 return ASTRecordLayouts.getMemorySize()
7355 + llvm::capacity_in_bytes(ObjCLayouts)
7356 + llvm::capacity_in_bytes(KeyFunctions)
7357 + llvm::capacity_in_bytes(ObjCImpls)
7358 + llvm::capacity_in_bytes(BlockVarCopyInits)
7359 + llvm::capacity_in_bytes(DeclAttrs)
7360 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7361 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7362 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7363 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7364 + llvm::capacity_in_bytes(OverriddenMethods)
7365 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007366 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007367 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007368}
Ted Kremenek540017e2011-10-06 05:00:56 +00007369
Douglas Gregor63798542012-02-20 19:44:39 +00007370unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7371 CXXRecordDecl *Lambda = CallOperator->getParent();
7372 return LambdaMangleContexts[Lambda->getDeclContext()]
7373 .getManglingNumber(CallOperator);
7374}
7375
7376
Ted Kremenek540017e2011-10-06 05:00:56 +00007377void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7378 ParamIndices[D] = index;
7379}
7380
7381unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7382 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7383 assert(I != ParamIndices.end() &&
7384 "ParmIndices lacks entry set by ParmVarDecl");
7385 return I->second;
7386}