blob: 874861872a644a27fd1007a10e1cd371d87a3ede [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Dmitri Gribenkoaa580812012-08-09 00:03:17 +000016#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000017#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000020#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000021#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000023#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000024#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000026#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000028#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000030#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000031#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000032#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000033#include "llvm/Support/raw_ostream.h"
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +000034#include "llvm/Support/Capacity.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000035#include "CXXABI.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000036#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000037
Reid Spencer5f016e22007-07-11 17:01:13 +000038using namespace clang;
39
Douglas Gregor18274032010-07-03 00:47:00 +000040unsigned ASTContext::NumImplicitDefaultConstructors;
41unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000042unsigned ASTContext::NumImplicitCopyConstructors;
43unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000044unsigned ASTContext::NumImplicitMoveConstructors;
45unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000046unsigned ASTContext::NumImplicitCopyAssignmentOperators;
47unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000048unsigned ASTContext::NumImplicitMoveAssignmentOperators;
49unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000050unsigned ASTContext::NumImplicitDestructors;
51unsigned ASTContext::NumImplicitDestructorsDeclared;
52
Reid Spencer5f016e22007-07-11 17:01:13 +000053enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000054 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000055};
56
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000057RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000058 if (!CommentsLoaded && ExternalSource) {
59 ExternalSource->ReadComments();
60 CommentsLoaded = true;
61 }
62
63 assert(D);
64
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000065 // User can not attach documentation to implicit declarations.
66 if (D->isImplicit())
67 return NULL;
68
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +000069 // User can not attach documentation to implicit instantiations.
70 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
71 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
72 return NULL;
73 }
74
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000075 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
76 if (VD->isStaticDataMember() &&
77 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
78 return NULL;
79 }
80
81 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
82 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
83 return NULL;
84 }
85
86 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
87 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
88 return NULL;
89 }
90
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000091 // TODO: handle comments for function parameters properly.
92 if (isa<ParmVarDecl>(D))
93 return NULL;
94
Dmitri Gribenko96b09862012-07-31 22:37:06 +000095 // TODO: we could look up template parameter documentation in the template
96 // documentation.
97 if (isa<TemplateTypeParmDecl>(D) ||
98 isa<NonTypeTemplateParmDecl>(D) ||
99 isa<TemplateTemplateParmDecl>(D))
100 return NULL;
101
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000102 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000103
104 // If there are no comments anywhere, we won't find anything.
105 if (RawComments.empty())
106 return NULL;
107
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000108 // Find declaration location.
109 // For Objective-C declarations we generally don't expect to have multiple
110 // declarators, thus use declaration starting location as the "declaration
111 // location".
112 // For all other declarations multiple declarators are used quite frequently,
113 // so we use the location of the identifier as the "declaration location".
114 SourceLocation DeclLoc;
115 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000116 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +0000117 isa<RedeclarableTemplateDecl>(D) ||
118 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000119 DeclLoc = D->getLocStart();
120 else
121 DeclLoc = D->getLocation();
122
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000123 // If the declaration doesn't map directly to a location in a file, we
124 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000125 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
126 return NULL;
127
128 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000129 ArrayRef<RawComment *>::iterator Comment;
130 {
131 // When searching for comments during parsing, the comment we are looking
132 // for is usually among the last two comments we parsed -- check them
133 // first.
134 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
135 BeforeThanCompare<RawComment> Compare(SourceMgr);
136 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
137 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
138 if (!Found && RawComments.size() >= 2) {
139 MaybeBeforeDecl--;
140 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
141 }
142
143 if (Found) {
144 Comment = MaybeBeforeDecl + 1;
145 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
146 &CommentAtDeclLoc, Compare));
147 } else {
148 // Slow path.
149 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
150 &CommentAtDeclLoc, Compare);
151 }
152 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000153
154 // Decompose the location for the declaration and find the beginning of the
155 // file buffer.
156 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
157
158 // First check whether we have a trailing comment.
159 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000160 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000161 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000162 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000163 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000164 // Check that Doxygen trailing comment comes after the declaration, starts
165 // on the same line and in the same file as the declaration.
166 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
167 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
168 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
169 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000170 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000171 }
172 }
173
174 // The comment just after the declaration was not a trailing comment.
175 // Let's look at the previous comment.
176 if (Comment == RawComments.begin())
177 return NULL;
178 --Comment;
179
180 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000181 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000182 return NULL;
183
184 // Decompose the end of the comment.
185 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000186 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000187
188 // If the comment and the declaration aren't in the same file, then they
189 // aren't related.
190 if (DeclLocDecomp.first != CommentEndDecomp.first)
191 return NULL;
192
193 // Get the corresponding buffer.
194 bool Invalid = false;
195 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
196 &Invalid).data();
197 if (Invalid)
198 return NULL;
199
200 // Extract text between the comment and declaration.
201 StringRef Text(Buffer + CommentEndDecomp.second,
202 DeclLocDecomp.second - CommentEndDecomp.second);
203
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000204 // There should be no other declarations or preprocessor directives between
205 // comment and declaration.
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000206 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000207 return NULL;
208
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000209 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000210}
211
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000212namespace {
213/// If we have a 'templated' declaration for a template, adjust 'D' to
214/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000215/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000216const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000217 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000218 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000219 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000220 return FTD;
221
222 // Nothing to do if function is not an implicit instantiation.
223 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
224 return D;
225
226 // Function is an implicit instantiation of a function template?
227 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
228 return FTD;
229
230 // Function is instantiated from a member definition of a class template?
231 if (const FunctionDecl *MemberDecl =
232 FD->getInstantiatedFromMemberFunction())
233 return MemberDecl;
234
235 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000236 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000237 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
238 // Static data member is instantiated from a member definition of a class
239 // template?
240 if (VD->isStaticDataMember())
241 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
242 return MemberDecl;
243
244 return D;
245 }
246 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
247 // Is this class declaration part of a class template?
248 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
249 return CTD;
250
251 // Class is an implicit instantiation of a class template or partial
252 // specialization?
253 if (const ClassTemplateSpecializationDecl *CTSD =
254 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
255 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
256 return D;
257 llvm::PointerUnion<ClassTemplateDecl *,
258 ClassTemplatePartialSpecializationDecl *>
259 PU = CTSD->getSpecializedTemplateOrPartial();
260 return PU.is<ClassTemplateDecl*>() ?
261 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
262 static_cast<const Decl*>(
263 PU.get<ClassTemplatePartialSpecializationDecl *>());
264 }
265
266 // Class is instantiated from a member definition of a class template?
267 if (const MemberSpecializationInfo *Info =
268 CRD->getMemberSpecializationInfo())
269 return Info->getInstantiatedFrom();
270
271 return D;
272 }
273 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
274 // Enum is instantiated from a member definition of a class template?
275 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
276 return MemberDecl;
277
278 return D;
279 }
280 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000281 return D;
282}
283} // unnamed namespace
284
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000285const RawComment *ASTContext::getRawCommentForAnyRedecl(
286 const Decl *D,
287 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000288 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000289
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000290 // Check whether we have cached a comment for this declaration already.
291 {
292 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
293 RedeclComments.find(D);
294 if (Pos != RedeclComments.end()) {
295 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000296 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
297 if (OriginalDecl)
298 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000299 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000300 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000301 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000302 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000303
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000304 // Search for comments attached to declarations in the redeclaration chain.
305 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000306 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000307 for (Decl::redecl_iterator I = D->redecls_begin(),
308 E = D->redecls_end();
309 I != E; ++I) {
310 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
311 RedeclComments.find(*I);
312 if (Pos != RedeclComments.end()) {
313 const RawCommentAndCacheFlags &Raw = Pos->second;
314 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
315 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000316 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000317 break;
318 }
319 } else {
320 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000321 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000322 RawCommentAndCacheFlags Raw;
323 if (RC) {
324 Raw.setRaw(RC);
325 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
326 } else
327 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000328 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000329 RedeclComments[*I] = Raw;
330 if (RC)
331 break;
332 }
333 }
334
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000335 // If we found a comment, it should be a documentation comment.
336 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000337
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000338 if (OriginalDecl)
339 *OriginalDecl = OriginalDeclForRC;
340
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000341 // Update cache for every declaration in the redeclaration chain.
342 RawCommentAndCacheFlags Raw;
343 Raw.setRaw(RC);
344 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000345 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000346
347 for (Decl::redecl_iterator I = D->redecls_begin(),
348 E = D->redecls_end();
349 I != E; ++I) {
350 RawCommentAndCacheFlags &R = RedeclComments[*I];
351 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
352 R = Raw;
353 }
354
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000355 return RC;
356}
357
Dmitri Gribenko19523542012-09-29 11:40:46 +0000358comments::FullComment *ASTContext::getCommentForDecl(
359 const Decl *D,
360 const Preprocessor *PP) const {
Dmitri Gribenkoc41ace92012-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 Gribenko1599eac2012-08-16 18:19:43 +0000368 const Decl *OriginalDecl;
369 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000370 if (!RC)
371 return NULL;
372
Dmitri Gribenko4b41c652012-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 Gribenko1599eac2012-08-16 18:19:43 +0000377 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000378 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000379
Dmitri Gribenko19523542012-09-29 11:40:46 +0000380 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000381 ParsedComments[Canonical] = FC;
382 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000383}
384
Douglas Gregor3e1274f2010-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 Gregor61c4d282011-01-05 15:48:55 +0000390 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-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 Gregor61c4d282011-01-05 15:48:55 +0000405 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000406 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000407 if (NTTP->isExpandedParameterPack()) {
408 ID.AddBoolean(true);
409 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-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 Gregor6952f1e2011-01-19 20:10:05 +0000414 } else
415 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-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 Foad4ba2a172011-01-12 09:06:06 +0000427 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-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 Lattner5f9e2722011-07-23 10:55:15 +0000439 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-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 Bagnara344577e2011-03-06 15:48:19 +0000447 SourceLocation(),
448 SourceLocation(),
449 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000450 TTP->getIndex(), 0, false,
451 TTP->isParameterPack()));
452 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-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 Lattner5f9e2722011-07-23 10:55:15 +0000458 SmallVector<QualType, 2> ExpandedTypes;
459 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-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 Bagnaraff676cb2011-03-08 08:55:46 +0000467 SourceLocation(),
468 SourceLocation(),
Douglas Gregor6952f1e2011-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 Bagnaraff676cb2011-03-08 08:55:46 +0000478 SourceLocation(),
479 SourceLocation(),
Douglas Gregor6952f1e2011-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 Gregor3e1274f2010-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 Gregor61c4d282011-01-05 15:48:55 +0000496 TTP->getPosition(),
497 TTP->isParameterPack(),
498 0,
Douglas Gregor3e1274f2010-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 Davis071cc7d2010-08-16 03:33:14 +0000516CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000517 if (!LangOpts.CPlusPlus) return 0;
518
Charles Davis20cf7172010-08-19 02:18:14 +0000519 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000520 case CXXABI_ARM:
521 return CreateARMCXXABI(*this);
522 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000523 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000524 case CXXABI_Microsoft:
525 return CreateMicrosoftCXXABI(*this);
526 }
David Blaikie7530c032012-01-17 06:56:22 +0000527 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000528}
529
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000530static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-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 Collingbourne4dc34eb2012-05-20 21:08:35 +0000538 3, // opencl_constant
539 4, // cuda_device
540 5, // cuda_constant
541 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000542 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000543 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000544 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000545 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000546 }
547}
548
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000549ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000550 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000551 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000552 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-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 Ingec5613b22012-06-16 03:34:49 +0000561 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000562 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000563 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000564 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000565 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000566 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
567 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
568 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000569 NullTypeSourceInfo(QualType()),
570 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000571 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000572 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000573 Idents(idents), Selectors(sels),
574 BuiltinInfo(builtins),
575 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000576 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000577 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +0000578 CommentCommandTraits(BumpAlloc),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000579 LastSDM(0, 0),
580 UniqueBlockByRefTypeID(0)
581{
Mike Stump1eb44332009-09-09 15:08:12 +0000582 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000583 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000584
585 if (!DelayInitialization) {
586 assert(t && "No target supplied for ASTContext initialization");
587 InitBuiltinTypes(*t);
588 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000589}
590
Reid Spencer5f016e22007-07-11 17:01:13 +0000591ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000592 // Release the DenseMaps associated with DeclContext objects.
593 // FIXME: Is this the ideal solution?
594 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000595
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000596 // Call all of the deallocation functions.
597 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
598 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000599
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000600 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000601 // because they can contain DenseMaps.
602 for (llvm::DenseMap<const ObjCContainerDecl*,
603 const ASTRecordLayout*>::iterator
604 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
605 // Increment in loop to prevent using deallocated memory.
606 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
607 R->Destroy(*this);
608
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000609 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
610 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
611 // Increment in loop to prevent using deallocated memory.
612 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
613 R->Destroy(*this);
614 }
Douglas Gregor63200642010-08-30 16:49:28 +0000615
616 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
617 AEnd = DeclAttrs.end();
618 A != AEnd; ++A)
619 A->second->~AttrVec();
620}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000621
Douglas Gregor00545312010-05-23 18:26:36 +0000622void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
623 Deallocations.push_back(std::make_pair(Callback, Data));
624}
625
Mike Stump1eb44332009-09-09 15:08:12 +0000626void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000627ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000628 ExternalSource.reset(Source.take());
629}
630
Reid Spencer5f016e22007-07-11 17:01:13 +0000631void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000632 llvm::errs() << "\n*** AST Context Stats:\n";
633 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000634
Douglas Gregordbe833d2009-05-26 14:40:08 +0000635 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000636#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000637#define ABSTRACT_TYPE(Name, Parent)
638#include "clang/AST/TypeNodes.def"
639 0 // Extra
640 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000641
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
643 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000644 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 }
646
Douglas Gregordbe833d2009-05-26 14:40:08 +0000647 unsigned Idx = 0;
648 unsigned TotalBytes = 0;
649#define TYPE(Name, Parent) \
650 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000651 llvm::errs() << " " << counts[Idx] << " " << #Name \
652 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000653 TotalBytes += counts[Idx] * sizeof(Name##Type); \
654 ++Idx;
655#define ABSTRACT_TYPE(Name, Parent)
656#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Chandler Carruthcd92a652011-07-04 05:32:14 +0000658 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
659
Douglas Gregor4923aa22010-07-02 20:37:36 +0000660 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000661 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
662 << NumImplicitDefaultConstructors
663 << " implicit default constructors created\n";
664 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
665 << NumImplicitCopyConstructors
666 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000667 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000668 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
669 << NumImplicitMoveConstructors
670 << " implicit move constructors created\n";
671 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
672 << NumImplicitCopyAssignmentOperators
673 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000674 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000675 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
676 << NumImplicitMoveAssignmentOperators
677 << " implicit move assignment operators created\n";
678 llvm::errs() << NumImplicitDestructorsDeclared << "/"
679 << NumImplicitDestructors
680 << " implicit destructors created\n";
681
Douglas Gregor2cf26342009-04-09 22:27:44 +0000682 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000683 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000684 ExternalSource->PrintStats();
685 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000686
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000687 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000688}
689
Douglas Gregor772eeae2011-08-12 06:49:56 +0000690TypedefDecl *ASTContext::getInt128Decl() const {
691 if (!Int128Decl) {
692 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
693 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
694 getTranslationUnitDecl(),
695 SourceLocation(),
696 SourceLocation(),
697 &Idents.get("__int128_t"),
698 TInfo);
699 }
700
701 return Int128Decl;
702}
703
704TypedefDecl *ASTContext::getUInt128Decl() const {
705 if (!UInt128Decl) {
706 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
707 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
708 getTranslationUnitDecl(),
709 SourceLocation(),
710 SourceLocation(),
711 &Idents.get("__uint128_t"),
712 TInfo);
713 }
714
715 return UInt128Decl;
716}
Reid Spencer5f016e22007-07-11 17:01:13 +0000717
John McCalle27ec8a2009-10-23 23:03:21 +0000718void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000719 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000720 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000721 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000722}
723
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000724void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
725 assert((!this->Target || this->Target == &Target) &&
726 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000729 this->Target = &Target;
730
731 ABI.reset(createCXXABI(Target));
732 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
733
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 // C99 6.2.5p19.
735 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 // C99 6.2.5p2.
738 InitBuiltinType(BoolTy, BuiltinType::Bool);
739 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000740 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000741 InitBuiltinType(CharTy, BuiltinType::Char_S);
742 else
743 InitBuiltinType(CharTy, BuiltinType::Char_U);
744 // C99 6.2.5p4.
745 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
746 InitBuiltinType(ShortTy, BuiltinType::Short);
747 InitBuiltinType(IntTy, BuiltinType::Int);
748 InitBuiltinType(LongTy, BuiltinType::Long);
749 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 // C99 6.2.5p6.
752 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
753 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
754 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
755 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
756 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Reid Spencer5f016e22007-07-11 17:01:13 +0000758 // C99 6.2.5p10.
759 InitBuiltinType(FloatTy, BuiltinType::Float);
760 InitBuiltinType(DoubleTy, BuiltinType::Double);
761 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000762
Chris Lattner2df9ced2009-04-30 02:43:43 +0000763 // GNU extension, 128-bit integers.
764 InitBuiltinType(Int128Ty, BuiltinType::Int128);
765 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
766
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000767 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000768 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000769 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
770 else // -fshort-wchar makes wchar_t be unsigned.
771 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000772 } else // C99 (or C++ using -fno-wchar)
Chris Lattner3a250322009-02-26 23:43:47 +0000773 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000774
James Molloy392da482012-05-04 10:55:22 +0000775 WIntTy = getFromTargetType(Target.getWIntType());
776
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000777 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
778 InitBuiltinType(Char16Ty, BuiltinType::Char16);
779 else // C99
780 Char16Ty = getFromTargetType(Target.getChar16Type());
781
782 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
783 InitBuiltinType(Char32Ty, BuiltinType::Char32);
784 else // C99
785 Char32Ty = getFromTargetType(Target.getChar32Type());
786
Douglas Gregor898574e2008-12-05 23:32:09 +0000787 // Placeholder type for type-dependent expressions whose type is
788 // completely unknown. No code should ever check a type against
789 // DependentTy and users should never see it; however, it is here to
790 // help diagnose failures to properly check for type-dependent
791 // expressions.
792 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000793
John McCall2a984ca2010-10-12 00:20:44 +0000794 // Placeholder type for functions.
795 InitBuiltinType(OverloadTy, BuiltinType::Overload);
796
John McCall864c0412011-04-26 20:42:42 +0000797 // Placeholder type for bound members.
798 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
799
John McCall3c3b7f92011-10-25 17:37:35 +0000800 // Placeholder type for pseudo-objects.
801 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
802
John McCall1de4d4e2011-04-07 08:22:57 +0000803 // "any" type; useful for debugger-like clients.
804 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
805
John McCall0ddaeb92011-10-17 18:09:15 +0000806 // Placeholder type for unbridged ARC casts.
807 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
808
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000809 // Placeholder type for builtin functions.
810 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
811
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 // C99 6.2.5p11.
813 FloatComplexTy = getComplexType(FloatTy);
814 DoubleComplexTy = getComplexType(DoubleTy);
815 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000816
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000817 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000818 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
819 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000820 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000821
822 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000823 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
824 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000825
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000826 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000828 // void * type
829 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000830
831 // nullptr type (C++0x 2.14.7)
832 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000833
834 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
835 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000836
837 // Builtin type used to help define __builtin_va_list.
838 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000839}
840
David Blaikied6471f72011-09-25 23:23:43 +0000841DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000842 return SourceMgr.getDiagnostics();
843}
844
Douglas Gregor63200642010-08-30 16:49:28 +0000845AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
846 AttrVec *&Result = DeclAttrs[D];
847 if (!Result) {
848 void *Mem = Allocate(sizeof(AttrVec));
849 Result = new (Mem) AttrVec;
850 }
851
852 return *Result;
853}
854
855/// \brief Erase the attributes corresponding to the given declaration.
856void ASTContext::eraseDeclAttrs(const Decl *D) {
857 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
858 if (Pos != DeclAttrs.end()) {
859 Pos->second->~AttrVec();
860 DeclAttrs.erase(Pos);
861 }
862}
863
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000864MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000865ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000866 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000867 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000868 = InstantiatedFromStaticDataMember.find(Var);
869 if (Pos == InstantiatedFromStaticDataMember.end())
870 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Douglas Gregor7caa6822009-07-24 20:34:43 +0000872 return Pos->second;
873}
874
Mike Stump1eb44332009-09-09 15:08:12 +0000875void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000876ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000877 TemplateSpecializationKind TSK,
878 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000879 assert(Inst->isStaticDataMember() && "Not a static data member");
880 assert(Tmpl->isStaticDataMember() && "Not a static data member");
881 assert(!InstantiatedFromStaticDataMember[Inst] &&
882 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000883 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000884 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000885}
886
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000887FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
888 const FunctionDecl *FD){
889 assert(FD && "Specialization is 0");
890 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000891 = ClassScopeSpecializationPattern.find(FD);
892 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000893 return 0;
894
895 return Pos->second;
896}
897
898void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
899 FunctionDecl *Pattern) {
900 assert(FD && "Specialization is 0");
901 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000902 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000903}
904
John McCall7ba107a2009-11-18 02:36:19 +0000905NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000906ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000907 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000908 = InstantiatedFromUsingDecl.find(UUD);
909 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000910 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Anders Carlsson0d8df782009-08-29 19:37:28 +0000912 return Pos->second;
913}
914
915void
John McCalled976492009-12-04 22:46:56 +0000916ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
917 assert((isa<UsingDecl>(Pattern) ||
918 isa<UnresolvedUsingValueDecl>(Pattern) ||
919 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
920 "pattern decl is not a using decl");
921 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
922 InstantiatedFromUsingDecl[Inst] = Pattern;
923}
924
925UsingShadowDecl *
926ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
927 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
928 = InstantiatedFromUsingShadowDecl.find(Inst);
929 if (Pos == InstantiatedFromUsingShadowDecl.end())
930 return 0;
931
932 return Pos->second;
933}
934
935void
936ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
937 UsingShadowDecl *Pattern) {
938 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
939 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000940}
941
Anders Carlssond8b285f2009-09-01 04:26:58 +0000942FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
943 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
944 = InstantiatedFromUnnamedFieldDecl.find(Field);
945 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
946 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Anders Carlssond8b285f2009-09-01 04:26:58 +0000948 return Pos->second;
949}
950
951void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
952 FieldDecl *Tmpl) {
953 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
954 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
955 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
956 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Anders Carlssond8b285f2009-09-01 04:26:58 +0000958 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
959}
960
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000961bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
962 const FieldDecl *LastFD) const {
963 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000964 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000965}
966
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000967bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
968 const FieldDecl *LastFD) const {
969 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000970 FD->getBitWidthValue(*this) == 0 &&
971 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000972}
973
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000974bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
975 const FieldDecl *LastFD) const {
976 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000977 FD->getBitWidthValue(*this) &&
978 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000979}
980
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000981bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000982 const FieldDecl *LastFD) const {
983 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000984 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000985}
986
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000987bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000988 const FieldDecl *LastFD) const {
989 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000990 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000991}
992
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000993ASTContext::overridden_cxx_method_iterator
994ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
995 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +0000996 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000997 if (Pos == OverriddenMethods.end())
998 return 0;
999
1000 return Pos->second.begin();
1001}
1002
1003ASTContext::overridden_cxx_method_iterator
1004ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1005 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001006 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001007 if (Pos == OverriddenMethods.end())
1008 return 0;
1009
1010 return Pos->second.end();
1011}
1012
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001013unsigned
1014ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1015 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001016 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001017 if (Pos == OverriddenMethods.end())
1018 return 0;
1019
1020 return Pos->second.size();
1021}
1022
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001023void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1024 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001025 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001026 OverriddenMethods[Method].push_back(Overridden);
1027}
1028
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001029void ASTContext::getOverriddenMethods(const NamedDecl *D,
1030 SmallVectorImpl<const NamedDecl *> &Overridden) {
1031 assert(D);
1032
1033 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001034 Overridden.append(CXXMethod->begin_overridden_methods(),
1035 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001036 return;
1037 }
1038
1039 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1040 if (!Method)
1041 return;
1042
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001043 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1044 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001045 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001046}
1047
Douglas Gregore6649772011-12-03 00:30:27 +00001048void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1049 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1050 assert(!Import->isFromASTFile() && "Non-local import declaration");
1051 if (!FirstLocalImport) {
1052 FirstLocalImport = Import;
1053 LastLocalImport = Import;
1054 return;
1055 }
1056
1057 LastLocalImport->NextLocalImport = Import;
1058 LastLocalImport = Import;
1059}
1060
Chris Lattner464175b2007-07-18 17:52:12 +00001061//===----------------------------------------------------------------------===//
1062// Type Sizing and Analysis
1063//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001064
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001065/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1066/// scalar floating point type.
1067const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001068 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001069 assert(BT && "Not a floating point type!");
1070 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001071 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001072 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001073 case BuiltinType::Float: return Target->getFloatFormat();
1074 case BuiltinType::Double: return Target->getDoubleFormat();
1075 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001076 }
1077}
1078
Ken Dyck8b752f12010-01-27 17:10:57 +00001079/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001080/// specified decl. Note that bitfields do not have a valid alignment, so
1081/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001082/// If @p RefAsPointee, references are treated like their underlying type
1083/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001084CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001085 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001086
John McCall4081a5c2010-10-08 18:24:19 +00001087 bool UseAlignAttrOnly = false;
1088 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1089 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001090
John McCall4081a5c2010-10-08 18:24:19 +00001091 // __attribute__((aligned)) can increase or decrease alignment
1092 // *except* on a struct or struct member, where it only increases
1093 // alignment unless 'packed' is also specified.
1094 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001095 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001096 // ignore that possibility; Sema should diagnose it.
1097 if (isa<FieldDecl>(D)) {
1098 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1099 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1100 } else {
1101 UseAlignAttrOnly = true;
1102 }
1103 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001104 else if (isa<FieldDecl>(D))
1105 UseAlignAttrOnly =
1106 D->hasAttr<PackedAttr>() ||
1107 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001108
John McCallba4f5d52011-01-20 07:57:12 +00001109 // If we're using the align attribute only, just ignore everything
1110 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001111 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001112 // do nothing
1113
John McCall4081a5c2010-10-08 18:24:19 +00001114 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001115 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001116 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001117 if (RefAsPointee)
1118 T = RT->getPointeeType();
1119 else
1120 T = getPointerType(RT->getPointeeType());
1121 }
1122 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001123 // Adjust alignments of declarations with array type by the
1124 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001125 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001126 const ArrayType *arrayType;
1127 if (MinWidth && (arrayType = getAsArrayType(T))) {
1128 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001129 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001130 else if (isa<ConstantArrayType>(arrayType) &&
1131 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001132 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001133
John McCall3b657512011-01-19 10:06:00 +00001134 // Walk through any array types while we're at it.
1135 T = getBaseElementType(arrayType);
1136 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001137 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +00001138 }
John McCallba4f5d52011-01-20 07:57:12 +00001139
1140 // Fields can be subject to extra alignment constraints, like if
1141 // the field is packed, the struct is packed, or the struct has a
1142 // a max-field-alignment constraint (#pragma pack). So calculate
1143 // the actual alignment of the field within the struct, and then
1144 // (as we're expected to) constrain that by the alignment of the type.
1145 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1146 // So calculate the alignment of the field.
1147 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1148
1149 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001150 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001151
1152 // Use the GCD of that and the offset within the record.
1153 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1154 if (offset > 0) {
1155 // Alignment is always a power of 2, so the GCD will be a power of 2,
1156 // which means we get to do this crazy thing instead of Euclid's.
1157 uint64_t lowBitOfOffset = offset & (~offset + 1);
1158 if (lowBitOfOffset < fieldAlign)
1159 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1160 }
1161
1162 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001163 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001164 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001165
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001166 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001167}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001168
John McCall929bbfb2012-08-21 04:10:00 +00001169// getTypeInfoDataSizeInChars - Return the size of a type, in
1170// chars. If the type is a record, its data size is returned. This is
1171// the size of the memcpy that's performed when assigning this type
1172// using a trivial copy/move assignment operator.
1173std::pair<CharUnits, CharUnits>
1174ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1175 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1176
1177 // In C++, objects can sometimes be allocated into the tail padding
1178 // of a base-class subobject. We decide whether that's possible
1179 // during class layout, so here we can just trust the layout results.
1180 if (getLangOpts().CPlusPlus) {
1181 if (const RecordType *RT = T->getAs<RecordType>()) {
1182 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1183 sizeAndAlign.first = layout.getDataSize();
1184 }
1185 }
1186
1187 return sizeAndAlign;
1188}
1189
John McCallea1471e2010-05-20 01:18:31 +00001190std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001191ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +00001192 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001193 return std::make_pair(toCharUnitsFromBits(Info.first),
1194 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001195}
1196
1197std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001198ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001199 return getTypeInfoInChars(T.getTypePtr());
1200}
1201
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001202std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1203 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1204 if (it != MemoizedTypeInfo.end())
1205 return it->second;
1206
1207 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1208 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1209 return Info;
1210}
1211
1212/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1213/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001214///
1215/// FIXME: Pointers into different addr spaces could have different sizes and
1216/// alignment requirements: getPointerInfo should take an AddrSpace, this
1217/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001218std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001219ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001220 uint64_t Width=0;
1221 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001222 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001223#define TYPE(Class, Base)
1224#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001225#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001226#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1227#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001228 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001229
Chris Lattner692233e2007-07-13 22:27:08 +00001230 case Type::FunctionNoProto:
1231 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001232 // GCC extension: alignof(function) = 32 bits
1233 Width = 0;
1234 Align = 32;
1235 break;
1236
Douglas Gregor72564e72009-02-26 23:50:07 +00001237 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001238 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001239 Width = 0;
1240 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1241 break;
1242
Steve Narofffb22d962007-08-30 01:06:46 +00001243 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001244 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Chris Lattner98be4942008-03-05 18:54:05 +00001246 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001247 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001248 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1249 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001250 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001251 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001252 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001253 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001254 }
Nate Begeman213541a2008-04-18 23:10:10 +00001255 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001256 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001257 const VectorType *VT = cast<VectorType>(T);
1258 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1259 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001260 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001261 // If the alignment is not a power of 2, round up to the next power of 2.
1262 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001263 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001264 Align = llvm::NextPowerOf2(Align);
1265 Width = llvm::RoundUpToAlignment(Width, Align);
1266 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001267 // Adjust the alignment based on the target max.
1268 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1269 if (TargetVectorAlign && TargetVectorAlign < Align)
1270 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001271 break;
1272 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001273
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001274 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001275 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001276 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001277 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001278 // GCC extension: alignof(void) = 8 bits.
1279 Width = 0;
1280 Align = 8;
1281 break;
1282
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001283 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001284 Width = Target->getBoolWidth();
1285 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001286 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001287 case BuiltinType::Char_S:
1288 case BuiltinType::Char_U:
1289 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001290 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001291 Width = Target->getCharWidth();
1292 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001293 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001294 case BuiltinType::WChar_S:
1295 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001296 Width = Target->getWCharWidth();
1297 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001298 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001299 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001300 Width = Target->getChar16Width();
1301 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001302 break;
1303 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001304 Width = Target->getChar32Width();
1305 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001306 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001307 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001308 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001309 Width = Target->getShortWidth();
1310 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001311 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001312 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001313 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001314 Width = Target->getIntWidth();
1315 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001316 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001317 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001318 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001319 Width = Target->getLongWidth();
1320 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001321 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001322 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001323 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001324 Width = Target->getLongLongWidth();
1325 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001326 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001327 case BuiltinType::Int128:
1328 case BuiltinType::UInt128:
1329 Width = 128;
1330 Align = 128; // int128_t is 128-bit aligned on all targets.
1331 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001332 case BuiltinType::Half:
1333 Width = Target->getHalfWidth();
1334 Align = Target->getHalfAlign();
1335 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001336 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001337 Width = Target->getFloatWidth();
1338 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001339 break;
1340 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001341 Width = Target->getDoubleWidth();
1342 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001343 break;
1344 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001345 Width = Target->getLongDoubleWidth();
1346 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001347 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001348 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001349 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1350 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001351 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001352 case BuiltinType::ObjCId:
1353 case BuiltinType::ObjCClass:
1354 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001355 Width = Target->getPointerWidth(0);
1356 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001357 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001358 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001359 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001360 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001361 Width = Target->getPointerWidth(0);
1362 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001363 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001364 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001365 unsigned AS = getTargetAddressSpace(
1366 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001367 Width = Target->getPointerWidth(AS);
1368 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001369 break;
1370 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001371 case Type::LValueReference:
1372 case Type::RValueReference: {
1373 // alignof and sizeof should never enter this code path here, so we go
1374 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001375 unsigned AS = getTargetAddressSpace(
1376 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001377 Width = Target->getPointerWidth(AS);
1378 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001379 break;
1380 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001381 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001382 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001383 Width = Target->getPointerWidth(AS);
1384 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001385 break;
1386 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001387 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001388 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001389 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001390 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001391 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001392 Align = PtrDiffInfo.second;
1393 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001394 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001395 case Type::Complex: {
1396 // Complex types have the same alignment as their elements, but twice the
1397 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001398 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001399 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001400 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001401 Align = EltInfo.second;
1402 break;
1403 }
John McCallc12c5bb2010-05-15 11:32:37 +00001404 case Type::ObjCObject:
1405 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001406 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001407 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001408 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001409 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001410 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001411 break;
1412 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001413 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001414 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001415 const TagType *TT = cast<TagType>(T);
1416
1417 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001418 Width = 8;
1419 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001420 break;
1421 }
Mike Stump1eb44332009-09-09 15:08:12 +00001422
Daniel Dunbar1d751182008-11-08 05:48:37 +00001423 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001424 return getTypeInfo(ET->getDecl()->getIntegerType());
1425
Daniel Dunbar1d751182008-11-08 05:48:37 +00001426 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001427 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001428 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001429 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001430 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001431 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001432
Chris Lattner9fcfe922009-10-22 05:17:15 +00001433 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001434 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1435 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001436
Richard Smith34b41d92011-02-20 03:19:35 +00001437 case Type::Auto: {
1438 const AutoType *A = cast<AutoType>(T);
1439 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001440 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001441 }
1442
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001443 case Type::Paren:
1444 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1445
Douglas Gregor18857642009-04-30 17:32:17 +00001446 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001447 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001448 std::pair<uint64_t, unsigned> Info
1449 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001450 // If the typedef has an aligned attribute on it, it overrides any computed
1451 // alignment we have. This violates the GCC documentation (which says that
1452 // attribute(aligned) can only round up) but matches its implementation.
1453 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1454 Align = AttrAlign;
1455 else
1456 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001457 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001458 break;
Chris Lattner71763312008-04-06 22:05:18 +00001459 }
Douglas Gregor18857642009-04-30 17:32:17 +00001460
1461 case Type::TypeOfExpr:
1462 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1463 .getTypePtr());
1464
1465 case Type::TypeOf:
1466 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1467
Anders Carlsson395b4752009-06-24 19:06:50 +00001468 case Type::Decltype:
1469 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1470 .getTypePtr());
1471
Sean Huntca63c202011-05-24 22:41:36 +00001472 case Type::UnaryTransform:
1473 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1474
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001475 case Type::Elaborated:
1476 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001477
John McCall9d156a72011-01-06 01:58:22 +00001478 case Type::Attributed:
1479 return getTypeInfo(
1480 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1481
Richard Smith3e4c6c42011-05-05 21:57:07 +00001482 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001483 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001484 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001485 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1486 // A type alias template specialization may refer to a typedef with the
1487 // aligned attribute on it.
1488 if (TST->isTypeAlias())
1489 return getTypeInfo(TST->getAliasedType().getTypePtr());
1490 else
1491 return getTypeInfo(getCanonicalType(T));
1492 }
1493
Eli Friedmanb001de72011-10-06 23:00:33 +00001494 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001495 std::pair<uint64_t, unsigned> Info
1496 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1497 Width = Info.first;
1498 Align = Info.second;
1499 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1500 llvm::isPowerOf2_64(Width)) {
1501 // We can potentially perform lock-free atomic operations for this
1502 // type; promote the alignment appropriately.
1503 // FIXME: We could potentially promote the width here as well...
1504 // is that worthwhile? (Non-struct atomic types generally have
1505 // power-of-two size anyway, but structs might not. Requires a bit
1506 // of implementation work to make sure we zero out the extra bits.)
1507 Align = static_cast<unsigned>(Width);
1508 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001509 }
1510
Douglas Gregor18857642009-04-30 17:32:17 +00001511 }
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Eli Friedman2be46072011-10-14 20:59:01 +00001513 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001514 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001515}
1516
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001517/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1518CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1519 return CharUnits::fromQuantity(BitSize / getCharWidth());
1520}
1521
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001522/// toBits - Convert a size in characters to a size in characters.
1523int64_t ASTContext::toBits(CharUnits CharSize) const {
1524 return CharSize.getQuantity() * getCharWidth();
1525}
1526
Ken Dyckbdc601b2009-12-22 14:23:30 +00001527/// getTypeSizeInChars - Return the size of the specified type, in characters.
1528/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001529CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001530 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001531}
Jay Foad4ba2a172011-01-12 09:06:06 +00001532CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001533 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001534}
1535
Ken Dyck16e20cc2010-01-26 17:25:18 +00001536/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001537/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001538CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001539 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001540}
Jay Foad4ba2a172011-01-12 09:06:06 +00001541CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001542 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001543}
1544
Chris Lattner34ebde42009-01-27 18:08:34 +00001545/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1546/// type for the current target in bits. This can be different than the ABI
1547/// alignment in cases where it is beneficial for performance to overalign
1548/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001549unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001550 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001551
1552 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001553 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001554 T = CT->getElementType().getTypePtr();
1555 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001556 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1557 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001558 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1559
Chris Lattner34ebde42009-01-27 18:08:34 +00001560 return ABIAlign;
1561}
1562
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001563/// DeepCollectObjCIvars -
1564/// This routine first collects all declared, but not synthesized, ivars in
1565/// super class and then collects all ivars, including those synthesized for
1566/// current class. This routine is used for implementation of current class
1567/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001568///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001569void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1570 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001571 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001572 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1573 DeepCollectObjCIvars(SuperClass, false, Ivars);
1574 if (!leafClass) {
1575 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1576 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001577 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001578 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001579 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001580 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001581 Iv= Iv->getNextIvar())
1582 Ivars.push_back(Iv);
1583 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001584}
1585
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001586/// CollectInheritedProtocols - Collect all protocols in current class and
1587/// those inherited by it.
1588void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001589 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001590 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001591 // We can use protocol_iterator here instead of
1592 // all_referenced_protocol_iterator since we are walking all categories.
1593 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1594 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001595 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001596 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001597 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001598 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001599 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001600 CollectInheritedProtocols(*P, Protocols);
1601 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001602 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001603
1604 // Categories of this Interface.
1605 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1606 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1607 CollectInheritedProtocols(CDeclChain, Protocols);
1608 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1609 while (SD) {
1610 CollectInheritedProtocols(SD, Protocols);
1611 SD = SD->getSuperClass();
1612 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001613 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001614 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001615 PE = OC->protocol_end(); P != PE; ++P) {
1616 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001617 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001618 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1619 PE = Proto->protocol_end(); P != PE; ++P)
1620 CollectInheritedProtocols(*P, Protocols);
1621 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001622 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001623 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1624 PE = OP->protocol_end(); P != PE; ++P) {
1625 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001626 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001627 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1628 PE = Proto->protocol_end(); P != PE; ++P)
1629 CollectInheritedProtocols(*P, Protocols);
1630 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001631 }
1632}
1633
Jay Foad4ba2a172011-01-12 09:06:06 +00001634unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001635 unsigned count = 0;
1636 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001637 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1638 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001639 count += CDecl->ivar_size();
1640
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001641 // Count ivar defined in this class's implementation. This
1642 // includes synthesized ivars.
1643 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001644 count += ImplDecl->ivar_size();
1645
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001646 return count;
1647}
1648
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001649bool ASTContext::isSentinelNullExpr(const Expr *E) {
1650 if (!E)
1651 return false;
1652
1653 // nullptr_t is always treated as null.
1654 if (E->getType()->isNullPtrType()) return true;
1655
1656 if (E->getType()->isAnyPointerType() &&
1657 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1658 Expr::NPC_ValueDependentIsNull))
1659 return true;
1660
1661 // Unfortunately, __null has type 'int'.
1662 if (isa<GNUNullExpr>(E)) return true;
1663
1664 return false;
1665}
1666
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001667/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1668ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1669 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1670 I = ObjCImpls.find(D);
1671 if (I != ObjCImpls.end())
1672 return cast<ObjCImplementationDecl>(I->second);
1673 return 0;
1674}
1675/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1676ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1677 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1678 I = ObjCImpls.find(D);
1679 if (I != ObjCImpls.end())
1680 return cast<ObjCCategoryImplDecl>(I->second);
1681 return 0;
1682}
1683
1684/// \brief Set the implementation of ObjCInterfaceDecl.
1685void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1686 ObjCImplementationDecl *ImplD) {
1687 assert(IFaceD && ImplD && "Passed null params");
1688 ObjCImpls[IFaceD] = ImplD;
1689}
1690/// \brief Set the implementation of ObjCCategoryDecl.
1691void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1692 ObjCCategoryImplDecl *ImplD) {
1693 assert(CatD && ImplD && "Passed null params");
1694 ObjCImpls[CatD] = ImplD;
1695}
1696
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001697ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1698 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1699 return ID;
1700 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1701 return CD->getClassInterface();
1702 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1703 return IMD->getClassInterface();
1704
1705 return 0;
1706}
1707
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001708/// \brief Get the copy initialization expression of VarDecl,or NULL if
1709/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001710Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001711 assert(VD && "Passed null params");
1712 assert(VD->hasAttr<BlocksAttr>() &&
1713 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001714 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001715 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001716 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1717}
1718
1719/// \brief Set the copy inialization expression of a block var decl.
1720void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1721 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001722 assert(VD->hasAttr<BlocksAttr>() &&
1723 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001724 BlockVarCopyInits[VD] = Init;
1725}
1726
John McCalla93c9342009-12-07 02:54:59 +00001727TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001728 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001729 if (!DataSize)
1730 DataSize = TypeLoc::getFullDataSizeForType(T);
1731 else
1732 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001733 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001734
John McCalla93c9342009-12-07 02:54:59 +00001735 TypeSourceInfo *TInfo =
1736 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1737 new (TInfo) TypeSourceInfo(T);
1738 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001739}
1740
John McCalla93c9342009-12-07 02:54:59 +00001741TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001742 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001743 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001744 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001745 return DI;
1746}
1747
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001748const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001749ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001750 return getObjCLayout(D, 0);
1751}
1752
1753const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001754ASTContext::getASTObjCImplementationLayout(
1755 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001756 return getObjCLayout(D->getClassInterface(), D);
1757}
1758
Chris Lattnera7674d82007-07-13 22:13:22 +00001759//===----------------------------------------------------------------------===//
1760// Type creation/memoization methods
1761//===----------------------------------------------------------------------===//
1762
Jay Foad4ba2a172011-01-12 09:06:06 +00001763QualType
John McCall3b657512011-01-19 10:06:00 +00001764ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1765 unsigned fastQuals = quals.getFastQualifiers();
1766 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001767
1768 // Check if we've already instantiated this type.
1769 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001770 ExtQuals::Profile(ID, baseType, quals);
1771 void *insertPos = 0;
1772 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1773 assert(eq->getQualifiers() == quals);
1774 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001775 }
1776
John McCall3b657512011-01-19 10:06:00 +00001777 // If the base type is not canonical, make the appropriate canonical type.
1778 QualType canon;
1779 if (!baseType->isCanonicalUnqualified()) {
1780 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001781 canonSplit.Quals.addConsistentQualifiers(quals);
1782 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001783
1784 // Re-find the insert position.
1785 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1786 }
1787
1788 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1789 ExtQualNodes.InsertNode(eq, insertPos);
1790 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001791}
1792
Jay Foad4ba2a172011-01-12 09:06:06 +00001793QualType
1794ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001795 QualType CanT = getCanonicalType(T);
1796 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001797 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001798
John McCall0953e762009-09-24 19:53:00 +00001799 // If we are composing extended qualifiers together, merge together
1800 // into one ExtQuals node.
1801 QualifierCollector Quals;
1802 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001803
John McCall0953e762009-09-24 19:53:00 +00001804 // If this type already has an address space specified, it cannot get
1805 // another one.
1806 assert(!Quals.hasAddressSpace() &&
1807 "Type cannot be in multiple addr spaces!");
1808 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001809
John McCall0953e762009-09-24 19:53:00 +00001810 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001811}
1812
Chris Lattnerb7d25532009-02-18 22:53:11 +00001813QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001814 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001815 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001816 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001817 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001818
John McCall7f040a92010-12-24 02:08:15 +00001819 if (const PointerType *ptr = T->getAs<PointerType>()) {
1820 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001821 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001822 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1823 return getPointerType(ResultType);
1824 }
1825 }
Mike Stump1eb44332009-09-09 15:08:12 +00001826
John McCall0953e762009-09-24 19:53:00 +00001827 // If we are composing extended qualifiers together, merge together
1828 // into one ExtQuals node.
1829 QualifierCollector Quals;
1830 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001831
John McCall0953e762009-09-24 19:53:00 +00001832 // If this type already has an ObjCGC specified, it cannot get
1833 // another one.
1834 assert(!Quals.hasObjCGCAttr() &&
1835 "Type cannot have multiple ObjCGCs!");
1836 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001837
John McCall0953e762009-09-24 19:53:00 +00001838 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001839}
Chris Lattnera7674d82007-07-13 22:13:22 +00001840
John McCalle6a365d2010-12-19 02:44:49 +00001841const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1842 FunctionType::ExtInfo Info) {
1843 if (T->getExtInfo() == Info)
1844 return T;
1845
1846 QualType Result;
1847 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1848 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1849 } else {
1850 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1851 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1852 EPI.ExtInfo = Info;
1853 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1854 FPT->getNumArgs(), EPI);
1855 }
1856
1857 return cast<FunctionType>(Result.getTypePtr());
1858}
1859
Reid Spencer5f016e22007-07-11 17:01:13 +00001860/// getComplexType - Return the uniqued reference to the type for a complex
1861/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001862QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001863 // Unique pointers, to guarantee there is only one pointer of a particular
1864 // structure.
1865 llvm::FoldingSetNodeID ID;
1866 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 void *InsertPos = 0;
1869 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1870 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Reid Spencer5f016e22007-07-11 17:01:13 +00001872 // If the pointee type isn't canonical, this won't be a canonical type either,
1873 // so fill in the canonical type field.
1874 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001875 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001876 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Reid Spencer5f016e22007-07-11 17:01:13 +00001878 // Get the new insert position for the node we care about.
1879 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001880 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001881 }
John McCall6b304a02009-09-24 23:30:46 +00001882 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001883 Types.push_back(New);
1884 ComplexTypes.InsertNode(New, InsertPos);
1885 return QualType(New, 0);
1886}
1887
Reid Spencer5f016e22007-07-11 17:01:13 +00001888/// getPointerType - Return the uniqued reference to the type for a pointer to
1889/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001890QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001891 // Unique pointers, to guarantee there is only one pointer of a particular
1892 // structure.
1893 llvm::FoldingSetNodeID ID;
1894 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Reid Spencer5f016e22007-07-11 17:01:13 +00001896 void *InsertPos = 0;
1897 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1898 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Reid Spencer5f016e22007-07-11 17:01:13 +00001900 // If the pointee type isn't canonical, this won't be a canonical type either,
1901 // so fill in the canonical type field.
1902 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001903 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001904 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Reid Spencer5f016e22007-07-11 17:01:13 +00001906 // Get the new insert position for the node we care about.
1907 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001908 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 }
John McCall6b304a02009-09-24 23:30:46 +00001910 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001911 Types.push_back(New);
1912 PointerTypes.InsertNode(New, InsertPos);
1913 return QualType(New, 0);
1914}
1915
Mike Stump1eb44332009-09-09 15:08:12 +00001916/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001917/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001918QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001919 assert(T->isFunctionType() && "block of function types only");
1920 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001921 // structure.
1922 llvm::FoldingSetNodeID ID;
1923 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001924
Steve Naroff5618bd42008-08-27 16:04:49 +00001925 void *InsertPos = 0;
1926 if (BlockPointerType *PT =
1927 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1928 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001929
1930 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001931 // type either so fill in the canonical type field.
1932 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001933 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001934 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Steve Naroff5618bd42008-08-27 16:04:49 +00001936 // Get the new insert position for the node we care about.
1937 BlockPointerType *NewIP =
1938 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001939 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001940 }
John McCall6b304a02009-09-24 23:30:46 +00001941 BlockPointerType *New
1942 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001943 Types.push_back(New);
1944 BlockPointerTypes.InsertNode(New, InsertPos);
1945 return QualType(New, 0);
1946}
1947
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001948/// getLValueReferenceType - Return the uniqued reference to the type for an
1949/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001950QualType
1951ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001952 assert(getCanonicalType(T) != OverloadTy &&
1953 "Unresolved overloaded function type");
1954
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 // Unique pointers, to guarantee there is only one pointer of a particular
1956 // structure.
1957 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001958 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001959
1960 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001961 if (LValueReferenceType *RT =
1962 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001963 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001964
John McCall54e14c42009-10-22 22:37:11 +00001965 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1966
Reid Spencer5f016e22007-07-11 17:01:13 +00001967 // If the referencee type isn't canonical, this won't be a canonical type
1968 // either, so fill in the canonical type field.
1969 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001970 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1971 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1972 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001973
Reid Spencer5f016e22007-07-11 17:01:13 +00001974 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001975 LValueReferenceType *NewIP =
1976 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001977 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 }
1979
John McCall6b304a02009-09-24 23:30:46 +00001980 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001981 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1982 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001984 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001985
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001986 return QualType(New, 0);
1987}
1988
1989/// getRValueReferenceType - Return the uniqued reference to the type for an
1990/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001991QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001992 // Unique pointers, to guarantee there is only one pointer of a particular
1993 // structure.
1994 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001995 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001996
1997 void *InsertPos = 0;
1998 if (RValueReferenceType *RT =
1999 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2000 return QualType(RT, 0);
2001
John McCall54e14c42009-10-22 22:37:11 +00002002 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2003
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002004 // If the referencee type isn't canonical, this won't be a canonical type
2005 // either, so fill in the canonical type field.
2006 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002007 if (InnerRef || !T.isCanonical()) {
2008 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2009 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002010
2011 // Get the new insert position for the node we care about.
2012 RValueReferenceType *NewIP =
2013 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002014 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002015 }
2016
John McCall6b304a02009-09-24 23:30:46 +00002017 RValueReferenceType *New
2018 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002019 Types.push_back(New);
2020 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 return QualType(New, 0);
2022}
2023
Sebastian Redlf30208a2009-01-24 21:16:55 +00002024/// getMemberPointerType - Return the uniqued reference to the type for a
2025/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002026QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002027 // Unique pointers, to guarantee there is only one pointer of a particular
2028 // structure.
2029 llvm::FoldingSetNodeID ID;
2030 MemberPointerType::Profile(ID, T, Cls);
2031
2032 void *InsertPos = 0;
2033 if (MemberPointerType *PT =
2034 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2035 return QualType(PT, 0);
2036
2037 // If the pointee or class type isn't canonical, this won't be a canonical
2038 // type either, so fill in the canonical type field.
2039 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002040 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002041 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2042
2043 // Get the new insert position for the node we care about.
2044 MemberPointerType *NewIP =
2045 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002046 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002047 }
John McCall6b304a02009-09-24 23:30:46 +00002048 MemberPointerType *New
2049 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002050 Types.push_back(New);
2051 MemberPointerTypes.InsertNode(New, InsertPos);
2052 return QualType(New, 0);
2053}
2054
Mike Stump1eb44332009-09-09 15:08:12 +00002055/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002056/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002057QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002058 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002059 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002060 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002061 assert((EltTy->isDependentType() ||
2062 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002063 "Constant array of VLAs is illegal!");
2064
Chris Lattner38aeec72009-05-13 04:12:56 +00002065 // Convert the array size into a canonical width matching the pointer size for
2066 // the target.
2067 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002068 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002069 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002070
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002072 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Reid Spencer5f016e22007-07-11 17:01:13 +00002074 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002075 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002076 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002077 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002078
John McCall3b657512011-01-19 10:06:00 +00002079 // If the element type isn't canonical or has qualifiers, this won't
2080 // be a canonical type either, so fill in the canonical type field.
2081 QualType Canon;
2082 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2083 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002084 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002085 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002086 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002087
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002089 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002090 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002091 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 }
Mike Stump1eb44332009-09-09 15:08:12 +00002093
John McCall6b304a02009-09-24 23:30:46 +00002094 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002095 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002096 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002097 Types.push_back(New);
2098 return QualType(New, 0);
2099}
2100
John McCallce889032011-01-18 08:40:38 +00002101/// getVariableArrayDecayedType - Turns the given type, which may be
2102/// variably-modified, into the corresponding type with all the known
2103/// sizes replaced with [*].
2104QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2105 // Vastly most common case.
2106 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002107
John McCallce889032011-01-18 08:40:38 +00002108 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002109
John McCallce889032011-01-18 08:40:38 +00002110 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002111 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002112 switch (ty->getTypeClass()) {
2113#define TYPE(Class, Base)
2114#define ABSTRACT_TYPE(Class, Base)
2115#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2116#include "clang/AST/TypeNodes.def"
2117 llvm_unreachable("didn't desugar past all non-canonical types?");
2118
2119 // These types should never be variably-modified.
2120 case Type::Builtin:
2121 case Type::Complex:
2122 case Type::Vector:
2123 case Type::ExtVector:
2124 case Type::DependentSizedExtVector:
2125 case Type::ObjCObject:
2126 case Type::ObjCInterface:
2127 case Type::ObjCObjectPointer:
2128 case Type::Record:
2129 case Type::Enum:
2130 case Type::UnresolvedUsing:
2131 case Type::TypeOfExpr:
2132 case Type::TypeOf:
2133 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002134 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002135 case Type::DependentName:
2136 case Type::InjectedClassName:
2137 case Type::TemplateSpecialization:
2138 case Type::DependentTemplateSpecialization:
2139 case Type::TemplateTypeParm:
2140 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002141 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002142 case Type::PackExpansion:
2143 llvm_unreachable("type should never be variably-modified");
2144
2145 // These types can be variably-modified but should never need to
2146 // further decay.
2147 case Type::FunctionNoProto:
2148 case Type::FunctionProto:
2149 case Type::BlockPointer:
2150 case Type::MemberPointer:
2151 return type;
2152
2153 // These types can be variably-modified. All these modifications
2154 // preserve structure except as noted by comments.
2155 // TODO: if we ever care about optimizing VLAs, there are no-op
2156 // optimizations available here.
2157 case Type::Pointer:
2158 result = getPointerType(getVariableArrayDecayedType(
2159 cast<PointerType>(ty)->getPointeeType()));
2160 break;
2161
2162 case Type::LValueReference: {
2163 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2164 result = getLValueReferenceType(
2165 getVariableArrayDecayedType(lv->getPointeeType()),
2166 lv->isSpelledAsLValue());
2167 break;
2168 }
2169
2170 case Type::RValueReference: {
2171 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2172 result = getRValueReferenceType(
2173 getVariableArrayDecayedType(lv->getPointeeType()));
2174 break;
2175 }
2176
Eli Friedmanb001de72011-10-06 23:00:33 +00002177 case Type::Atomic: {
2178 const AtomicType *at = cast<AtomicType>(ty);
2179 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2180 break;
2181 }
2182
John McCallce889032011-01-18 08:40:38 +00002183 case Type::ConstantArray: {
2184 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2185 result = getConstantArrayType(
2186 getVariableArrayDecayedType(cat->getElementType()),
2187 cat->getSize(),
2188 cat->getSizeModifier(),
2189 cat->getIndexTypeCVRQualifiers());
2190 break;
2191 }
2192
2193 case Type::DependentSizedArray: {
2194 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2195 result = getDependentSizedArrayType(
2196 getVariableArrayDecayedType(dat->getElementType()),
2197 dat->getSizeExpr(),
2198 dat->getSizeModifier(),
2199 dat->getIndexTypeCVRQualifiers(),
2200 dat->getBracketsRange());
2201 break;
2202 }
2203
2204 // Turn incomplete types into [*] types.
2205 case Type::IncompleteArray: {
2206 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2207 result = getVariableArrayType(
2208 getVariableArrayDecayedType(iat->getElementType()),
2209 /*size*/ 0,
2210 ArrayType::Normal,
2211 iat->getIndexTypeCVRQualifiers(),
2212 SourceRange());
2213 break;
2214 }
2215
2216 // Turn VLA types into [*] types.
2217 case Type::VariableArray: {
2218 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2219 result = getVariableArrayType(
2220 getVariableArrayDecayedType(vat->getElementType()),
2221 /*size*/ 0,
2222 ArrayType::Star,
2223 vat->getIndexTypeCVRQualifiers(),
2224 vat->getBracketsRange());
2225 break;
2226 }
2227 }
2228
2229 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002230 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002231}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002232
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002233/// getVariableArrayType - Returns a non-unique reference to the type for a
2234/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002235QualType ASTContext::getVariableArrayType(QualType EltTy,
2236 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002237 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002238 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002239 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002240 // Since we don't unique expressions, it isn't possible to unique VLA's
2241 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002242 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002243
John McCall3b657512011-01-19 10:06:00 +00002244 // Be sure to pull qualifiers off the element type.
2245 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2246 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002247 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002248 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002249 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002250 }
2251
John McCall6b304a02009-09-24 23:30:46 +00002252 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002253 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002254
2255 VariableArrayTypes.push_back(New);
2256 Types.push_back(New);
2257 return QualType(New, 0);
2258}
2259
Douglas Gregor898574e2008-12-05 23:32:09 +00002260/// getDependentSizedArrayType - Returns a non-unique reference to
2261/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002262/// type.
John McCall3b657512011-01-19 10:06:00 +00002263QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2264 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002265 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002266 unsigned elementTypeQuals,
2267 SourceRange brackets) const {
2268 assert((!numElements || numElements->isTypeDependent() ||
2269 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002270 "Size must be type- or value-dependent!");
2271
John McCall3b657512011-01-19 10:06:00 +00002272 // Dependently-sized array types that do not have a specified number
2273 // of elements will have their sizes deduced from a dependent
2274 // initializer. We do no canonicalization here at all, which is okay
2275 // because they can't be used in most locations.
2276 if (!numElements) {
2277 DependentSizedArrayType *newType
2278 = new (*this, TypeAlignment)
2279 DependentSizedArrayType(*this, elementType, QualType(),
2280 numElements, ASM, elementTypeQuals,
2281 brackets);
2282 Types.push_back(newType);
2283 return QualType(newType, 0);
2284 }
2285
2286 // Otherwise, we actually build a new type every time, but we
2287 // also build a canonical type.
2288
2289 SplitQualType canonElementType = getCanonicalType(elementType).split();
2290
2291 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002292 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002293 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002294 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002295 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002296
John McCall3b657512011-01-19 10:06:00 +00002297 // Look for an existing type with these properties.
2298 DependentSizedArrayType *canonTy =
2299 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002300
John McCall3b657512011-01-19 10:06:00 +00002301 // If we don't have one, build one.
2302 if (!canonTy) {
2303 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002304 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002305 QualType(), numElements, ASM, elementTypeQuals,
2306 brackets);
2307 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2308 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002309 }
2310
John McCall3b657512011-01-19 10:06:00 +00002311 // Apply qualifiers from the element type to the array.
2312 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002313 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002314
John McCall3b657512011-01-19 10:06:00 +00002315 // If we didn't need extra canonicalization for the element type,
2316 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002317 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002318 return canon;
2319
2320 // Otherwise, we need to build a type which follows the spelling
2321 // of the element type.
2322 DependentSizedArrayType *sugaredType
2323 = new (*this, TypeAlignment)
2324 DependentSizedArrayType(*this, elementType, canon, numElements,
2325 ASM, elementTypeQuals, brackets);
2326 Types.push_back(sugaredType);
2327 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002328}
2329
John McCall3b657512011-01-19 10:06:00 +00002330QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002331 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002332 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002333 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002334 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002335
John McCall3b657512011-01-19 10:06:00 +00002336 void *insertPos = 0;
2337 if (IncompleteArrayType *iat =
2338 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2339 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002340
2341 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002342 // either, so fill in the canonical type field. We also have to pull
2343 // qualifiers off the element type.
2344 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002345
John McCall3b657512011-01-19 10:06:00 +00002346 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2347 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002348 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002349 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002350 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002351
2352 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002353 IncompleteArrayType *existing =
2354 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2355 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002356 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002357
John McCall3b657512011-01-19 10:06:00 +00002358 IncompleteArrayType *newType = new (*this, TypeAlignment)
2359 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002360
John McCall3b657512011-01-19 10:06:00 +00002361 IncompleteArrayTypes.InsertNode(newType, insertPos);
2362 Types.push_back(newType);
2363 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002364}
2365
Steve Naroff73322922007-07-18 18:00:27 +00002366/// getVectorType - Return the unique reference to a vector type of
2367/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002368QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002369 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002370 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002371
Reid Spencer5f016e22007-07-11 17:01:13 +00002372 // Check if we've already instantiated a vector of this type.
2373 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002374 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002375
Reid Spencer5f016e22007-07-11 17:01:13 +00002376 void *InsertPos = 0;
2377 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2378 return QualType(VTP, 0);
2379
2380 // If the element type isn't canonical, this won't be a canonical type either,
2381 // so fill in the canonical type field.
2382 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002383 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002384 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002385
Reid Spencer5f016e22007-07-11 17:01:13 +00002386 // Get the new insert position for the node we care about.
2387 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002388 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002389 }
John McCall6b304a02009-09-24 23:30:46 +00002390 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002391 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002392 VectorTypes.InsertNode(New, InsertPos);
2393 Types.push_back(New);
2394 return QualType(New, 0);
2395}
2396
Nate Begeman213541a2008-04-18 23:10:10 +00002397/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002398/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002399QualType
2400ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002401 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002402
Steve Naroff73322922007-07-18 18:00:27 +00002403 // Check if we've already instantiated a vector of this type.
2404 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002405 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002406 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002407 void *InsertPos = 0;
2408 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2409 return QualType(VTP, 0);
2410
2411 // If the element type isn't canonical, this won't be a canonical type either,
2412 // so fill in the canonical type field.
2413 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002414 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002415 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002416
Steve Naroff73322922007-07-18 18:00:27 +00002417 // Get the new insert position for the node we care about.
2418 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002419 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002420 }
John McCall6b304a02009-09-24 23:30:46 +00002421 ExtVectorType *New = new (*this, TypeAlignment)
2422 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002423 VectorTypes.InsertNode(New, InsertPos);
2424 Types.push_back(New);
2425 return QualType(New, 0);
2426}
2427
Jay Foad4ba2a172011-01-12 09:06:06 +00002428QualType
2429ASTContext::getDependentSizedExtVectorType(QualType vecType,
2430 Expr *SizeExpr,
2431 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002432 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002433 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002434 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002435
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002436 void *InsertPos = 0;
2437 DependentSizedExtVectorType *Canon
2438 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2439 DependentSizedExtVectorType *New;
2440 if (Canon) {
2441 // We already have a canonical version of this array type; use it as
2442 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002443 New = new (*this, TypeAlignment)
2444 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2445 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002446 } else {
2447 QualType CanonVecTy = getCanonicalType(vecType);
2448 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002449 New = new (*this, TypeAlignment)
2450 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2451 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002452
2453 DependentSizedExtVectorType *CanonCheck
2454 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2455 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2456 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002457 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2458 } else {
2459 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2460 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002461 New = new (*this, TypeAlignment)
2462 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002463 }
2464 }
Mike Stump1eb44332009-09-09 15:08:12 +00002465
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002466 Types.push_back(New);
2467 return QualType(New, 0);
2468}
2469
Douglas Gregor72564e72009-02-26 23:50:07 +00002470/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002471///
Jay Foad4ba2a172011-01-12 09:06:06 +00002472QualType
2473ASTContext::getFunctionNoProtoType(QualType ResultTy,
2474 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002475 const CallingConv DefaultCC = Info.getCC();
2476 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2477 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002478 // Unique functions, to guarantee there is only one function of a particular
2479 // structure.
2480 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002481 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002482
Reid Spencer5f016e22007-07-11 17:01:13 +00002483 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002484 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002485 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002486 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002487
Reid Spencer5f016e22007-07-11 17:01:13 +00002488 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002489 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002490 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002491 Canonical =
2492 getFunctionNoProtoType(getCanonicalType(ResultTy),
2493 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002494
Reid Spencer5f016e22007-07-11 17:01:13 +00002495 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002496 FunctionNoProtoType *NewIP =
2497 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002498 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002499 }
Mike Stump1eb44332009-09-09 15:08:12 +00002500
Roman Divackycfe9af22011-03-01 17:40:53 +00002501 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002502 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002503 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002504 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002505 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002506 return QualType(New, 0);
2507}
2508
2509/// getFunctionType - Return a normal function type with a typed argument
2510/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002511QualType
2512ASTContext::getFunctionType(QualType ResultTy,
2513 const QualType *ArgArray, unsigned NumArgs,
2514 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002515 // Unique functions, to guarantee there is only one function of a particular
2516 // structure.
2517 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002518 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002519
2520 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002521 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002522 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002523 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002524
2525 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002526 bool isCanonical =
2527 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2528 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002529 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002530 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002531 isCanonical = false;
2532
Roman Divackycfe9af22011-03-01 17:40:53 +00002533 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2534 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2535 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002536
Reid Spencer5f016e22007-07-11 17:01:13 +00002537 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002538 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002539 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002540 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002541 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002542 CanonicalArgs.reserve(NumArgs);
2543 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002544 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002545
John McCalle23cf432010-12-14 08:05:40 +00002546 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002547 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002548 CanonicalEPI.ExceptionSpecType = EST_None;
2549 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002550 CanonicalEPI.ExtInfo
2551 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2552
Chris Lattnerf52ab252008-04-06 22:59:24 +00002553 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002554 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002555 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002556
Reid Spencer5f016e22007-07-11 17:01:13 +00002557 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002558 FunctionProtoType *NewIP =
2559 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002560 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002561 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002562
John McCallf85e1932011-06-15 23:02:42 +00002563 // FunctionProtoType objects are allocated with extra bytes after
2564 // them for three variable size arrays at the end:
2565 // - parameter types
2566 // - exception types
2567 // - consumed-arguments flags
2568 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002569 // expression, or information used to resolve the exception
2570 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002571 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002572 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002573 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002574 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002575 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002576 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002577 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002578 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002579 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2580 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002581 }
John McCallf85e1932011-06-15 23:02:42 +00002582 if (EPI.ConsumedArguments)
2583 Size += NumArgs * sizeof(bool);
2584
John McCalle23cf432010-12-14 08:05:40 +00002585 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002586 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2587 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002588 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002589 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002590 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002591 return QualType(FTP, 0);
2592}
2593
John McCall3cb0ebd2010-03-10 03:28:59 +00002594#ifndef NDEBUG
2595static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2596 if (!isa<CXXRecordDecl>(D)) return false;
2597 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2598 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2599 return true;
2600 if (RD->getDescribedClassTemplate() &&
2601 !isa<ClassTemplateSpecializationDecl>(RD))
2602 return true;
2603 return false;
2604}
2605#endif
2606
2607/// getInjectedClassNameType - Return the unique reference to the
2608/// injected class name type for the specified templated declaration.
2609QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002610 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002611 assert(NeedsInjectedClassNameType(Decl));
2612 if (Decl->TypeForDecl) {
2613 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002614 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002615 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2616 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2617 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2618 } else {
John McCallf4c73712011-01-19 06:33:43 +00002619 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002620 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002621 Decl->TypeForDecl = newType;
2622 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002623 }
2624 return QualType(Decl->TypeForDecl, 0);
2625}
2626
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002627/// getTypeDeclType - Return the unique reference to the type for the
2628/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002629QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002630 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002631 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002632
Richard Smith162e1c12011-04-15 14:24:37 +00002633 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002634 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002635
John McCallbecb8d52010-03-10 06:48:02 +00002636 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2637 "Template type parameter types are always available.");
2638
John McCall19c85762010-02-16 03:57:14 +00002639 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002640 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002641 "struct/union has previous declaration");
2642 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002643 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002644 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002645 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002646 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002647 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002648 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002649 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002650 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2651 Decl->TypeForDecl = newType;
2652 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002653 } else
John McCallbecb8d52010-03-10 06:48:02 +00002654 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002655
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002656 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002657}
2658
Reid Spencer5f016e22007-07-11 17:01:13 +00002659/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002660/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002661QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002662ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2663 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002664 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002665
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002666 if (Canonical.isNull())
2667 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002668 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002669 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002670 Decl->TypeForDecl = newType;
2671 Types.push_back(newType);
2672 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002673}
2674
Jay Foad4ba2a172011-01-12 09:06:06 +00002675QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002676 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2677
Douglas Gregoref96ee02012-01-14 16:38:05 +00002678 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002679 if (PrevDecl->TypeForDecl)
2680 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2681
John McCallf4c73712011-01-19 06:33:43 +00002682 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2683 Decl->TypeForDecl = newType;
2684 Types.push_back(newType);
2685 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002686}
2687
Jay Foad4ba2a172011-01-12 09:06:06 +00002688QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002689 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2690
Douglas Gregoref96ee02012-01-14 16:38:05 +00002691 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002692 if (PrevDecl->TypeForDecl)
2693 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2694
John McCallf4c73712011-01-19 06:33:43 +00002695 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2696 Decl->TypeForDecl = newType;
2697 Types.push_back(newType);
2698 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002699}
2700
John McCall9d156a72011-01-06 01:58:22 +00002701QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2702 QualType modifiedType,
2703 QualType equivalentType) {
2704 llvm::FoldingSetNodeID id;
2705 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2706
2707 void *insertPos = 0;
2708 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2709 if (type) return QualType(type, 0);
2710
2711 QualType canon = getCanonicalType(equivalentType);
2712 type = new (*this, TypeAlignment)
2713 AttributedType(canon, attrKind, modifiedType, equivalentType);
2714
2715 Types.push_back(type);
2716 AttributedTypes.InsertNode(type, insertPos);
2717
2718 return QualType(type, 0);
2719}
2720
2721
John McCall49a832b2009-10-18 09:09:24 +00002722/// \brief Retrieve a substitution-result type.
2723QualType
2724ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002725 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002726 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002727 && "replacement types must always be canonical");
2728
2729 llvm::FoldingSetNodeID ID;
2730 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2731 void *InsertPos = 0;
2732 SubstTemplateTypeParmType *SubstParm
2733 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2734
2735 if (!SubstParm) {
2736 SubstParm = new (*this, TypeAlignment)
2737 SubstTemplateTypeParmType(Parm, Replacement);
2738 Types.push_back(SubstParm);
2739 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2740 }
2741
2742 return QualType(SubstParm, 0);
2743}
2744
Douglas Gregorc3069d62011-01-14 02:55:32 +00002745/// \brief Retrieve a
2746QualType ASTContext::getSubstTemplateTypeParmPackType(
2747 const TemplateTypeParmType *Parm,
2748 const TemplateArgument &ArgPack) {
2749#ifndef NDEBUG
2750 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2751 PEnd = ArgPack.pack_end();
2752 P != PEnd; ++P) {
2753 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2754 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2755 }
2756#endif
2757
2758 llvm::FoldingSetNodeID ID;
2759 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2760 void *InsertPos = 0;
2761 if (SubstTemplateTypeParmPackType *SubstParm
2762 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2763 return QualType(SubstParm, 0);
2764
2765 QualType Canon;
2766 if (!Parm->isCanonicalUnqualified()) {
2767 Canon = getCanonicalType(QualType(Parm, 0));
2768 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2769 ArgPack);
2770 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2771 }
2772
2773 SubstTemplateTypeParmPackType *SubstParm
2774 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2775 ArgPack);
2776 Types.push_back(SubstParm);
2777 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2778 return QualType(SubstParm, 0);
2779}
2780
Douglas Gregorfab9d672009-02-05 23:33:38 +00002781/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002782/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002783/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002784QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002785 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002786 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002787 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002788 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002789 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002790 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002791 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2792
2793 if (TypeParm)
2794 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002796 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002797 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002798 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002799
2800 TemplateTypeParmType *TypeCheck
2801 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2802 assert(!TypeCheck && "Template type parameter canonical type broken");
2803 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002804 } else
John McCall6b304a02009-09-24 23:30:46 +00002805 TypeParm = new (*this, TypeAlignment)
2806 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002807
2808 Types.push_back(TypeParm);
2809 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2810
2811 return QualType(TypeParm, 0);
2812}
2813
John McCall3cb0ebd2010-03-10 03:28:59 +00002814TypeSourceInfo *
2815ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2816 SourceLocation NameLoc,
2817 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002818 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002819 assert(!Name.getAsDependentTemplateName() &&
2820 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002821 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002822
2823 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2824 TemplateSpecializationTypeLoc TL
2825 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002826 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002827 TL.setTemplateNameLoc(NameLoc);
2828 TL.setLAngleLoc(Args.getLAngleLoc());
2829 TL.setRAngleLoc(Args.getRAngleLoc());
2830 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2831 TL.setArgLocInfo(i, Args[i].getLocInfo());
2832 return DI;
2833}
2834
Mike Stump1eb44332009-09-09 15:08:12 +00002835QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002836ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002837 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002838 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002839 assert(!Template.getAsDependentTemplateName() &&
2840 "No dependent template names here!");
2841
John McCalld5532b62009-11-23 01:53:49 +00002842 unsigned NumArgs = Args.size();
2843
Chris Lattner5f9e2722011-07-23 10:55:15 +00002844 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002845 ArgVec.reserve(NumArgs);
2846 for (unsigned i = 0; i != NumArgs; ++i)
2847 ArgVec.push_back(Args[i].getArgument());
2848
John McCall31f17ec2010-04-27 00:57:59 +00002849 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002850 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002851}
2852
Douglas Gregorb70126a2012-02-03 17:16:23 +00002853#ifndef NDEBUG
2854static bool hasAnyPackExpansions(const TemplateArgument *Args,
2855 unsigned NumArgs) {
2856 for (unsigned I = 0; I != NumArgs; ++I)
2857 if (Args[I].isPackExpansion())
2858 return true;
2859
2860 return true;
2861}
2862#endif
2863
John McCall833ca992009-10-29 08:12:44 +00002864QualType
2865ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002866 const TemplateArgument *Args,
2867 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002868 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002869 assert(!Template.getAsDependentTemplateName() &&
2870 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002871 // Look through qualified template names.
2872 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2873 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002874
Douglas Gregorb70126a2012-02-03 17:16:23 +00002875 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002876 Template.getAsTemplateDecl() &&
2877 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002878 QualType CanonType;
2879 if (!Underlying.isNull())
2880 CanonType = getCanonicalType(Underlying);
2881 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002882 // We can get here with an alias template when the specialization contains
2883 // a pack expansion that does not match up with a parameter pack.
2884 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2885 "Caller must compute aliased type");
2886 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00002887 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2888 NumArgs);
2889 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002890
Douglas Gregor1275ae02009-07-28 23:00:59 +00002891 // Allocate the (non-canonical) template specialization type, but don't
2892 // try to unique it: these types typically have location information that
2893 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002894 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2895 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00002896 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002897 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002898 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00002899 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2900 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002901
Douglas Gregor55f6b142009-02-09 18:46:07 +00002902 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002903 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002904}
2905
Mike Stump1eb44332009-09-09 15:08:12 +00002906QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002907ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2908 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002909 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002910 assert(!Template.getAsDependentTemplateName() &&
2911 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002912
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002913 // Look through qualified template names.
2914 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2915 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002916
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002917 // Build the canonical template specialization type.
2918 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002919 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002920 CanonArgs.reserve(NumArgs);
2921 for (unsigned I = 0; I != NumArgs; ++I)
2922 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2923
2924 // Determine whether this canonical template specialization type already
2925 // exists.
2926 llvm::FoldingSetNodeID ID;
2927 TemplateSpecializationType::Profile(ID, CanonTemplate,
2928 CanonArgs.data(), NumArgs, *this);
2929
2930 void *InsertPos = 0;
2931 TemplateSpecializationType *Spec
2932 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2933
2934 if (!Spec) {
2935 // Allocate a new canonical template specialization type.
2936 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2937 sizeof(TemplateArgument) * NumArgs),
2938 TypeAlignment);
2939 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2940 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002941 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002942 Types.push_back(Spec);
2943 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2944 }
2945
2946 assert(Spec->isDependentType() &&
2947 "Non-dependent template-id type must have a canonical type");
2948 return QualType(Spec, 0);
2949}
2950
2951QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002952ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2953 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002954 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002955 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002956 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002957
2958 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002959 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002960 if (T)
2961 return QualType(T, 0);
2962
Douglas Gregor789b1f62010-02-04 18:10:26 +00002963 QualType Canon = NamedType;
2964 if (!Canon.isCanonical()) {
2965 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002966 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2967 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002968 (void)CheckT;
2969 }
2970
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002971 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002972 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002973 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002974 return QualType(T, 0);
2975}
2976
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002977QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002978ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002979 llvm::FoldingSetNodeID ID;
2980 ParenType::Profile(ID, InnerType);
2981
2982 void *InsertPos = 0;
2983 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2984 if (T)
2985 return QualType(T, 0);
2986
2987 QualType Canon = InnerType;
2988 if (!Canon.isCanonical()) {
2989 Canon = getCanonicalType(InnerType);
2990 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2991 assert(!CheckT && "Paren canonical type broken");
2992 (void)CheckT;
2993 }
2994
2995 T = new (*this) ParenType(InnerType, Canon);
2996 Types.push_back(T);
2997 ParenTypes.InsertNode(T, InsertPos);
2998 return QualType(T, 0);
2999}
3000
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003001QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3002 NestedNameSpecifier *NNS,
3003 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003004 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003005 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3006
3007 if (Canon.isNull()) {
3008 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003009 ElaboratedTypeKeyword CanonKeyword = Keyword;
3010 if (Keyword == ETK_None)
3011 CanonKeyword = ETK_Typename;
3012
3013 if (CanonNNS != NNS || CanonKeyword != Keyword)
3014 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003015 }
3016
3017 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003018 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003019
3020 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003021 DependentNameType *T
3022 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003023 if (T)
3024 return QualType(T, 0);
3025
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003026 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003027 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003028 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003029 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003030}
3031
Mike Stump1eb44332009-09-09 15:08:12 +00003032QualType
John McCall33500952010-06-11 00:33:02 +00003033ASTContext::getDependentTemplateSpecializationType(
3034 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003035 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003036 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003037 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003038 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003039 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003040 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3041 ArgCopy.push_back(Args[I].getArgument());
3042 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3043 ArgCopy.size(),
3044 ArgCopy.data());
3045}
3046
3047QualType
3048ASTContext::getDependentTemplateSpecializationType(
3049 ElaboratedTypeKeyword Keyword,
3050 NestedNameSpecifier *NNS,
3051 const IdentifierInfo *Name,
3052 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003053 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003054 assert((!NNS || NNS->isDependent()) &&
3055 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003056
Douglas Gregor789b1f62010-02-04 18:10:26 +00003057 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003058 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3059 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003060
3061 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003062 DependentTemplateSpecializationType *T
3063 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003064 if (T)
3065 return QualType(T, 0);
3066
John McCall33500952010-06-11 00:33:02 +00003067 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003068
John McCall33500952010-06-11 00:33:02 +00003069 ElaboratedTypeKeyword CanonKeyword = Keyword;
3070 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3071
3072 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003073 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003074 for (unsigned I = 0; I != NumArgs; ++I) {
3075 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3076 if (!CanonArgs[I].structurallyEquals(Args[I]))
3077 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003078 }
3079
John McCall33500952010-06-11 00:33:02 +00003080 QualType Canon;
3081 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3082 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3083 Name, NumArgs,
3084 CanonArgs.data());
3085
3086 // Find the insert position again.
3087 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3088 }
3089
3090 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3091 sizeof(TemplateArgument) * NumArgs),
3092 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003093 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003094 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003095 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003096 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003097 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003098}
3099
Douglas Gregorcded4f62011-01-14 17:04:44 +00003100QualType ASTContext::getPackExpansionType(QualType Pattern,
3101 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003102 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003103 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003104
3105 assert(Pattern->containsUnexpandedParameterPack() &&
3106 "Pack expansions must expand one or more parameter packs");
3107 void *InsertPos = 0;
3108 PackExpansionType *T
3109 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3110 if (T)
3111 return QualType(T, 0);
3112
3113 QualType Canon;
3114 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003115 Canon = getCanonicalType(Pattern);
3116 // The canonical type might not contain an unexpanded parameter pack, if it
3117 // contains an alias template specialization which ignores one of its
3118 // parameters.
3119 if (Canon->containsUnexpandedParameterPack()) {
3120 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003121
Richard Smithd8672ef2012-07-16 00:20:35 +00003122 // Find the insert position again, in case we inserted an element into
3123 // PackExpansionTypes and invalidated our insert position.
3124 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3125 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003126 }
3127
Douglas Gregorcded4f62011-01-14 17:04:44 +00003128 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003129 Types.push_back(T);
3130 PackExpansionTypes.InsertNode(T, InsertPos);
3131 return QualType(T, 0);
3132}
3133
Chris Lattner88cb27a2008-04-07 04:56:42 +00003134/// CmpProtocolNames - Comparison predicate for sorting protocols
3135/// alphabetically.
3136static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3137 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003138 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003139}
3140
John McCallc12c5bb2010-05-15 11:32:37 +00003141static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003142 unsigned NumProtocols) {
3143 if (NumProtocols == 0) return true;
3144
Douglas Gregor61cc2962012-01-02 02:00:30 +00003145 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3146 return false;
3147
John McCall54e14c42009-10-22 22:37:11 +00003148 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003149 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3150 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003151 return false;
3152 return true;
3153}
3154
3155static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003156 unsigned &NumProtocols) {
3157 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003158
Chris Lattner88cb27a2008-04-07 04:56:42 +00003159 // Sort protocols, keyed by name.
3160 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3161
Douglas Gregor61cc2962012-01-02 02:00:30 +00003162 // Canonicalize.
3163 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3164 Protocols[I] = Protocols[I]->getCanonicalDecl();
3165
Chris Lattner88cb27a2008-04-07 04:56:42 +00003166 // Remove duplicates.
3167 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3168 NumProtocols = ProtocolsEnd-Protocols;
3169}
3170
John McCallc12c5bb2010-05-15 11:32:37 +00003171QualType ASTContext::getObjCObjectType(QualType BaseType,
3172 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003173 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003174 // If the base type is an interface and there aren't any protocols
3175 // to add, then the interface type will do just fine.
3176 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3177 return BaseType;
3178
3179 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003180 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003181 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003182 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003183 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3184 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003185
John McCallc12c5bb2010-05-15 11:32:37 +00003186 // Build the canonical type, which has the canonical base type and
3187 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003188 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003189 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3190 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3191 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003192 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003193 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003194 unsigned UniqueCount = NumProtocols;
3195
John McCall54e14c42009-10-22 22:37:11 +00003196 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003197 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3198 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003199 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003200 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3201 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003202 }
3203
3204 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003205 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3206 }
3207
3208 unsigned Size = sizeof(ObjCObjectTypeImpl);
3209 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3210 void *Mem = Allocate(Size, TypeAlignment);
3211 ObjCObjectTypeImpl *T =
3212 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3213
3214 Types.push_back(T);
3215 ObjCObjectTypes.InsertNode(T, InsertPos);
3216 return QualType(T, 0);
3217}
3218
3219/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3220/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003221QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003222 llvm::FoldingSetNodeID ID;
3223 ObjCObjectPointerType::Profile(ID, ObjectT);
3224
3225 void *InsertPos = 0;
3226 if (ObjCObjectPointerType *QT =
3227 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3228 return QualType(QT, 0);
3229
3230 // Find the canonical object type.
3231 QualType Canonical;
3232 if (!ObjectT.isCanonical()) {
3233 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3234
3235 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003236 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3237 }
3238
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003239 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003240 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3241 ObjCObjectPointerType *QType =
3242 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003243
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003244 Types.push_back(QType);
3245 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003246 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003247}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003248
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003249/// getObjCInterfaceType - Return the unique reference to the type for the
3250/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003251QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3252 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003253 if (Decl->TypeForDecl)
3254 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003255
Douglas Gregor0af55012011-12-16 03:12:41 +00003256 if (PrevDecl) {
3257 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3258 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3259 return QualType(PrevDecl->TypeForDecl, 0);
3260 }
3261
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003262 // Prefer the definition, if there is one.
3263 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3264 Decl = Def;
3265
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003266 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3267 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3268 Decl->TypeForDecl = T;
3269 Types.push_back(T);
3270 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003271}
3272
Douglas Gregor72564e72009-02-26 23:50:07 +00003273/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3274/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003275/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003276/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003277/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003278QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003279 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003280 if (tofExpr->isTypeDependent()) {
3281 llvm::FoldingSetNodeID ID;
3282 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003283
Douglas Gregorb1975722009-07-30 23:18:24 +00003284 void *InsertPos = 0;
3285 DependentTypeOfExprType *Canon
3286 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3287 if (Canon) {
3288 // We already have a "canonical" version of an identical, dependent
3289 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003290 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003291 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003292 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003293 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003294 Canon
3295 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003296 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3297 toe = Canon;
3298 }
3299 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003300 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003301 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003302 }
Steve Naroff9752f252007-08-01 18:02:17 +00003303 Types.push_back(toe);
3304 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003305}
3306
Steve Naroff9752f252007-08-01 18:02:17 +00003307/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3308/// TypeOfType AST's. The only motivation to unique these nodes would be
3309/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003310/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003311/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003312QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003313 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003314 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003315 Types.push_back(tot);
3316 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003317}
3318
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003319
Anders Carlsson395b4752009-06-24 19:06:50 +00003320/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3321/// DecltypeType AST's. The only motivation to unique these nodes would be
3322/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003323/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003324/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003325QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003326 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003327
3328 // C++0x [temp.type]p2:
3329 // If an expression e involves a template parameter, decltype(e) denotes a
3330 // unique dependent type. Two such decltype-specifiers refer to the same
3331 // type only if their expressions are equivalent (14.5.6.1).
3332 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003333 llvm::FoldingSetNodeID ID;
3334 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003335
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003336 void *InsertPos = 0;
3337 DependentDecltypeType *Canon
3338 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3339 if (Canon) {
3340 // We already have a "canonical" version of an equivalent, dependent
3341 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003342 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003343 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003344 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003345 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003346 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003347 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3348 dt = Canon;
3349 }
3350 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003351 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3352 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003353 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003354 Types.push_back(dt);
3355 return QualType(dt, 0);
3356}
3357
Sean Huntca63c202011-05-24 22:41:36 +00003358/// getUnaryTransformationType - We don't unique these, since the memory
3359/// savings are minimal and these are rare.
3360QualType ASTContext::getUnaryTransformType(QualType BaseType,
3361 QualType UnderlyingType,
3362 UnaryTransformType::UTTKind Kind)
3363 const {
3364 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003365 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3366 Kind,
3367 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003368 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003369 Types.push_back(Ty);
3370 return QualType(Ty, 0);
3371}
3372
Richard Smith483b9f32011-02-21 20:05:19 +00003373/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00003374QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00003375 void *InsertPos = 0;
3376 if (!DeducedType.isNull()) {
3377 // Look in the folding set for an existing type.
3378 llvm::FoldingSetNodeID ID;
3379 AutoType::Profile(ID, DeducedType);
3380 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3381 return QualType(AT, 0);
3382 }
3383
3384 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3385 Types.push_back(AT);
3386 if (InsertPos)
3387 AutoTypes.InsertNode(AT, InsertPos);
3388 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003389}
3390
Eli Friedmanb001de72011-10-06 23:00:33 +00003391/// getAtomicType - Return the uniqued reference to the atomic type for
3392/// the given value type.
3393QualType ASTContext::getAtomicType(QualType T) const {
3394 // Unique pointers, to guarantee there is only one pointer of a particular
3395 // structure.
3396 llvm::FoldingSetNodeID ID;
3397 AtomicType::Profile(ID, T);
3398
3399 void *InsertPos = 0;
3400 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3401 return QualType(AT, 0);
3402
3403 // If the atomic value type isn't canonical, this won't be a canonical type
3404 // either, so fill in the canonical type field.
3405 QualType Canonical;
3406 if (!T.isCanonical()) {
3407 Canonical = getAtomicType(getCanonicalType(T));
3408
3409 // Get the new insert position for the node we care about.
3410 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3411 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3412 }
3413 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3414 Types.push_back(New);
3415 AtomicTypes.InsertNode(New, InsertPos);
3416 return QualType(New, 0);
3417}
3418
Richard Smithad762fc2011-04-14 22:09:26 +00003419/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3420QualType ASTContext::getAutoDeductType() const {
3421 if (AutoDeductTy.isNull())
3422 AutoDeductTy = getAutoType(QualType());
3423 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3424 return AutoDeductTy;
3425}
3426
3427/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3428QualType ASTContext::getAutoRRefDeductType() const {
3429 if (AutoRRefDeductTy.isNull())
3430 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3431 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3432 return AutoRRefDeductTy;
3433}
3434
Reid Spencer5f016e22007-07-11 17:01:13 +00003435/// getTagDeclType - Return the unique reference to the type for the
3436/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003437QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003438 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003439 // FIXME: What is the design on getTagDeclType when it requires casting
3440 // away const? mutable?
3441 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003442}
3443
Mike Stump1eb44332009-09-09 15:08:12 +00003444/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3445/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3446/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003447CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003448 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003449}
3450
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003451/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3452CanQualType ASTContext::getIntMaxType() const {
3453 return getFromTargetType(Target->getIntMaxType());
3454}
3455
3456/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3457CanQualType ASTContext::getUIntMaxType() const {
3458 return getFromTargetType(Target->getUIntMaxType());
3459}
3460
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003461/// getSignedWCharType - Return the type of "signed wchar_t".
3462/// Used when in C++, as a GCC extension.
3463QualType ASTContext::getSignedWCharType() const {
3464 // FIXME: derive from "Target" ?
3465 return WCharTy;
3466}
3467
3468/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3469/// Used when in C++, as a GCC extension.
3470QualType ASTContext::getUnsignedWCharType() const {
3471 // FIXME: derive from "Target" ?
3472 return UnsignedIntTy;
3473}
3474
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003475/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003476/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3477QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003478 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003479}
3480
Chris Lattnere6327742008-04-02 05:18:44 +00003481//===----------------------------------------------------------------------===//
3482// Type Operators
3483//===----------------------------------------------------------------------===//
3484
Jay Foad4ba2a172011-01-12 09:06:06 +00003485CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003486 // Push qualifiers into arrays, and then discard any remaining
3487 // qualifiers.
3488 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003489 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003490 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003491 QualType Result;
3492 if (isa<ArrayType>(Ty)) {
3493 Result = getArrayDecayedType(QualType(Ty,0));
3494 } else if (isa<FunctionType>(Ty)) {
3495 Result = getPointerType(QualType(Ty, 0));
3496 } else {
3497 Result = QualType(Ty, 0);
3498 }
3499
3500 return CanQualType::CreateUnsafe(Result);
3501}
3502
John McCall62c28c82011-01-18 07:41:22 +00003503QualType ASTContext::getUnqualifiedArrayType(QualType type,
3504 Qualifiers &quals) {
3505 SplitQualType splitType = type.getSplitUnqualifiedType();
3506
3507 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3508 // the unqualified desugared type and then drops it on the floor.
3509 // We then have to strip that sugar back off with
3510 // getUnqualifiedDesugaredType(), which is silly.
3511 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003512 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003513
3514 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003515 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003516 quals = splitType.Quals;
3517 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003518 }
3519
John McCall62c28c82011-01-18 07:41:22 +00003520 // Otherwise, recurse on the array's element type.
3521 QualType elementType = AT->getElementType();
3522 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3523
3524 // If that didn't change the element type, AT has no qualifiers, so we
3525 // can just use the results in splitType.
3526 if (elementType == unqualElementType) {
3527 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003528 quals = splitType.Quals;
3529 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003530 }
3531
3532 // Otherwise, add in the qualifiers from the outermost type, then
3533 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003534 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003535
Douglas Gregor9dadd942010-05-17 18:45:21 +00003536 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003537 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003538 CAT->getSizeModifier(), 0);
3539 }
3540
Douglas Gregor9dadd942010-05-17 18:45:21 +00003541 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003542 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003543 }
3544
Douglas Gregor9dadd942010-05-17 18:45:21 +00003545 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003546 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003547 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003548 VAT->getSizeModifier(),
3549 VAT->getIndexTypeCVRQualifiers(),
3550 VAT->getBracketsRange());
3551 }
3552
3553 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003554 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003555 DSAT->getSizeModifier(), 0,
3556 SourceRange());
3557}
3558
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003559/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3560/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3561/// they point to and return true. If T1 and T2 aren't pointer types
3562/// or pointer-to-member types, or if they are not similar at this
3563/// level, returns false and leaves T1 and T2 unchanged. Top-level
3564/// qualifiers on T1 and T2 are ignored. This function will typically
3565/// be called in a loop that successively "unwraps" pointer and
3566/// pointer-to-member types to compare them at each level.
3567bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3568 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3569 *T2PtrType = T2->getAs<PointerType>();
3570 if (T1PtrType && T2PtrType) {
3571 T1 = T1PtrType->getPointeeType();
3572 T2 = T2PtrType->getPointeeType();
3573 return true;
3574 }
3575
3576 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3577 *T2MPType = T2->getAs<MemberPointerType>();
3578 if (T1MPType && T2MPType &&
3579 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3580 QualType(T2MPType->getClass(), 0))) {
3581 T1 = T1MPType->getPointeeType();
3582 T2 = T2MPType->getPointeeType();
3583 return true;
3584 }
3585
David Blaikie4e4d0842012-03-11 07:00:24 +00003586 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003587 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3588 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3589 if (T1OPType && T2OPType) {
3590 T1 = T1OPType->getPointeeType();
3591 T2 = T2OPType->getPointeeType();
3592 return true;
3593 }
3594 }
3595
3596 // FIXME: Block pointers, too?
3597
3598 return false;
3599}
3600
Jay Foad4ba2a172011-01-12 09:06:06 +00003601DeclarationNameInfo
3602ASTContext::getNameForTemplate(TemplateName Name,
3603 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003604 switch (Name.getKind()) {
3605 case TemplateName::QualifiedTemplate:
3606 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003607 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003608 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3609 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003610
John McCall14606042011-06-30 08:33:18 +00003611 case TemplateName::OverloadedTemplate: {
3612 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3613 // DNInfo work in progress: CHECKME: what about DNLoc?
3614 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3615 }
3616
3617 case TemplateName::DependentTemplate: {
3618 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003619 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003620 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003621 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3622 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003623 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003624 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3625 // DNInfo work in progress: FIXME: source locations?
3626 DeclarationNameLoc DNLoc;
3627 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3628 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3629 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003630 }
3631 }
3632
John McCall14606042011-06-30 08:33:18 +00003633 case TemplateName::SubstTemplateTemplateParm: {
3634 SubstTemplateTemplateParmStorage *subst
3635 = Name.getAsSubstTemplateTemplateParm();
3636 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3637 NameLoc);
3638 }
3639
3640 case TemplateName::SubstTemplateTemplateParmPack: {
3641 SubstTemplateTemplateParmPackStorage *subst
3642 = Name.getAsSubstTemplateTemplateParmPack();
3643 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3644 NameLoc);
3645 }
3646 }
3647
3648 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003649}
3650
Jay Foad4ba2a172011-01-12 09:06:06 +00003651TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003652 switch (Name.getKind()) {
3653 case TemplateName::QualifiedTemplate:
3654 case TemplateName::Template: {
3655 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003656 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003657 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003658 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3659
3660 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003661 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003662 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003663
John McCall14606042011-06-30 08:33:18 +00003664 case TemplateName::OverloadedTemplate:
3665 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003666
John McCall14606042011-06-30 08:33:18 +00003667 case TemplateName::DependentTemplate: {
3668 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3669 assert(DTN && "Non-dependent template names must refer to template decls.");
3670 return DTN->CanonicalTemplateName;
3671 }
3672
3673 case TemplateName::SubstTemplateTemplateParm: {
3674 SubstTemplateTemplateParmStorage *subst
3675 = Name.getAsSubstTemplateTemplateParm();
3676 return getCanonicalTemplateName(subst->getReplacement());
3677 }
3678
3679 case TemplateName::SubstTemplateTemplateParmPack: {
3680 SubstTemplateTemplateParmPackStorage *subst
3681 = Name.getAsSubstTemplateTemplateParmPack();
3682 TemplateTemplateParmDecl *canonParameter
3683 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3684 TemplateArgument canonArgPack
3685 = getCanonicalTemplateArgument(subst->getArgumentPack());
3686 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3687 }
3688 }
3689
3690 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003691}
3692
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003693bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3694 X = getCanonicalTemplateName(X);
3695 Y = getCanonicalTemplateName(Y);
3696 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3697}
3698
Mike Stump1eb44332009-09-09 15:08:12 +00003699TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003700ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003701 switch (Arg.getKind()) {
3702 case TemplateArgument::Null:
3703 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003704
Douglas Gregor1275ae02009-07-28 23:00:59 +00003705 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003706 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003707
Douglas Gregord2008e22012-04-06 22:40:38 +00003708 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003709 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3710 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003711 }
Mike Stump1eb44332009-09-09 15:08:12 +00003712
Eli Friedmand7a6b162012-09-26 02:36:12 +00003713 case TemplateArgument::NullPtr:
3714 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3715 /*isNullPtr*/true);
3716
Douglas Gregor788cd062009-11-11 01:00:40 +00003717 case TemplateArgument::Template:
3718 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003719
3720 case TemplateArgument::TemplateExpansion:
3721 return TemplateArgument(getCanonicalTemplateName(
3722 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003723 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003724
Douglas Gregor1275ae02009-07-28 23:00:59 +00003725 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00003726 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003727
Douglas Gregor1275ae02009-07-28 23:00:59 +00003728 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003729 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003730
Douglas Gregor1275ae02009-07-28 23:00:59 +00003731 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003732 if (Arg.pack_size() == 0)
3733 return Arg;
3734
Douglas Gregor910f8002010-11-07 23:05:16 +00003735 TemplateArgument *CanonArgs
3736 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003737 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003738 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003739 AEnd = Arg.pack_end();
3740 A != AEnd; (void)++A, ++Idx)
3741 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003742
Douglas Gregor910f8002010-11-07 23:05:16 +00003743 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003744 }
3745 }
3746
3747 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003748 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003749}
3750
Douglas Gregord57959a2009-03-27 23:10:48 +00003751NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003752ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003753 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003754 return 0;
3755
3756 switch (NNS->getKind()) {
3757 case NestedNameSpecifier::Identifier:
3758 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003759 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003760 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3761 NNS->getAsIdentifier());
3762
3763 case NestedNameSpecifier::Namespace:
3764 // A namespace is canonical; build a nested-name-specifier with
3765 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003766 return NestedNameSpecifier::Create(*this, 0,
3767 NNS->getAsNamespace()->getOriginalNamespace());
3768
3769 case NestedNameSpecifier::NamespaceAlias:
3770 // A namespace is canonical; build a nested-name-specifier with
3771 // this namespace and no prefix.
3772 return NestedNameSpecifier::Create(*this, 0,
3773 NNS->getAsNamespaceAlias()->getNamespace()
3774 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003775
3776 case NestedNameSpecifier::TypeSpec:
3777 case NestedNameSpecifier::TypeSpecWithTemplate: {
3778 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003779
3780 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3781 // break it apart into its prefix and identifier, then reconsititute those
3782 // as the canonical nested-name-specifier. This is required to canonicalize
3783 // a dependent nested-name-specifier involving typedefs of dependent-name
3784 // types, e.g.,
3785 // typedef typename T::type T1;
3786 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003787 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3788 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003789 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003790
Eli Friedman16412ef2012-03-03 04:09:56 +00003791 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3792 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3793 // first place?
John McCall3b657512011-01-19 10:06:00 +00003794 return NestedNameSpecifier::Create(*this, 0, false,
3795 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003796 }
3797
3798 case NestedNameSpecifier::Global:
3799 // The global specifier is canonical and unique.
3800 return NNS;
3801 }
3802
David Blaikie7530c032012-01-17 06:56:22 +00003803 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003804}
3805
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003806
Jay Foad4ba2a172011-01-12 09:06:06 +00003807const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003808 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003809 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003810 // Handle the common positive case fast.
3811 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3812 return AT;
3813 }
Mike Stump1eb44332009-09-09 15:08:12 +00003814
John McCall0953e762009-09-24 19:53:00 +00003815 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003816 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003817 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003818
John McCall0953e762009-09-24 19:53:00 +00003819 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003820 // implements C99 6.7.3p8: "If the specification of an array type includes
3821 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003822
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003823 // If we get here, we either have type qualifiers on the type, or we have
3824 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003825 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003826
John McCall3b657512011-01-19 10:06:00 +00003827 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003828 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003829
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003830 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003831 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003832 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003833 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003834
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003835 // Otherwise, we have an array and we have qualifiers on it. Push the
3836 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003837 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003838
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003839 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3840 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3841 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003842 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003843 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3844 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3845 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003846 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003847
Mike Stump1eb44332009-09-09 15:08:12 +00003848 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003849 = dyn_cast<DependentSizedArrayType>(ATy))
3850 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003851 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003852 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003853 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003854 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003855 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003856
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003857 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003858 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003859 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003860 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003861 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003862 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003863}
3864
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003865QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003866 // C99 6.7.5.3p7:
3867 // A declaration of a parameter as "array of type" shall be
3868 // adjusted to "qualified pointer to type", where the type
3869 // qualifiers (if any) are those specified within the [ and ] of
3870 // the array type derivation.
3871 if (T->isArrayType())
3872 return getArrayDecayedType(T);
3873
3874 // C99 6.7.5.3p8:
3875 // A declaration of a parameter as "function returning type"
3876 // shall be adjusted to "pointer to function returning type", as
3877 // in 6.3.2.1.
3878 if (T->isFunctionType())
3879 return getPointerType(T);
3880
3881 return T;
3882}
3883
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003884QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003885 T = getVariableArrayDecayedType(T);
3886 T = getAdjustedParameterType(T);
3887 return T.getUnqualifiedType();
3888}
3889
Chris Lattnere6327742008-04-02 05:18:44 +00003890/// getArrayDecayedType - Return the properly qualified result of decaying the
3891/// specified array type to a pointer. This operation is non-trivial when
3892/// handling typedefs etc. The canonical type of "T" must be an array type,
3893/// this returns a pointer to a properly qualified element of the array.
3894///
3895/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003896QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003897 // Get the element type with 'getAsArrayType' so that we don't lose any
3898 // typedefs in the element type of the array. This also handles propagation
3899 // of type qualifiers from the array type into the element type if present
3900 // (C99 6.7.3p8).
3901 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3902 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003903
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003904 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003905
3906 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003907 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003908}
3909
John McCall3b657512011-01-19 10:06:00 +00003910QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3911 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003912}
3913
John McCall3b657512011-01-19 10:06:00 +00003914QualType ASTContext::getBaseElementType(QualType type) const {
3915 Qualifiers qs;
3916 while (true) {
3917 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003918 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00003919 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003920
John McCall3b657512011-01-19 10:06:00 +00003921 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00003922 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00003923 }
Mike Stump1eb44332009-09-09 15:08:12 +00003924
John McCall3b657512011-01-19 10:06:00 +00003925 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003926}
3927
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003928/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003929uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003930ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3931 uint64_t ElementCount = 1;
3932 do {
3933 ElementCount *= CA->getSize().getZExtValue();
3934 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3935 } while (CA);
3936 return ElementCount;
3937}
3938
Reid Spencer5f016e22007-07-11 17:01:13 +00003939/// getFloatingRank - Return a relative rank for floating point types.
3940/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003941static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003942 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003943 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003944
John McCall183700f2009-09-21 23:43:11 +00003945 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3946 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003947 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003948 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003949 case BuiltinType::Float: return FloatRank;
3950 case BuiltinType::Double: return DoubleRank;
3951 case BuiltinType::LongDouble: return LongDoubleRank;
3952 }
3953}
3954
Mike Stump1eb44332009-09-09 15:08:12 +00003955/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3956/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003957/// 'typeDomain' is a real floating point or complex type.
3958/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003959QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3960 QualType Domain) const {
3961 FloatingRank EltRank = getFloatingRank(Size);
3962 if (Domain->isComplexType()) {
3963 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003964 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00003965 case FloatRank: return FloatComplexTy;
3966 case DoubleRank: return DoubleComplexTy;
3967 case LongDoubleRank: return LongDoubleComplexTy;
3968 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003969 }
Chris Lattner1361b112008-04-06 23:58:54 +00003970
3971 assert(Domain->isRealFloatingType() && "Unknown domain!");
3972 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003973 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattner1361b112008-04-06 23:58:54 +00003974 case FloatRank: return FloatTy;
3975 case DoubleRank: return DoubleTy;
3976 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003977 }
David Blaikie561d3ab2012-01-17 02:30:50 +00003978 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00003979}
3980
Chris Lattner7cfeb082008-04-06 23:55:33 +00003981/// getFloatingTypeOrder - Compare the rank of the two specified floating
3982/// point types, ignoring the domain of the type (i.e. 'double' ==
3983/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003984/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003985int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003986 FloatingRank LHSR = getFloatingRank(LHS);
3987 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003988
Chris Lattnera75cea32008-04-06 23:38:49 +00003989 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003990 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003991 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003992 return 1;
3993 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003994}
3995
Chris Lattnerf52ab252008-04-06 22:59:24 +00003996/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3997/// routine will assert if passed a built-in type that isn't an integer or enum,
3998/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003999unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004000 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004001
Chris Lattnerf52ab252008-04-06 22:59:24 +00004002 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004003 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004004 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004005 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004006 case BuiltinType::Char_S:
4007 case BuiltinType::Char_U:
4008 case BuiltinType::SChar:
4009 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004010 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004011 case BuiltinType::Short:
4012 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004013 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004014 case BuiltinType::Int:
4015 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004016 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004017 case BuiltinType::Long:
4018 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004019 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004020 case BuiltinType::LongLong:
4021 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004022 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004023 case BuiltinType::Int128:
4024 case BuiltinType::UInt128:
4025 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004026 }
4027}
4028
Eli Friedman04e83572009-08-20 04:21:42 +00004029/// \brief Whether this is a promotable bitfield reference according
4030/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4031///
4032/// \returns the type this bit-field will promote to, or NULL if no
4033/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004034QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004035 if (E->isTypeDependent() || E->isValueDependent())
4036 return QualType();
4037
Eli Friedman04e83572009-08-20 04:21:42 +00004038 FieldDecl *Field = E->getBitField();
4039 if (!Field)
4040 return QualType();
4041
4042 QualType FT = Field->getType();
4043
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004044 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004045 uint64_t IntSize = getTypeSize(IntTy);
4046 // GCC extension compatibility: if the bit-field size is less than or equal
4047 // to the size of int, it gets promoted no matter what its type is.
4048 // For instance, unsigned long bf : 4 gets promoted to signed int.
4049 if (BitWidth < IntSize)
4050 return IntTy;
4051
4052 if (BitWidth == IntSize)
4053 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4054
4055 // Types bigger than int are not subject to promotions, and therefore act
4056 // like the base type.
4057 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4058 // is ridiculous.
4059 return QualType();
4060}
4061
Eli Friedmana95d7572009-08-19 07:44:53 +00004062/// getPromotedIntegerType - Returns the type that Promotable will
4063/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4064/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004065QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004066 assert(!Promotable.isNull());
4067 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004068 if (const EnumType *ET = Promotable->getAs<EnumType>())
4069 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004070
4071 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4072 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4073 // (3.9.1) can be converted to a prvalue of the first of the following
4074 // types that can represent all the values of its underlying type:
4075 // int, unsigned int, long int, unsigned long int, long long int, or
4076 // unsigned long long int [...]
4077 // FIXME: Is there some better way to compute this?
4078 if (BT->getKind() == BuiltinType::WChar_S ||
4079 BT->getKind() == BuiltinType::WChar_U ||
4080 BT->getKind() == BuiltinType::Char16 ||
4081 BT->getKind() == BuiltinType::Char32) {
4082 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4083 uint64_t FromSize = getTypeSize(BT);
4084 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4085 LongLongTy, UnsignedLongLongTy };
4086 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4087 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4088 if (FromSize < ToSize ||
4089 (FromSize == ToSize &&
4090 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4091 return PromoteTypes[Idx];
4092 }
4093 llvm_unreachable("char type should fit into long long");
4094 }
4095 }
4096
4097 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004098 if (Promotable->isSignedIntegerType())
4099 return IntTy;
4100 uint64_t PromotableSize = getTypeSize(Promotable);
4101 uint64_t IntSize = getTypeSize(IntTy);
4102 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4103 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4104}
4105
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004106/// \brief Recurses in pointer/array types until it finds an objc retainable
4107/// type and returns its ownership.
4108Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4109 while (!T.isNull()) {
4110 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4111 return T.getObjCLifetime();
4112 if (T->isArrayType())
4113 T = getBaseElementType(T);
4114 else if (const PointerType *PT = T->getAs<PointerType>())
4115 T = PT->getPointeeType();
4116 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004117 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004118 else
4119 break;
4120 }
4121
4122 return Qualifiers::OCL_None;
4123}
4124
Mike Stump1eb44332009-09-09 15:08:12 +00004125/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004126/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004127/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004128int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004129 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4130 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004131 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004132
Chris Lattnerf52ab252008-04-06 22:59:24 +00004133 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4134 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004135
Chris Lattner7cfeb082008-04-06 23:55:33 +00004136 unsigned LHSRank = getIntegerRank(LHSC);
4137 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004138
Chris Lattner7cfeb082008-04-06 23:55:33 +00004139 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4140 if (LHSRank == RHSRank) return 0;
4141 return LHSRank > RHSRank ? 1 : -1;
4142 }
Mike Stump1eb44332009-09-09 15:08:12 +00004143
Chris Lattner7cfeb082008-04-06 23:55:33 +00004144 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4145 if (LHSUnsigned) {
4146 // If the unsigned [LHS] type is larger, return it.
4147 if (LHSRank >= RHSRank)
4148 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004149
Chris Lattner7cfeb082008-04-06 23:55:33 +00004150 // If the signed type can represent all values of the unsigned type, it
4151 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004152 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004153 return -1;
4154 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004155
Chris Lattner7cfeb082008-04-06 23:55:33 +00004156 // If the unsigned [RHS] type is larger, return it.
4157 if (RHSRank >= LHSRank)
4158 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004159
Chris Lattner7cfeb082008-04-06 23:55:33 +00004160 // If the signed type can represent all values of the unsigned type, it
4161 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004162 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004163 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004164}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004165
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004166static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004167CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4168 DeclContext *DC, IdentifierInfo *Id) {
4169 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004170 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004171 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004172 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004173 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004174}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004175
Mike Stump1eb44332009-09-09 15:08:12 +00004176// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004177QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004178 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004179 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004180 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004181 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004182 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004183
Anders Carlssonf06273f2007-11-19 00:25:30 +00004184 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004185
Anders Carlsson71993dd2007-08-17 05:31:46 +00004186 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004187 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004188 // int flags;
4189 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004190 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004191 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004192 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004193 FieldTypes[3] = LongTy;
4194
Anders Carlsson71993dd2007-08-17 05:31:46 +00004195 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004196 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004197 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004198 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004199 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004200 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004201 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004202 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004203 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004204 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004205 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004206 }
4207
Douglas Gregor838db382010-02-11 01:19:42 +00004208 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004209 }
Mike Stump1eb44332009-09-09 15:08:12 +00004210
Anders Carlsson71993dd2007-08-17 05:31:46 +00004211 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004212}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004213
Douglas Gregor319ac892009-04-23 22:29:11 +00004214void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004215 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004216 assert(Rec && "Invalid CFConstantStringType");
4217 CFConstantStringTypeDecl = Rec->getDecl();
4218}
4219
Jay Foad4ba2a172011-01-12 09:06:06 +00004220QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004221 if (BlockDescriptorType)
4222 return getTagDeclType(BlockDescriptorType);
4223
4224 RecordDecl *T;
4225 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004226 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004227 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004228 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004229
4230 QualType FieldTypes[] = {
4231 UnsignedLongTy,
4232 UnsignedLongTy,
4233 };
4234
4235 const char *FieldNames[] = {
4236 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004237 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004238 };
4239
4240 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004241 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004242 SourceLocation(),
4243 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004244 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004245 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004246 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004247 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004248 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004249 T->addDecl(Field);
4250 }
4251
Douglas Gregor838db382010-02-11 01:19:42 +00004252 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004253
4254 BlockDescriptorType = T;
4255
4256 return getTagDeclType(BlockDescriptorType);
4257}
4258
Jay Foad4ba2a172011-01-12 09:06:06 +00004259QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004260 if (BlockDescriptorExtendedType)
4261 return getTagDeclType(BlockDescriptorExtendedType);
4262
4263 RecordDecl *T;
4264 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004265 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004266 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004267 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004268
4269 QualType FieldTypes[] = {
4270 UnsignedLongTy,
4271 UnsignedLongTy,
4272 getPointerType(VoidPtrTy),
4273 getPointerType(VoidPtrTy)
4274 };
4275
4276 const char *FieldNames[] = {
4277 "reserved",
4278 "Size",
4279 "CopyFuncPtr",
4280 "DestroyFuncPtr"
4281 };
4282
4283 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004284 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004285 SourceLocation(),
4286 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004287 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004288 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004289 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004290 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004291 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004292 T->addDecl(Field);
4293 }
4294
Douglas Gregor838db382010-02-11 01:19:42 +00004295 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004296
4297 BlockDescriptorExtendedType = T;
4298
4299 return getTagDeclType(BlockDescriptorExtendedType);
4300}
4301
Jay Foad4ba2a172011-01-12 09:06:06 +00004302bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00004303 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004304 return true;
David Blaikie4e4d0842012-03-11 07:00:24 +00004305 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004306 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4307 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00004308 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004309
4310 }
4311 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004312 return false;
4313}
4314
Jay Foad4ba2a172011-01-12 09:06:06 +00004315QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00004316ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004317 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00004318 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004319 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00004320 // unsigned int __flags;
4321 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00004322 // void *__copy_helper; // as needed
4323 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004324 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00004325 // } *
4326
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004327 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4328
4329 // FIXME: Move up
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004330 SmallString<36> Name;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00004331 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4332 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004333 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004334 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004335 T->startDefinition();
4336 QualType Int32Ty = IntTy;
4337 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4338 QualType FieldTypes[] = {
4339 getPointerType(VoidPtrTy),
4340 getPointerType(getTagDeclType(T)),
4341 Int32Ty,
4342 Int32Ty,
4343 getPointerType(VoidPtrTy),
4344 getPointerType(VoidPtrTy),
4345 Ty
4346 };
4347
Chris Lattner5f9e2722011-07-23 10:55:15 +00004348 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004349 "__isa",
4350 "__forwarding",
4351 "__flags",
4352 "__size",
4353 "__copy_helper",
4354 "__destroy_helper",
4355 DeclName,
4356 };
4357
4358 for (size_t i = 0; i < 7; ++i) {
4359 if (!HasCopyAndDispose && i >=4 && i <= 5)
4360 continue;
4361 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004362 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004363 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004364 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004365 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004366 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004367 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004368 T->addDecl(Field);
4369 }
4370
Douglas Gregor838db382010-02-11 01:19:42 +00004371 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004372
4373 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00004374}
4375
Douglas Gregore97179c2011-09-08 01:46:34 +00004376TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4377 if (!ObjCInstanceTypeDecl)
4378 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4379 getTranslationUnitDecl(),
4380 SourceLocation(),
4381 SourceLocation(),
4382 &Idents.get("instancetype"),
4383 getTrivialTypeSourceInfo(getObjCIdType()));
4384 return ObjCInstanceTypeDecl;
4385}
4386
Anders Carlssone8c49532007-10-29 06:33:42 +00004387// This returns true if a type has been typedefed to BOOL:
4388// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004389static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004390 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004391 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4392 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004393
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004394 return false;
4395}
4396
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004397/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004398/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004399CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004400 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4401 return CharUnits::Zero();
4402
Ken Dyck199c3d62010-01-11 17:06:35 +00004403 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004404
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004405 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004406 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004407 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004408 // Treat arrays as pointers, since that's how they're passed in.
4409 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004410 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004411 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004412}
4413
4414static inline
4415std::string charUnitsToString(const CharUnits &CU) {
4416 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004417}
4418
John McCall6b5a61b2011-02-07 10:33:21 +00004419/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004420/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004421std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4422 std::string S;
4423
David Chisnall5e530af2009-11-17 19:33:30 +00004424 const BlockDecl *Decl = Expr->getBlockDecl();
4425 QualType BlockTy =
4426 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4427 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004428 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004429 // Compute size of all parameters.
4430 // Start with computing size of a pointer in number of bytes.
4431 // FIXME: There might(should) be a better way of doing this computation!
4432 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004433 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4434 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004435 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004436 E = Decl->param_end(); PI != E; ++PI) {
4437 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004438 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004439 if (sz.isZero())
4440 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004441 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004442 ParmOffset += sz;
4443 }
4444 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004445 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004446 // Block pointer and offset.
4447 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004448
4449 // Argument types.
4450 ParmOffset = PtrSize;
4451 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4452 Decl->param_end(); PI != E; ++PI) {
4453 ParmVarDecl *PVDecl = *PI;
4454 QualType PType = PVDecl->getOriginalType();
4455 if (const ArrayType *AT =
4456 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4457 // Use array's original type only if it has known number of
4458 // elements.
4459 if (!isa<ConstantArrayType>(AT))
4460 PType = PVDecl->getType();
4461 } else if (PType->isFunctionType())
4462 PType = PVDecl->getType();
4463 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004464 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004465 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004466 }
John McCall6b5a61b2011-02-07 10:33:21 +00004467
4468 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004469}
4470
Douglas Gregorf968d832011-05-27 01:19:52 +00004471bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004472 std::string& S) {
4473 // Encode result type.
4474 getObjCEncodingForType(Decl->getResultType(), S);
4475 CharUnits ParmOffset;
4476 // Compute size of all parameters.
4477 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4478 E = Decl->param_end(); PI != E; ++PI) {
4479 QualType PType = (*PI)->getType();
4480 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004481 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004482 continue;
4483
David Chisnall5389f482010-12-30 14:05:53 +00004484 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004485 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004486 ParmOffset += sz;
4487 }
4488 S += charUnitsToString(ParmOffset);
4489 ParmOffset = CharUnits::Zero();
4490
4491 // Argument types.
4492 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4493 E = Decl->param_end(); PI != E; ++PI) {
4494 ParmVarDecl *PVDecl = *PI;
4495 QualType PType = PVDecl->getOriginalType();
4496 if (const ArrayType *AT =
4497 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4498 // Use array's original type only if it has known number of
4499 // elements.
4500 if (!isa<ConstantArrayType>(AT))
4501 PType = PVDecl->getType();
4502 } else if (PType->isFunctionType())
4503 PType = PVDecl->getType();
4504 getObjCEncodingForType(PType, S);
4505 S += charUnitsToString(ParmOffset);
4506 ParmOffset += getObjCEncodingTypeSize(PType);
4507 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004508
4509 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004510}
4511
Bob Wilsondc8dab62011-11-30 01:57:58 +00004512/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4513/// method parameter or return type. If Extended, include class names and
4514/// block object types.
4515void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4516 QualType T, std::string& S,
4517 bool Extended) const {
4518 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4519 getObjCEncodingForTypeQualifier(QT, S);
4520 // Encode parameter type.
4521 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4522 true /*OutermostType*/,
4523 false /*EncodingProperty*/,
4524 false /*StructField*/,
4525 Extended /*EncodeBlockParameters*/,
4526 Extended /*EncodeClassNames*/);
4527}
4528
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004529/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004530/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004531bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004532 std::string& S,
4533 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004534 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004535 // Encode return type.
4536 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4537 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004538 // Compute size of all parameters.
4539 // Start with computing size of a pointer in number of bytes.
4540 // FIXME: There might(should) be a better way of doing this computation!
4541 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004542 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004543 // The first two arguments (self and _cmd) are pointers; account for
4544 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004545 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004546 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004547 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004548 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004549 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004550 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004551 continue;
4552
Ken Dyck199c3d62010-01-11 17:06:35 +00004553 assert (sz.isPositive() &&
4554 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004555 ParmOffset += sz;
4556 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004557 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004558 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004559 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004560
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004561 // Argument types.
4562 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004563 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004564 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004565 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004566 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004567 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004568 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4569 // Use array's original type only if it has known number of
4570 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004571 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004572 PType = PVDecl->getType();
4573 } else if (PType->isFunctionType())
4574 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004575 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4576 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004577 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004578 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004579 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004580
4581 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004582}
4583
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004584/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004585/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004586/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4587/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004588/// Property attributes are stored as a comma-delimited C string. The simple
4589/// attributes readonly and bycopy are encoded as single characters. The
4590/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4591/// encoded as single characters, followed by an identifier. Property types
4592/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004593/// these attributes are defined by the following enumeration:
4594/// @code
4595/// enum PropertyAttributes {
4596/// kPropertyReadOnly = 'R', // property is read-only.
4597/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4598/// kPropertyByref = '&', // property is a reference to the value last assigned
4599/// kPropertyDynamic = 'D', // property is dynamic
4600/// kPropertyGetter = 'G', // followed by getter selector name
4601/// kPropertySetter = 'S', // followed by setter selector name
4602/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004603/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004604/// kPropertyWeak = 'W' // 'weak' property
4605/// kPropertyStrong = 'P' // property GC'able
4606/// kPropertyNonAtomic = 'N' // property non-atomic
4607/// };
4608/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004609void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004610 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004611 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004612 // Collect information from the property implementation decl(s).
4613 bool Dynamic = false;
4614 ObjCPropertyImplDecl *SynthesizePID = 0;
4615
4616 // FIXME: Duplicated code due to poor abstraction.
4617 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004618 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004619 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4620 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004621 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004622 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004623 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004624 if (PID->getPropertyDecl() == PD) {
4625 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4626 Dynamic = true;
4627 } else {
4628 SynthesizePID = PID;
4629 }
4630 }
4631 }
4632 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004633 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004634 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004635 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004636 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004637 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004638 if (PID->getPropertyDecl() == PD) {
4639 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4640 Dynamic = true;
4641 } else {
4642 SynthesizePID = PID;
4643 }
4644 }
Mike Stump1eb44332009-09-09 15:08:12 +00004645 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004646 }
4647 }
4648
4649 // FIXME: This is not very efficient.
4650 S = "T";
4651
4652 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004653 // GCC has some special rules regarding encoding of properties which
4654 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004655 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004656 true /* outermost type */,
4657 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004658
4659 if (PD->isReadOnly()) {
4660 S += ",R";
4661 } else {
4662 switch (PD->getSetterKind()) {
4663 case ObjCPropertyDecl::Assign: break;
4664 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004665 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004666 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004667 }
4668 }
4669
4670 // It really isn't clear at all what this means, since properties
4671 // are "dynamic by default".
4672 if (Dynamic)
4673 S += ",D";
4674
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004675 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4676 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004677
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004678 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4679 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004680 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004681 }
4682
4683 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4684 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004685 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004686 }
4687
4688 if (SynthesizePID) {
4689 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4690 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004691 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004692 }
4693
4694 // FIXME: OBJCGC: weak & strong
4695}
4696
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004697/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004698/// Another legacy compatibility encoding: 32-bit longs are encoded as
4699/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004700/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4701///
4702void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004703 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004704 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004705 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004706 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004707 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004708 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004709 PointeeTy = IntTy;
4710 }
4711 }
4712}
4713
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004714void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004715 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004716 // We follow the behavior of gcc, expanding structures which are
4717 // directly pointed to, and expanding embedded structures. Note that
4718 // these rules are sufficient to prevent recursive encoding of the
4719 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004720 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004721 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004722}
4723
David Chisnall64fd7e82010-06-04 01:10:52 +00004724static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4725 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004726 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004727 case BuiltinType::Void: return 'v';
4728 case BuiltinType::Bool: return 'B';
4729 case BuiltinType::Char_U:
4730 case BuiltinType::UChar: return 'C';
4731 case BuiltinType::UShort: return 'S';
4732 case BuiltinType::UInt: return 'I';
4733 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004734 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004735 case BuiltinType::UInt128: return 'T';
4736 case BuiltinType::ULongLong: return 'Q';
4737 case BuiltinType::Char_S:
4738 case BuiltinType::SChar: return 'c';
4739 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004740 case BuiltinType::WChar_S:
4741 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004742 case BuiltinType::Int: return 'i';
4743 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004744 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004745 case BuiltinType::LongLong: return 'q';
4746 case BuiltinType::Int128: return 't';
4747 case BuiltinType::Float: return 'f';
4748 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004749 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004750 }
4751}
4752
Douglas Gregor5471bc82011-09-08 17:18:35 +00004753static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4754 EnumDecl *Enum = ET->getDecl();
4755
4756 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4757 if (!Enum->isFixed())
4758 return 'i';
4759
4760 // The encoding of a fixed enum type matches its fixed underlying type.
4761 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4762}
4763
Jay Foad4ba2a172011-01-12 09:06:06 +00004764static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004765 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004766 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004767 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004768 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4769 // The GNU runtime requires more information; bitfields are encoded as b,
4770 // then the offset (in bits) of the first element, then the type of the
4771 // bitfield, then the size in bits. For example, in this structure:
4772 //
4773 // struct
4774 // {
4775 // int integer;
4776 // int flags:2;
4777 // };
4778 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4779 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4780 // information is not especially sensible, but we're stuck with it for
4781 // compatibility with GCC, although providing it breaks anything that
4782 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00004783 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004784 const RecordDecl *RD = FD->getParent();
4785 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004786 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004787 if (const EnumType *ET = T->getAs<EnumType>())
4788 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004789 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004790 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004791 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004792 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004793}
4794
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004795// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004796void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4797 bool ExpandPointedToStructures,
4798 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004799 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004800 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004801 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004802 bool StructField,
4803 bool EncodeBlockParameters,
4804 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004805 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004806 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004807 return EncodeBitField(this, S, T, FD);
4808 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004809 return;
4810 }
Mike Stump1eb44332009-09-09 15:08:12 +00004811
John McCall183700f2009-09-21 23:43:11 +00004812 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004813 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004814 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004815 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004816 return;
4817 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004818
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004819 // encoding for pointer or r3eference types.
4820 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004821 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004822 if (PT->isObjCSelType()) {
4823 S += ':';
4824 return;
4825 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004826 PointeeTy = PT->getPointeeType();
4827 }
4828 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4829 PointeeTy = RT->getPointeeType();
4830 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004831 bool isReadOnly = false;
4832 // For historical/compatibility reasons, the read-only qualifier of the
4833 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4834 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004835 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004836 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004837 if (OutermostType && T.isConstQualified()) {
4838 isReadOnly = true;
4839 S += 'r';
4840 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004841 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004842 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004843 while (P->getAs<PointerType>())
4844 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004845 if (P.isConstQualified()) {
4846 isReadOnly = true;
4847 S += 'r';
4848 }
4849 }
4850 if (isReadOnly) {
4851 // Another legacy compatibility encoding. Some ObjC qualifier and type
4852 // combinations need to be rearranged.
4853 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004854 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004855 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004856 }
Mike Stump1eb44332009-09-09 15:08:12 +00004857
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004858 if (PointeeTy->isCharType()) {
4859 // char pointer types should be encoded as '*' unless it is a
4860 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004861 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004862 S += '*';
4863 return;
4864 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004865 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004866 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4867 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4868 S += '#';
4869 return;
4870 }
4871 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4872 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4873 S += '@';
4874 return;
4875 }
4876 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004877 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004878 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004879 getLegacyIntegralTypeEncoding(PointeeTy);
4880
Mike Stump1eb44332009-09-09 15:08:12 +00004881 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004882 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004883 return;
4884 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004885
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004886 if (const ArrayType *AT =
4887 // Ignore type qualifiers etc.
4888 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004889 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004890 // Incomplete arrays are encoded as a pointer to the array element.
4891 S += '^';
4892
Mike Stump1eb44332009-09-09 15:08:12 +00004893 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004894 false, ExpandStructures, FD);
4895 } else {
4896 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004897
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004898 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4899 if (getTypeSize(CAT->getElementType()) == 0)
4900 S += '0';
4901 else
4902 S += llvm::utostr(CAT->getSize().getZExtValue());
4903 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004904 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004905 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4906 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004907 S += '0';
4908 }
Mike Stump1eb44332009-09-09 15:08:12 +00004909
4910 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004911 false, ExpandStructures, FD);
4912 S += ']';
4913 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004914 return;
4915 }
Mike Stump1eb44332009-09-09 15:08:12 +00004916
John McCall183700f2009-09-21 23:43:11 +00004917 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004918 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004919 return;
4920 }
Mike Stump1eb44332009-09-09 15:08:12 +00004921
Ted Kremenek6217b802009-07-29 21:53:49 +00004922 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004923 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004924 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004925 // Anonymous structures print as '?'
4926 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4927 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004928 if (ClassTemplateSpecializationDecl *Spec
4929 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4930 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4931 std::string TemplateArgsStr
4932 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004933 TemplateArgs.data(),
4934 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004935 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004936
4937 S += TemplateArgsStr;
4938 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004939 } else {
4940 S += '?';
4941 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004942 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004943 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004944 if (!RDecl->isUnion()) {
4945 getObjCEncodingForStructureImpl(RDecl, S, FD);
4946 } else {
4947 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4948 FieldEnd = RDecl->field_end();
4949 Field != FieldEnd; ++Field) {
4950 if (FD) {
4951 S += '"';
4952 S += Field->getNameAsString();
4953 S += '"';
4954 }
Mike Stump1eb44332009-09-09 15:08:12 +00004955
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004956 // Special case bit-fields.
4957 if (Field->isBitField()) {
4958 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00004959 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004960 } else {
4961 QualType qt = Field->getType();
4962 getLegacyIntegralTypeEncoding(qt);
4963 getObjCEncodingForTypeImpl(qt, S, false, true,
4964 FD, /*OutermostType*/false,
4965 /*EncodingProperty*/false,
4966 /*StructField*/true);
4967 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004968 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004969 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004970 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004971 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004972 return;
4973 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004974
Douglas Gregor5471bc82011-09-08 17:18:35 +00004975 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004976 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004977 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004978 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004979 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004980 return;
4981 }
Mike Stump1eb44332009-09-09 15:08:12 +00004982
Bob Wilsondc8dab62011-11-30 01:57:58 +00004983 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004984 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004985 if (EncodeBlockParameters) {
4986 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4987
4988 S += '<';
4989 // Block return type
4990 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4991 ExpandPointedToStructures, ExpandStructures,
4992 FD,
4993 false /* OutermostType */,
4994 EncodingProperty,
4995 false /* StructField */,
4996 EncodeBlockParameters,
4997 EncodeClassNames);
4998 // Block self
4999 S += "@?";
5000 // Block parameters
5001 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5002 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5003 E = FPT->arg_type_end(); I && (I != E); ++I) {
5004 getObjCEncodingForTypeImpl(*I, S,
5005 ExpandPointedToStructures,
5006 ExpandStructures,
5007 FD,
5008 false /* OutermostType */,
5009 EncodingProperty,
5010 false /* StructField */,
5011 EncodeBlockParameters,
5012 EncodeClassNames);
5013 }
5014 }
5015 S += '>';
5016 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005017 return;
5018 }
Mike Stump1eb44332009-09-09 15:08:12 +00005019
John McCallc12c5bb2010-05-15 11:32:37 +00005020 // Ignore protocol qualifiers when mangling at this level.
5021 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
5022 T = OT->getBaseType();
5023
John McCall0953e762009-09-24 19:53:00 +00005024 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005025 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005026 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005027 S += '{';
5028 const IdentifierInfo *II = OI->getIdentifier();
5029 S += II->getName();
5030 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005031 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005032 DeepCollectObjCIvars(OI, true, Ivars);
5033 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005034 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005035 if (Field->isBitField())
5036 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005037 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005038 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005039 }
5040 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005041 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005042 }
Mike Stump1eb44332009-09-09 15:08:12 +00005043
John McCall183700f2009-09-21 23:43:11 +00005044 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00005045 if (OPT->isObjCIdType()) {
5046 S += '@';
5047 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005048 }
Mike Stump1eb44332009-09-09 15:08:12 +00005049
Steve Naroff27d20a22009-10-28 22:03:49 +00005050 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5051 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5052 // Since this is a binary compatibility issue, need to consult with runtime
5053 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005054 S += '#';
5055 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005056 }
Mike Stump1eb44332009-09-09 15:08:12 +00005057
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005058 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005059 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005060 ExpandPointedToStructures,
5061 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005062 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005063 // Note that we do extended encoding of protocol qualifer list
5064 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005065 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005066 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5067 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005068 S += '<';
5069 S += (*I)->getNameAsString();
5070 S += '>';
5071 }
5072 S += '"';
5073 }
5074 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005075 }
Mike Stump1eb44332009-09-09 15:08:12 +00005076
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005077 QualType PointeeTy = OPT->getPointeeType();
5078 if (!EncodingProperty &&
5079 isa<TypedefType>(PointeeTy.getTypePtr())) {
5080 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005081 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005082 // {...};
5083 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005084 getObjCEncodingForTypeImpl(PointeeTy, S,
5085 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005086 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00005087 return;
5088 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005089
5090 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005091 if (OPT->getInterfaceDecl() &&
5092 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005093 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005094 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005095 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5096 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005097 S += '<';
5098 S += (*I)->getNameAsString();
5099 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005100 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005101 S += '"';
5102 }
5103 return;
5104 }
Mike Stump1eb44332009-09-09 15:08:12 +00005105
John McCall532ec7b2010-05-17 23:56:34 +00005106 // gcc just blithely ignores member pointers.
5107 // TODO: maybe there should be a mangling for these
5108 if (T->getAs<MemberPointerType>())
5109 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005110
5111 if (T->isVectorType()) {
5112 // This matches gcc's encoding, even though technically it is
5113 // insufficient.
5114 // FIXME. We should do a better job than gcc.
5115 return;
5116 }
5117
David Blaikieb219cfc2011-09-23 05:06:16 +00005118 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005119}
5120
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005121void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5122 std::string &S,
5123 const FieldDecl *FD,
5124 bool includeVBases) const {
5125 assert(RDecl && "Expected non-null RecordDecl");
5126 assert(!RDecl->isUnion() && "Should not be called for unions");
5127 if (!RDecl->getDefinition())
5128 return;
5129
5130 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5131 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5132 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5133
5134 if (CXXRec) {
5135 for (CXXRecordDecl::base_class_iterator
5136 BI = CXXRec->bases_begin(),
5137 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5138 if (!BI->isVirtual()) {
5139 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005140 if (base->isEmpty())
5141 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005142 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005143 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5144 std::make_pair(offs, base));
5145 }
5146 }
5147 }
5148
5149 unsigned i = 0;
5150 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5151 FieldEnd = RDecl->field_end();
5152 Field != FieldEnd; ++Field, ++i) {
5153 uint64_t offs = layout.getFieldOffset(i);
5154 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005155 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005156 }
5157
5158 if (CXXRec && includeVBases) {
5159 for (CXXRecordDecl::base_class_iterator
5160 BI = CXXRec->vbases_begin(),
5161 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5162 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005163 if (base->isEmpty())
5164 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005165 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005166 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5167 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5168 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005169 }
5170 }
5171
5172 CharUnits size;
5173 if (CXXRec) {
5174 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5175 } else {
5176 size = layout.getSize();
5177 }
5178
5179 uint64_t CurOffs = 0;
5180 std::multimap<uint64_t, NamedDecl *>::iterator
5181 CurLayObj = FieldOrBaseOffsets.begin();
5182
Douglas Gregor58db7a52012-04-27 22:30:01 +00005183 if (CXXRec && CXXRec->isDynamicClass() &&
5184 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005185 if (FD) {
5186 S += "\"_vptr$";
5187 std::string recname = CXXRec->getNameAsString();
5188 if (recname.empty()) recname = "?";
5189 S += recname;
5190 S += '"';
5191 }
5192 S += "^^?";
5193 CurOffs += getTypeSize(VoidPtrTy);
5194 }
5195
5196 if (!RDecl->hasFlexibleArrayMember()) {
5197 // Mark the end of the structure.
5198 uint64_t offs = toBits(size);
5199 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5200 std::make_pair(offs, (NamedDecl*)0));
5201 }
5202
5203 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5204 assert(CurOffs <= CurLayObj->first);
5205
5206 if (CurOffs < CurLayObj->first) {
5207 uint64_t padding = CurLayObj->first - CurOffs;
5208 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5209 // packing/alignment of members is different that normal, in which case
5210 // the encoding will be out-of-sync with the real layout.
5211 // If the runtime switches to just consider the size of types without
5212 // taking into account alignment, we could make padding explicit in the
5213 // encoding (e.g. using arrays of chars). The encoding strings would be
5214 // longer then though.
5215 CurOffs += padding;
5216 }
5217
5218 NamedDecl *dcl = CurLayObj->second;
5219 if (dcl == 0)
5220 break; // reached end of structure.
5221
5222 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5223 // We expand the bases without their virtual bases since those are going
5224 // in the initial structure. Note that this differs from gcc which
5225 // expands virtual bases each time one is encountered in the hierarchy,
5226 // making the encoding type bigger than it really is.
5227 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005228 assert(!base->isEmpty());
5229 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005230 } else {
5231 FieldDecl *field = cast<FieldDecl>(dcl);
5232 if (FD) {
5233 S += '"';
5234 S += field->getNameAsString();
5235 S += '"';
5236 }
5237
5238 if (field->isBitField()) {
5239 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005240 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005241 } else {
5242 QualType qt = field->getType();
5243 getLegacyIntegralTypeEncoding(qt);
5244 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5245 /*OutermostType*/false,
5246 /*EncodingProperty*/false,
5247 /*StructField*/true);
5248 CurOffs += getTypeSize(field->getType());
5249 }
5250 }
5251 }
5252}
5253
Mike Stump1eb44332009-09-09 15:08:12 +00005254void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005255 std::string& S) const {
5256 if (QT & Decl::OBJC_TQ_In)
5257 S += 'n';
5258 if (QT & Decl::OBJC_TQ_Inout)
5259 S += 'N';
5260 if (QT & Decl::OBJC_TQ_Out)
5261 S += 'o';
5262 if (QT & Decl::OBJC_TQ_Bycopy)
5263 S += 'O';
5264 if (QT & Decl::OBJC_TQ_Byref)
5265 S += 'R';
5266 if (QT & Decl::OBJC_TQ_Oneway)
5267 S += 'V';
5268}
5269
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005270TypedefDecl *ASTContext::getObjCIdDecl() const {
5271 if (!ObjCIdDecl) {
5272 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5273 T = getObjCObjectPointerType(T);
5274 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5275 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5276 getTranslationUnitDecl(),
5277 SourceLocation(), SourceLocation(),
5278 &Idents.get("id"), IdInfo);
5279 }
5280
5281 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005282}
5283
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005284TypedefDecl *ASTContext::getObjCSelDecl() const {
5285 if (!ObjCSelDecl) {
5286 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5287 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5288 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5289 getTranslationUnitDecl(),
5290 SourceLocation(), SourceLocation(),
5291 &Idents.get("SEL"), SelInfo);
5292 }
5293 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005294}
5295
Douglas Gregor79d67262011-08-12 05:59:41 +00005296TypedefDecl *ASTContext::getObjCClassDecl() const {
5297 if (!ObjCClassDecl) {
5298 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5299 T = getObjCObjectPointerType(T);
5300 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5301 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5302 getTranslationUnitDecl(),
5303 SourceLocation(), SourceLocation(),
5304 &Idents.get("Class"), ClassInfo);
5305 }
5306
5307 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005308}
5309
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005310ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5311 if (!ObjCProtocolClassDecl) {
5312 ObjCProtocolClassDecl
5313 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5314 SourceLocation(),
5315 &Idents.get("Protocol"),
5316 /*PrevDecl=*/0,
5317 SourceLocation(), true);
5318 }
5319
5320 return ObjCProtocolClassDecl;
5321}
5322
Meador Ingec5613b22012-06-16 03:34:49 +00005323//===----------------------------------------------------------------------===//
5324// __builtin_va_list Construction Functions
5325//===----------------------------------------------------------------------===//
5326
5327static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5328 // typedef char* __builtin_va_list;
5329 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5330 TypeSourceInfo *TInfo
5331 = Context->getTrivialTypeSourceInfo(CharPtrType);
5332
5333 TypedefDecl *VaListTypeDecl
5334 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5335 Context->getTranslationUnitDecl(),
5336 SourceLocation(), SourceLocation(),
5337 &Context->Idents.get("__builtin_va_list"),
5338 TInfo);
5339 return VaListTypeDecl;
5340}
5341
5342static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5343 // typedef void* __builtin_va_list;
5344 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5345 TypeSourceInfo *TInfo
5346 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5347
5348 TypedefDecl *VaListTypeDecl
5349 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5350 Context->getTranslationUnitDecl(),
5351 SourceLocation(), SourceLocation(),
5352 &Context->Idents.get("__builtin_va_list"),
5353 TInfo);
5354 return VaListTypeDecl;
5355}
5356
5357static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5358 // typedef struct __va_list_tag {
5359 RecordDecl *VaListTagDecl;
5360
5361 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5362 Context->getTranslationUnitDecl(),
5363 &Context->Idents.get("__va_list_tag"));
5364 VaListTagDecl->startDefinition();
5365
5366 const size_t NumFields = 5;
5367 QualType FieldTypes[NumFields];
5368 const char *FieldNames[NumFields];
5369
5370 // unsigned char gpr;
5371 FieldTypes[0] = Context->UnsignedCharTy;
5372 FieldNames[0] = "gpr";
5373
5374 // unsigned char fpr;
5375 FieldTypes[1] = Context->UnsignedCharTy;
5376 FieldNames[1] = "fpr";
5377
5378 // unsigned short reserved;
5379 FieldTypes[2] = Context->UnsignedShortTy;
5380 FieldNames[2] = "reserved";
5381
5382 // void* overflow_arg_area;
5383 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5384 FieldNames[3] = "overflow_arg_area";
5385
5386 // void* reg_save_area;
5387 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5388 FieldNames[4] = "reg_save_area";
5389
5390 // Create fields
5391 for (unsigned i = 0; i < NumFields; ++i) {
5392 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5393 SourceLocation(),
5394 SourceLocation(),
5395 &Context->Idents.get(FieldNames[i]),
5396 FieldTypes[i], /*TInfo=*/0,
5397 /*BitWidth=*/0,
5398 /*Mutable=*/false,
5399 ICIS_NoInit);
5400 Field->setAccess(AS_public);
5401 VaListTagDecl->addDecl(Field);
5402 }
5403 VaListTagDecl->completeDefinition();
5404 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005405 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005406
5407 // } __va_list_tag;
5408 TypedefDecl *VaListTagTypedefDecl
5409 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5410 Context->getTranslationUnitDecl(),
5411 SourceLocation(), SourceLocation(),
5412 &Context->Idents.get("__va_list_tag"),
5413 Context->getTrivialTypeSourceInfo(VaListTagType));
5414 QualType VaListTagTypedefType =
5415 Context->getTypedefType(VaListTagTypedefDecl);
5416
5417 // typedef __va_list_tag __builtin_va_list[1];
5418 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5419 QualType VaListTagArrayType
5420 = Context->getConstantArrayType(VaListTagTypedefType,
5421 Size, ArrayType::Normal, 0);
5422 TypeSourceInfo *TInfo
5423 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5424 TypedefDecl *VaListTypedefDecl
5425 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5426 Context->getTranslationUnitDecl(),
5427 SourceLocation(), SourceLocation(),
5428 &Context->Idents.get("__builtin_va_list"),
5429 TInfo);
5430
5431 return VaListTypedefDecl;
5432}
5433
5434static TypedefDecl *
5435CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5436 // typedef struct __va_list_tag {
5437 RecordDecl *VaListTagDecl;
5438 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5439 Context->getTranslationUnitDecl(),
5440 &Context->Idents.get("__va_list_tag"));
5441 VaListTagDecl->startDefinition();
5442
5443 const size_t NumFields = 4;
5444 QualType FieldTypes[NumFields];
5445 const char *FieldNames[NumFields];
5446
5447 // unsigned gp_offset;
5448 FieldTypes[0] = Context->UnsignedIntTy;
5449 FieldNames[0] = "gp_offset";
5450
5451 // unsigned fp_offset;
5452 FieldTypes[1] = Context->UnsignedIntTy;
5453 FieldNames[1] = "fp_offset";
5454
5455 // void* overflow_arg_area;
5456 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5457 FieldNames[2] = "overflow_arg_area";
5458
5459 // void* reg_save_area;
5460 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5461 FieldNames[3] = "reg_save_area";
5462
5463 // Create fields
5464 for (unsigned i = 0; i < NumFields; ++i) {
5465 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5466 VaListTagDecl,
5467 SourceLocation(),
5468 SourceLocation(),
5469 &Context->Idents.get(FieldNames[i]),
5470 FieldTypes[i], /*TInfo=*/0,
5471 /*BitWidth=*/0,
5472 /*Mutable=*/false,
5473 ICIS_NoInit);
5474 Field->setAccess(AS_public);
5475 VaListTagDecl->addDecl(Field);
5476 }
5477 VaListTagDecl->completeDefinition();
5478 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005479 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005480
5481 // } __va_list_tag;
5482 TypedefDecl *VaListTagTypedefDecl
5483 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5484 Context->getTranslationUnitDecl(),
5485 SourceLocation(), SourceLocation(),
5486 &Context->Idents.get("__va_list_tag"),
5487 Context->getTrivialTypeSourceInfo(VaListTagType));
5488 QualType VaListTagTypedefType =
5489 Context->getTypedefType(VaListTagTypedefDecl);
5490
5491 // typedef __va_list_tag __builtin_va_list[1];
5492 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5493 QualType VaListTagArrayType
5494 = Context->getConstantArrayType(VaListTagTypedefType,
5495 Size, ArrayType::Normal,0);
5496 TypeSourceInfo *TInfo
5497 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5498 TypedefDecl *VaListTypedefDecl
5499 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5500 Context->getTranslationUnitDecl(),
5501 SourceLocation(), SourceLocation(),
5502 &Context->Idents.get("__builtin_va_list"),
5503 TInfo);
5504
5505 return VaListTypedefDecl;
5506}
5507
5508static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5509 // typedef int __builtin_va_list[4];
5510 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5511 QualType IntArrayType
5512 = Context->getConstantArrayType(Context->IntTy,
5513 Size, ArrayType::Normal, 0);
5514 TypedefDecl *VaListTypedefDecl
5515 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5516 Context->getTranslationUnitDecl(),
5517 SourceLocation(), SourceLocation(),
5518 &Context->Idents.get("__builtin_va_list"),
5519 Context->getTrivialTypeSourceInfo(IntArrayType));
5520
5521 return VaListTypedefDecl;
5522}
5523
Logan Chieneae5a8202012-10-10 06:56:20 +00005524static TypedefDecl *
5525CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5526 RecordDecl *VaListDecl;
5527 if (Context->getLangOpts().CPlusPlus) {
5528 // namespace std { struct __va_list {
5529 NamespaceDecl *NS;
5530 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5531 Context->getTranslationUnitDecl(),
5532 /*Inline*/false, SourceLocation(),
5533 SourceLocation(), &Context->Idents.get("std"),
5534 /*PrevDecl*/0);
5535
5536 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5537 Context->getTranslationUnitDecl(),
5538 SourceLocation(), SourceLocation(),
5539 &Context->Idents.get("__va_list"));
5540
5541 VaListDecl->setDeclContext(NS);
5542
5543 } else {
5544 // struct __va_list {
5545 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5546 Context->getTranslationUnitDecl(),
5547 &Context->Idents.get("__va_list"));
5548 }
5549
5550 VaListDecl->startDefinition();
5551
5552 // void * __ap;
5553 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5554 VaListDecl,
5555 SourceLocation(),
5556 SourceLocation(),
5557 &Context->Idents.get("__ap"),
5558 Context->getPointerType(Context->VoidTy),
5559 /*TInfo=*/0,
5560 /*BitWidth=*/0,
5561 /*Mutable=*/false,
5562 ICIS_NoInit);
5563 Field->setAccess(AS_public);
5564 VaListDecl->addDecl(Field);
5565
5566 // };
5567 VaListDecl->completeDefinition();
5568
5569 // typedef struct __va_list __builtin_va_list;
5570 TypeSourceInfo *TInfo
5571 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5572
5573 TypedefDecl *VaListTypeDecl
5574 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5575 Context->getTranslationUnitDecl(),
5576 SourceLocation(), SourceLocation(),
5577 &Context->Idents.get("__builtin_va_list"),
5578 TInfo);
5579
5580 return VaListTypeDecl;
5581}
5582
Meador Ingec5613b22012-06-16 03:34:49 +00005583static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5584 TargetInfo::BuiltinVaListKind Kind) {
5585 switch (Kind) {
5586 case TargetInfo::CharPtrBuiltinVaList:
5587 return CreateCharPtrBuiltinVaListDecl(Context);
5588 case TargetInfo::VoidPtrBuiltinVaList:
5589 return CreateVoidPtrBuiltinVaListDecl(Context);
5590 case TargetInfo::PowerABIBuiltinVaList:
5591 return CreatePowerABIBuiltinVaListDecl(Context);
5592 case TargetInfo::X86_64ABIBuiltinVaList:
5593 return CreateX86_64ABIBuiltinVaListDecl(Context);
5594 case TargetInfo::PNaClABIBuiltinVaList:
5595 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00005596 case TargetInfo::AAPCSABIBuiltinVaList:
5597 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00005598 }
5599
5600 llvm_unreachable("Unhandled __builtin_va_list type kind");
5601}
5602
5603TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5604 if (!BuiltinVaListDecl)
5605 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5606
5607 return BuiltinVaListDecl;
5608}
5609
Meador Ingefb40e3f2012-07-01 15:57:25 +00005610QualType ASTContext::getVaListTagType() const {
5611 // Force the creation of VaListTagTy by building the __builtin_va_list
5612 // declaration.
5613 if (VaListTagTy.isNull())
5614 (void) getBuiltinVaListDecl();
5615
5616 return VaListTagTy;
5617}
5618
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005619void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00005620 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00005621 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00005622
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005623 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00005624}
5625
John McCall0bd6feb2009-12-02 08:04:21 +00005626/// \brief Retrieve the template name that corresponds to a non-empty
5627/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00005628TemplateName
5629ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5630 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00005631 unsigned size = End - Begin;
5632 assert(size > 1 && "set is not overloaded!");
5633
5634 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5635 size * sizeof(FunctionTemplateDecl*));
5636 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5637
5638 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00005639 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00005640 NamedDecl *D = *I;
5641 assert(isa<FunctionTemplateDecl>(D) ||
5642 (isa<UsingShadowDecl>(D) &&
5643 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5644 *Storage++ = D;
5645 }
5646
5647 return TemplateName(OT);
5648}
5649
Douglas Gregor7532dc62009-03-30 22:58:21 +00005650/// \brief Retrieve the template name that represents a qualified
5651/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00005652TemplateName
5653ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5654 bool TemplateKeyword,
5655 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00005656 assert(NNS && "Missing nested-name-specifier in qualified template name");
5657
Douglas Gregor789b1f62010-02-04 18:10:26 +00005658 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00005659 llvm::FoldingSetNodeID ID;
5660 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5661
5662 void *InsertPos = 0;
5663 QualifiedTemplateName *QTN =
5664 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5665 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005666 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5667 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005668 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5669 }
5670
5671 return TemplateName(QTN);
5672}
5673
5674/// \brief Retrieve the template name that represents a dependent
5675/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00005676TemplateName
5677ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5678 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00005679 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005680 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005681
5682 llvm::FoldingSetNodeID ID;
5683 DependentTemplateName::Profile(ID, NNS, Name);
5684
5685 void *InsertPos = 0;
5686 DependentTemplateName *QTN =
5687 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5688
5689 if (QTN)
5690 return TemplateName(QTN);
5691
5692 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5693 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005694 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5695 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005696 } else {
5697 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00005698 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5699 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005700 DependentTemplateName *CheckQTN =
5701 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5702 assert(!CheckQTN && "Dependent type name canonicalization broken");
5703 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005704 }
5705
5706 DependentTemplateNames.InsertNode(QTN, InsertPos);
5707 return TemplateName(QTN);
5708}
5709
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005710/// \brief Retrieve the template name that represents a dependent
5711/// template name such as \c MetaFun::template operator+.
5712TemplateName
5713ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005714 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005715 assert((!NNS || NNS->isDependent()) &&
5716 "Nested name specifier must be dependent");
5717
5718 llvm::FoldingSetNodeID ID;
5719 DependentTemplateName::Profile(ID, NNS, Operator);
5720
5721 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005722 DependentTemplateName *QTN
5723 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005724
5725 if (QTN)
5726 return TemplateName(QTN);
5727
5728 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5729 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005730 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5731 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005732 } else {
5733 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00005734 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5735 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005736
5737 DependentTemplateName *CheckQTN
5738 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5739 assert(!CheckQTN && "Dependent template name canonicalization broken");
5740 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005741 }
5742
5743 DependentTemplateNames.InsertNode(QTN, InsertPos);
5744 return TemplateName(QTN);
5745}
5746
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005747TemplateName
John McCall14606042011-06-30 08:33:18 +00005748ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5749 TemplateName replacement) const {
5750 llvm::FoldingSetNodeID ID;
5751 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5752
5753 void *insertPos = 0;
5754 SubstTemplateTemplateParmStorage *subst
5755 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5756
5757 if (!subst) {
5758 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5759 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5760 }
5761
5762 return TemplateName(subst);
5763}
5764
5765TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005766ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5767 const TemplateArgument &ArgPack) const {
5768 ASTContext &Self = const_cast<ASTContext &>(*this);
5769 llvm::FoldingSetNodeID ID;
5770 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5771
5772 void *InsertPos = 0;
5773 SubstTemplateTemplateParmPackStorage *Subst
5774 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5775
5776 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005777 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005778 ArgPack.pack_size(),
5779 ArgPack.pack_begin());
5780 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5781 }
5782
5783 return TemplateName(Subst);
5784}
5785
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005786/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005787/// TargetInfo, produce the corresponding type. The unsigned @p Type
5788/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005789CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005790 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005791 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005792 case TargetInfo::SignedShort: return ShortTy;
5793 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5794 case TargetInfo::SignedInt: return IntTy;
5795 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5796 case TargetInfo::SignedLong: return LongTy;
5797 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5798 case TargetInfo::SignedLongLong: return LongLongTy;
5799 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5800 }
5801
David Blaikieb219cfc2011-09-23 05:06:16 +00005802 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005803}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005804
5805//===----------------------------------------------------------------------===//
5806// Type Predicates.
5807//===----------------------------------------------------------------------===//
5808
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005809/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5810/// garbage collection attribute.
5811///
John McCallae278a32011-01-12 00:34:59 +00005812Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00005813 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005814 return Qualifiers::GCNone;
5815
David Blaikie4e4d0842012-03-11 07:00:24 +00005816 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00005817 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5818
5819 // Default behaviour under objective-C's gc is for ObjC pointers
5820 // (or pointers to them) be treated as though they were declared
5821 // as __strong.
5822 if (GCAttrs == Qualifiers::GCNone) {
5823 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5824 return Qualifiers::Strong;
5825 else if (Ty->isPointerType())
5826 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5827 } else {
5828 // It's not valid to set GC attributes on anything that isn't a
5829 // pointer.
5830#ifndef NDEBUG
5831 QualType CT = Ty->getCanonicalTypeInternal();
5832 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5833 CT = AT->getElementType();
5834 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5835#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005836 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005837 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005838}
5839
Chris Lattner6ac46a42008-04-07 06:51:04 +00005840//===----------------------------------------------------------------------===//
5841// Type Compatibility Testing
5842//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005843
Mike Stump1eb44332009-09-09 15:08:12 +00005844/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005845/// compatible.
5846static bool areCompatVectorTypes(const VectorType *LHS,
5847 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005848 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005849 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005850 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005851}
5852
Douglas Gregor255210e2010-08-06 10:14:59 +00005853bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5854 QualType SecondVec) {
5855 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5856 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5857
5858 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5859 return true;
5860
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005861 // Treat Neon vector types and most AltiVec vector types as if they are the
5862 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005863 const VectorType *First = FirstVec->getAs<VectorType>();
5864 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005865 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005866 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005867 First->getVectorKind() != VectorType::AltiVecPixel &&
5868 First->getVectorKind() != VectorType::AltiVecBool &&
5869 Second->getVectorKind() != VectorType::AltiVecPixel &&
5870 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005871 return true;
5872
5873 return false;
5874}
5875
Steve Naroff4084c302009-07-23 01:01:38 +00005876//===----------------------------------------------------------------------===//
5877// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5878//===----------------------------------------------------------------------===//
5879
5880/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5881/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005882bool
5883ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5884 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005885 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00005886 return true;
5887 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5888 E = rProto->protocol_end(); PI != E; ++PI)
5889 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5890 return true;
5891 return false;
5892}
5893
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00005894/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00005895/// return true if lhs's protocols conform to rhs's protocol; false
5896/// otherwise.
5897bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5898 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5899 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5900 return false;
5901}
5902
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00005903/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
5904/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005905bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5906 QualType rhs) {
5907 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5908 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5909 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5910
5911 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5912 E = lhsQID->qual_end(); I != E; ++I) {
5913 bool match = false;
5914 ObjCProtocolDecl *lhsProto = *I;
5915 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5916 E = rhsOPT->qual_end(); J != E; ++J) {
5917 ObjCProtocolDecl *rhsProto = *J;
5918 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5919 match = true;
5920 break;
5921 }
5922 }
5923 if (!match)
5924 return false;
5925 }
5926 return true;
5927}
5928
Steve Naroff4084c302009-07-23 01:01:38 +00005929/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5930/// ObjCQualifiedIDType.
5931bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5932 bool compare) {
5933 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005934 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005935 lhs->isObjCIdType() || lhs->isObjCClassType())
5936 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005937 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005938 rhs->isObjCIdType() || rhs->isObjCClassType())
5939 return true;
5940
5941 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005942 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005943
Steve Naroff4084c302009-07-23 01:01:38 +00005944 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005945
Steve Naroff4084c302009-07-23 01:01:38 +00005946 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005947 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005948 // make sure we check the class hierarchy.
5949 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5950 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5951 E = lhsQID->qual_end(); I != E; ++I) {
5952 // when comparing an id<P> on lhs with a static type on rhs,
5953 // see if static class implements all of id's protocols, directly or
5954 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005955 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005956 return false;
5957 }
5958 }
5959 // If there are no qualifiers and no interface, we have an 'id'.
5960 return true;
5961 }
Mike Stump1eb44332009-09-09 15:08:12 +00005962 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005963 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5964 E = lhsQID->qual_end(); I != E; ++I) {
5965 ObjCProtocolDecl *lhsProto = *I;
5966 bool match = false;
5967
5968 // when comparing an id<P> on lhs with a static type on rhs,
5969 // see if static class implements all of id's protocols, directly or
5970 // through its super class and categories.
5971 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5972 E = rhsOPT->qual_end(); J != E; ++J) {
5973 ObjCProtocolDecl *rhsProto = *J;
5974 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5975 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5976 match = true;
5977 break;
5978 }
5979 }
Mike Stump1eb44332009-09-09 15:08:12 +00005980 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005981 // make sure we check the class hierarchy.
5982 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5983 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5984 E = lhsQID->qual_end(); I != E; ++I) {
5985 // when comparing an id<P> on lhs with a static type on rhs,
5986 // see if static class implements all of id's protocols, directly or
5987 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005988 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005989 match = true;
5990 break;
5991 }
5992 }
5993 }
5994 if (!match)
5995 return false;
5996 }
Mike Stump1eb44332009-09-09 15:08:12 +00005997
Steve Naroff4084c302009-07-23 01:01:38 +00005998 return true;
5999 }
Mike Stump1eb44332009-09-09 15:08:12 +00006000
Steve Naroff4084c302009-07-23 01:01:38 +00006001 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6002 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6003
Mike Stump1eb44332009-09-09 15:08:12 +00006004 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006005 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006006 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006007 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6008 E = lhsOPT->qual_end(); I != E; ++I) {
6009 ObjCProtocolDecl *lhsProto = *I;
6010 bool match = false;
6011
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006012 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006013 // see if static class implements all of id's protocols, directly or
6014 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006015 // First, lhs protocols in the qualifier list must be found, direct
6016 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006017 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6018 E = rhsQID->qual_end(); J != E; ++J) {
6019 ObjCProtocolDecl *rhsProto = *J;
6020 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6021 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6022 match = true;
6023 break;
6024 }
6025 }
6026 if (!match)
6027 return false;
6028 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006029
6030 // Static class's protocols, or its super class or category protocols
6031 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6032 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6033 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6034 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6035 // This is rather dubious but matches gcc's behavior. If lhs has
6036 // no type qualifier and its class has no static protocol(s)
6037 // assume that it is mismatch.
6038 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6039 return false;
6040 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6041 LHSInheritedProtocols.begin(),
6042 E = LHSInheritedProtocols.end(); I != E; ++I) {
6043 bool match = false;
6044 ObjCProtocolDecl *lhsProto = (*I);
6045 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6046 E = rhsQID->qual_end(); J != E; ++J) {
6047 ObjCProtocolDecl *rhsProto = *J;
6048 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6049 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6050 match = true;
6051 break;
6052 }
6053 }
6054 if (!match)
6055 return false;
6056 }
6057 }
Steve Naroff4084c302009-07-23 01:01:38 +00006058 return true;
6059 }
6060 return false;
6061}
6062
Eli Friedman3d815e72008-08-22 00:56:42 +00006063/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006064/// compatible for assignment from RHS to LHS. This handles validation of any
6065/// protocol qualifiers on the LHS or RHS.
6066///
Steve Naroff14108da2009-07-10 23:34:53 +00006067bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6068 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006069 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6070 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6071
Steve Naroffde2e22d2009-07-15 18:40:39 +00006072 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006073 if (LHS->isObjCUnqualifiedIdOrClass() ||
6074 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006075 return true;
6076
John McCallc12c5bb2010-05-15 11:32:37 +00006077 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006078 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6079 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006080 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006081
6082 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6083 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6084 QualType(RHSOPT,0));
6085
John McCallc12c5bb2010-05-15 11:32:37 +00006086 // If we have 2 user-defined types, fall into that path.
6087 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006088 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006089
Steve Naroff4084c302009-07-23 01:01:38 +00006090 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006091}
6092
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006093/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006094/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006095/// arguments in block literals. When passed as arguments, passing 'A*' where
6096/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6097/// not OK. For the return type, the opposite is not OK.
6098bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6099 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006100 const ObjCObjectPointerType *RHSOPT,
6101 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006102 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006103 return true;
6104
6105 if (LHSOPT->isObjCBuiltinType()) {
6106 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6107 }
6108
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006109 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006110 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6111 QualType(RHSOPT,0),
6112 false);
6113
6114 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6115 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6116 if (LHS && RHS) { // We have 2 user-defined types.
6117 if (LHS != RHS) {
6118 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006119 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006120 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006121 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006122 }
6123 else
6124 return true;
6125 }
6126 return false;
6127}
6128
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006129/// getIntersectionOfProtocols - This routine finds the intersection of set
6130/// of protocols inherited from two distinct objective-c pointer objects.
6131/// It is used to build composite qualifier list of the composite type of
6132/// the conditional expression involving two objective-c pointer objects.
6133static
6134void getIntersectionOfProtocols(ASTContext &Context,
6135 const ObjCObjectPointerType *LHSOPT,
6136 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006137 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006138
John McCallc12c5bb2010-05-15 11:32:37 +00006139 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6140 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6141 assert(LHS->getInterface() && "LHS must have an interface base");
6142 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006143
6144 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6145 unsigned LHSNumProtocols = LHS->getNumProtocols();
6146 if (LHSNumProtocols > 0)
6147 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6148 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006149 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006150 Context.CollectInheritedProtocols(LHS->getInterface(),
6151 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006152 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6153 LHSInheritedProtocols.end());
6154 }
6155
6156 unsigned RHSNumProtocols = RHS->getNumProtocols();
6157 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006158 ObjCProtocolDecl **RHSProtocols =
6159 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006160 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6161 if (InheritedProtocolSet.count(RHSProtocols[i]))
6162 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006163 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006164 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006165 Context.CollectInheritedProtocols(RHS->getInterface(),
6166 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006167 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6168 RHSInheritedProtocols.begin(),
6169 E = RHSInheritedProtocols.end(); I != E; ++I)
6170 if (InheritedProtocolSet.count((*I)))
6171 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006172 }
6173}
6174
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006175/// areCommonBaseCompatible - Returns common base class of the two classes if
6176/// one found. Note that this is O'2 algorithm. But it will be called as the
6177/// last type comparison in a ?-exp of ObjC pointer types before a
6178/// warning is issued. So, its invokation is extremely rare.
6179QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006180 const ObjCObjectPointerType *Lptr,
6181 const ObjCObjectPointerType *Rptr) {
6182 const ObjCObjectType *LHS = Lptr->getObjectType();
6183 const ObjCObjectType *RHS = Rptr->getObjectType();
6184 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6185 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006186 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006187 return QualType();
6188
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006189 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006190 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006191 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006192 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006193 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6194
6195 QualType Result = QualType(LHS, 0);
6196 if (!Protocols.empty())
6197 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6198 Result = getObjCObjectPointerType(Result);
6199 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006200 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006201 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006202
6203 return QualType();
6204}
6205
John McCallc12c5bb2010-05-15 11:32:37 +00006206bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6207 const ObjCObjectType *RHS) {
6208 assert(LHS->getInterface() && "LHS is not an interface type");
6209 assert(RHS->getInterface() && "RHS is not an interface type");
6210
Chris Lattner6ac46a42008-04-07 06:51:04 +00006211 // Verify that the base decls are compatible: the RHS must be a subclass of
6212 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006213 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006214 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006215
Chris Lattner6ac46a42008-04-07 06:51:04 +00006216 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6217 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006218 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006219 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006220
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006221 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6222 // more detailed analysis is required.
6223 if (RHS->getNumProtocols() == 0) {
6224 // OK, if LHS is a superclass of RHS *and*
6225 // this superclass is assignment compatible with LHS.
6226 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006227 bool IsSuperClass =
6228 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6229 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006230 // OK if conversion of LHS to SuperClass results in narrowing of types
6231 // ; i.e., SuperClass may implement at least one of the protocols
6232 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6233 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6234 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006235 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006236 // If super class has no protocols, it is not a match.
6237 if (SuperClassInheritedProtocols.empty())
6238 return false;
6239
6240 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6241 LHSPE = LHS->qual_end();
6242 LHSPI != LHSPE; LHSPI++) {
6243 bool SuperImplementsProtocol = false;
6244 ObjCProtocolDecl *LHSProto = (*LHSPI);
6245
6246 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6247 SuperClassInheritedProtocols.begin(),
6248 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6249 ObjCProtocolDecl *SuperClassProto = (*I);
6250 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6251 SuperImplementsProtocol = true;
6252 break;
6253 }
6254 }
6255 if (!SuperImplementsProtocol)
6256 return false;
6257 }
6258 return true;
6259 }
6260 return false;
6261 }
Mike Stump1eb44332009-09-09 15:08:12 +00006262
John McCallc12c5bb2010-05-15 11:32:37 +00006263 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6264 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006265 LHSPI != LHSPE; LHSPI++) {
6266 bool RHSImplementsProtocol = false;
6267
6268 // If the RHS doesn't implement the protocol on the left, the types
6269 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006270 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6271 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006272 RHSPI != RHSPE; RHSPI++) {
6273 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006274 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006275 break;
6276 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006277 }
6278 // FIXME: For better diagnostics, consider passing back the protocol name.
6279 if (!RHSImplementsProtocol)
6280 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006281 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006282 // The RHS implements all protocols listed on the LHS.
6283 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006284}
6285
Steve Naroff389bf462009-02-12 17:52:19 +00006286bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6287 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006288 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6289 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006290
Steve Naroff14108da2009-07-10 23:34:53 +00006291 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006292 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006293
6294 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6295 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006296}
6297
Douglas Gregor569c3162010-08-07 11:51:51 +00006298bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6299 return canAssignObjCInterfaces(
6300 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6301 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6302}
6303
Mike Stump1eb44332009-09-09 15:08:12 +00006304/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006305/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006306/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006307/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006308bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6309 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006310 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006311 return hasSameType(LHS, RHS);
6312
Douglas Gregor447234d2010-07-29 15:18:02 +00006313 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006314}
6315
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006316bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006317 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006318}
6319
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006320bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6321 return !mergeTypes(LHS, RHS, true).isNull();
6322}
6323
Peter Collingbourne48466752010-10-24 18:30:18 +00006324/// mergeTransparentUnionType - if T is a transparent union type and a member
6325/// of T is compatible with SubType, return the merged type, else return
6326/// QualType()
6327QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6328 bool OfBlockPointer,
6329 bool Unqualified) {
6330 if (const RecordType *UT = T->getAsUnionType()) {
6331 RecordDecl *UD = UT->getDecl();
6332 if (UD->hasAttr<TransparentUnionAttr>()) {
6333 for (RecordDecl::field_iterator it = UD->field_begin(),
6334 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006335 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006336 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6337 if (!MT.isNull())
6338 return MT;
6339 }
6340 }
6341 }
6342
6343 return QualType();
6344}
6345
6346/// mergeFunctionArgumentTypes - merge two types which appear as function
6347/// argument types
6348QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6349 bool OfBlockPointer,
6350 bool Unqualified) {
6351 // GNU extension: two types are compatible if they appear as a function
6352 // argument, one of the types is a transparent union type and the other
6353 // type is compatible with a union member
6354 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6355 Unqualified);
6356 if (!lmerge.isNull())
6357 return lmerge;
6358
6359 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6360 Unqualified);
6361 if (!rmerge.isNull())
6362 return rmerge;
6363
6364 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6365}
6366
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006367QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006368 bool OfBlockPointer,
6369 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006370 const FunctionType *lbase = lhs->getAs<FunctionType>();
6371 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006372 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6373 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006374 bool allLTypes = true;
6375 bool allRTypes = true;
6376
6377 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006378 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006379 if (OfBlockPointer) {
6380 QualType RHS = rbase->getResultType();
6381 QualType LHS = lbase->getResultType();
6382 bool UnqualifiedResult = Unqualified;
6383 if (!UnqualifiedResult)
6384 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006385 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006386 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006387 else
John McCall8cc246c2010-12-15 01:06:38 +00006388 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6389 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006390 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006391
6392 if (Unqualified)
6393 retType = retType.getUnqualifiedType();
6394
6395 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6396 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6397 if (Unqualified) {
6398 LRetType = LRetType.getUnqualifiedType();
6399 RRetType = RRetType.getUnqualifiedType();
6400 }
6401
6402 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006403 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006404 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006405 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006406
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006407 // FIXME: double check this
6408 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6409 // rbase->getRegParmAttr() != 0 &&
6410 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006411 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6412 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006413
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006414 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006415 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006416 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006417
John McCall8cc246c2010-12-15 01:06:38 +00006418 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006419 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6420 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006421 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6422 return QualType();
6423
John McCallf85e1932011-06-15 23:02:42 +00006424 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6425 return QualType();
6426
Fariborz Jahanian53c81672011-10-05 00:05:34 +00006427 // functypes which return are preferred over those that do not.
6428 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6429 allLTypes = false;
6430 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6431 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006432 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6433 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006434
John McCallf85e1932011-06-15 23:02:42 +00006435 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006436
Eli Friedman3d815e72008-08-22 00:56:42 +00006437 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006438 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6439 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006440 unsigned lproto_nargs = lproto->getNumArgs();
6441 unsigned rproto_nargs = rproto->getNumArgs();
6442
6443 // Compatible functions must have the same number of arguments
6444 if (lproto_nargs != rproto_nargs)
6445 return QualType();
6446
6447 // Variadic and non-variadic functions aren't compatible
6448 if (lproto->isVariadic() != rproto->isVariadic())
6449 return QualType();
6450
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006451 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6452 return QualType();
6453
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006454 if (LangOpts.ObjCAutoRefCount &&
6455 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6456 return QualType();
6457
Eli Friedman3d815e72008-08-22 00:56:42 +00006458 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006459 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006460 for (unsigned i = 0; i < lproto_nargs; i++) {
6461 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6462 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006463 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6464 OfBlockPointer,
6465 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006466 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006467
6468 if (Unqualified)
6469 argtype = argtype.getUnqualifiedType();
6470
Eli Friedman3d815e72008-08-22 00:56:42 +00006471 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006472 if (Unqualified) {
6473 largtype = largtype.getUnqualifiedType();
6474 rargtype = rargtype.getUnqualifiedType();
6475 }
6476
Chris Lattner61710852008-10-05 17:34:18 +00006477 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6478 allLTypes = false;
6479 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6480 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006481 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006482
Eli Friedman3d815e72008-08-22 00:56:42 +00006483 if (allLTypes) return lhs;
6484 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006485
6486 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6487 EPI.ExtInfo = einfo;
6488 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006489 }
6490
6491 if (lproto) allRTypes = false;
6492 if (rproto) allLTypes = false;
6493
Douglas Gregor72564e72009-02-26 23:50:07 +00006494 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00006495 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00006496 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006497 if (proto->isVariadic()) return QualType();
6498 // Check that the types are compatible with the types that
6499 // would result from default argument promotions (C99 6.7.5.3p15).
6500 // The only types actually affected are promotable integer
6501 // types and floats, which would be passed as a different
6502 // type depending on whether the prototype is visible.
6503 unsigned proto_nargs = proto->getNumArgs();
6504 for (unsigned i = 0; i < proto_nargs; ++i) {
6505 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006506
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006507 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006508 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006509 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6510 argTy = Enum->getDecl()->getIntegerType();
6511 if (argTy.isNull())
6512 return QualType();
6513 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006514
Eli Friedman3d815e72008-08-22 00:56:42 +00006515 if (argTy->isPromotableIntegerType() ||
6516 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6517 return QualType();
6518 }
6519
6520 if (allLTypes) return lhs;
6521 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006522
6523 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6524 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00006525 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006526 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006527 }
6528
6529 if (allLTypes) return lhs;
6530 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00006531 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00006532}
6533
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006534QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00006535 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006536 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00006537 // C++ [expr]: If an expression initially has the type "reference to T", the
6538 // type is adjusted to "T" prior to any further analysis, the expression
6539 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006540 // expression is an lvalue unless the reference is an rvalue reference and
6541 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006542 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6543 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00006544
6545 if (Unqualified) {
6546 LHS = LHS.getUnqualifiedType();
6547 RHS = RHS.getUnqualifiedType();
6548 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006549
Eli Friedman3d815e72008-08-22 00:56:42 +00006550 QualType LHSCan = getCanonicalType(LHS),
6551 RHSCan = getCanonicalType(RHS);
6552
6553 // If two types are identical, they are compatible.
6554 if (LHSCan == RHSCan)
6555 return LHS;
6556
John McCall0953e762009-09-24 19:53:00 +00006557 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006558 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6559 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00006560 if (LQuals != RQuals) {
6561 // If any of these qualifiers are different, we have a type
6562 // mismatch.
6563 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00006564 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6565 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00006566 return QualType();
6567
6568 // Exactly one GC qualifier difference is allowed: __strong is
6569 // okay if the other type has no GC qualifier but is an Objective
6570 // C object pointer (i.e. implicitly strong by default). We fix
6571 // this by pretending that the unqualified type was actually
6572 // qualified __strong.
6573 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6574 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6575 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6576
6577 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6578 return QualType();
6579
6580 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6581 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6582 }
6583 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6584 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6585 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006586 return QualType();
John McCall0953e762009-09-24 19:53:00 +00006587 }
6588
6589 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00006590
Eli Friedman852d63b2009-06-01 01:22:52 +00006591 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6592 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00006593
Chris Lattner1adb8832008-01-14 05:45:46 +00006594 // We want to consider the two function types to be the same for these
6595 // comparisons, just force one to the other.
6596 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6597 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00006598
6599 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00006600 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6601 LHSClass = Type::ConstantArray;
6602 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6603 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00006604
John McCallc12c5bb2010-05-15 11:32:37 +00006605 // ObjCInterfaces are just specialized ObjCObjects.
6606 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6607 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6608
Nate Begeman213541a2008-04-18 23:10:10 +00006609 // Canonicalize ExtVector -> Vector.
6610 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6611 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00006612
Chris Lattnera36a61f2008-04-07 05:43:21 +00006613 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006614 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00006615 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00006616 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00006617 // Compatibility is based on the underlying type, not the promotion
6618 // type.
John McCall183700f2009-09-21 23:43:11 +00006619 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006620 QualType TINT = ETy->getDecl()->getIntegerType();
6621 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006622 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006623 }
John McCall183700f2009-09-21 23:43:11 +00006624 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006625 QualType TINT = ETy->getDecl()->getIntegerType();
6626 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006627 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006628 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006629 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00006630 if (OfBlockPointer && !BlockReturnType) {
6631 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6632 return LHS;
6633 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6634 return RHS;
6635 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006636
Eli Friedman3d815e72008-08-22 00:56:42 +00006637 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006638 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006639
Steve Naroff4a746782008-01-09 22:43:08 +00006640 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006641 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00006642#define TYPE(Class, Base)
6643#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00006644#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00006645#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6646#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6647#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00006648 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00006649
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006650 case Type::LValueReference:
6651 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00006652 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00006653 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00006654
John McCallc12c5bb2010-05-15 11:32:37 +00006655 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00006656 case Type::IncompleteArray:
6657 case Type::VariableArray:
6658 case Type::FunctionProto:
6659 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00006660 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00006661
Chris Lattner1adb8832008-01-14 05:45:46 +00006662 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00006663 {
6664 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006665 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6666 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006667 if (Unqualified) {
6668 LHSPointee = LHSPointee.getUnqualifiedType();
6669 RHSPointee = RHSPointee.getUnqualifiedType();
6670 }
6671 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6672 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006673 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00006674 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006675 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00006676 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006677 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006678 return getPointerType(ResultType);
6679 }
Steve Naroffc0febd52008-12-10 17:49:55 +00006680 case Type::BlockPointer:
6681 {
6682 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006683 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6684 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006685 if (Unqualified) {
6686 LHSPointee = LHSPointee.getUnqualifiedType();
6687 RHSPointee = RHSPointee.getUnqualifiedType();
6688 }
6689 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6690 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006691 if (ResultType.isNull()) return QualType();
6692 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6693 return LHS;
6694 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6695 return RHS;
6696 return getBlockPointerType(ResultType);
6697 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006698 case Type::Atomic:
6699 {
6700 // Merge two pointer types, while trying to preserve typedef info
6701 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6702 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6703 if (Unqualified) {
6704 LHSValue = LHSValue.getUnqualifiedType();
6705 RHSValue = RHSValue.getUnqualifiedType();
6706 }
6707 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6708 Unqualified);
6709 if (ResultType.isNull()) return QualType();
6710 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6711 return LHS;
6712 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6713 return RHS;
6714 return getAtomicType(ResultType);
6715 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006716 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006717 {
6718 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6719 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6720 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6721 return QualType();
6722
6723 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6724 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006725 if (Unqualified) {
6726 LHSElem = LHSElem.getUnqualifiedType();
6727 RHSElem = RHSElem.getUnqualifiedType();
6728 }
6729
6730 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006731 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006732 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6733 return LHS;
6734 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6735 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006736 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6737 ArrayType::ArraySizeModifier(), 0);
6738 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6739 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006740 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6741 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006742 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6743 return LHS;
6744 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6745 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006746 if (LVAT) {
6747 // FIXME: This isn't correct! But tricky to implement because
6748 // the array's size has to be the size of LHS, but the type
6749 // has to be different.
6750 return LHS;
6751 }
6752 if (RVAT) {
6753 // FIXME: This isn't correct! But tricky to implement because
6754 // the array's size has to be the size of RHS, but the type
6755 // has to be different.
6756 return RHS;
6757 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006758 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6759 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006760 return getIncompleteArrayType(ResultType,
6761 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006762 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006763 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006764 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006765 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006766 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006767 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006768 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006769 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006770 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006771 case Type::Complex:
6772 // Distinct complex types are incompatible.
6773 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006774 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006775 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006776 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6777 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006778 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006779 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006780 case Type::ObjCObject: {
6781 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006782 // FIXME: This should be type compatibility, e.g. whether
6783 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006784 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6785 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6786 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006787 return LHS;
6788
Eli Friedman3d815e72008-08-22 00:56:42 +00006789 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006790 }
Steve Naroff14108da2009-07-10 23:34:53 +00006791 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006792 if (OfBlockPointer) {
6793 if (canAssignObjCInterfacesInBlockPointer(
6794 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006795 RHS->getAs<ObjCObjectPointerType>(),
6796 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006797 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006798 return QualType();
6799 }
John McCall183700f2009-09-21 23:43:11 +00006800 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6801 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006802 return LHS;
6803
Steve Naroffbc76dd02008-12-10 22:14:21 +00006804 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006805 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006806 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006807
David Blaikie7530c032012-01-17 06:56:22 +00006808 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006809}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006810
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006811bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6812 const FunctionProtoType *FromFunctionType,
6813 const FunctionProtoType *ToFunctionType) {
6814 if (FromFunctionType->hasAnyConsumedArgs() !=
6815 ToFunctionType->hasAnyConsumedArgs())
6816 return false;
6817 FunctionProtoType::ExtProtoInfo FromEPI =
6818 FromFunctionType->getExtProtoInfo();
6819 FunctionProtoType::ExtProtoInfo ToEPI =
6820 ToFunctionType->getExtProtoInfo();
6821 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6822 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6823 ArgIdx != NumArgs; ++ArgIdx) {
6824 if (FromEPI.ConsumedArguments[ArgIdx] !=
6825 ToEPI.ConsumedArguments[ArgIdx])
6826 return false;
6827 }
6828 return true;
6829}
6830
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006831/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6832/// 'RHS' attributes and returns the merged version; including for function
6833/// return types.
6834QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6835 QualType LHSCan = getCanonicalType(LHS),
6836 RHSCan = getCanonicalType(RHS);
6837 // If two types are identical, they are compatible.
6838 if (LHSCan == RHSCan)
6839 return LHS;
6840 if (RHSCan->isFunctionType()) {
6841 if (!LHSCan->isFunctionType())
6842 return QualType();
6843 QualType OldReturnType =
6844 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6845 QualType NewReturnType =
6846 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6847 QualType ResReturnType =
6848 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6849 if (ResReturnType.isNull())
6850 return QualType();
6851 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6852 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6853 // In either case, use OldReturnType to build the new function type.
6854 const FunctionType *F = LHS->getAs<FunctionType>();
6855 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006856 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6857 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006858 QualType ResultType
6859 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006860 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006861 return ResultType;
6862 }
6863 }
6864 return QualType();
6865 }
6866
6867 // If the qualifiers are different, the types can still be merged.
6868 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6869 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6870 if (LQuals != RQuals) {
6871 // If any of these qualifiers are different, we have a type mismatch.
6872 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6873 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6874 return QualType();
6875
6876 // Exactly one GC qualifier difference is allowed: __strong is
6877 // okay if the other type has no GC qualifier but is an Objective
6878 // C object pointer (i.e. implicitly strong by default). We fix
6879 // this by pretending that the unqualified type was actually
6880 // qualified __strong.
6881 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6882 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6883 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6884
6885 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6886 return QualType();
6887
6888 if (GC_L == Qualifiers::Strong)
6889 return LHS;
6890 if (GC_R == Qualifiers::Strong)
6891 return RHS;
6892 return QualType();
6893 }
6894
6895 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6896 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6897 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6898 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6899 if (ResQT == LHSBaseQT)
6900 return LHS;
6901 if (ResQT == RHSBaseQT)
6902 return RHS;
6903 }
6904 return QualType();
6905}
6906
Chris Lattner5426bf62008-04-07 07:01:58 +00006907//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006908// Integer Predicates
6909//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006910
Jay Foad4ba2a172011-01-12 09:06:06 +00006911unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006912 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006913 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006914 if (T->isBooleanType())
6915 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006916 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006917 return (unsigned)getTypeSize(T);
6918}
6919
Abramo Bagnara762f1592012-09-09 10:21:24 +00006920QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00006921 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006922
6923 // Turn <4 x signed int> -> <4 x unsigned int>
6924 if (const VectorType *VTy = T->getAs<VectorType>())
6925 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006926 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006927
6928 // For enums, we return the unsigned version of the base type.
6929 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006930 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006931
6932 const BuiltinType *BTy = T->getAs<BuiltinType>();
6933 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006934 switch (BTy->getKind()) {
6935 case BuiltinType::Char_S:
6936 case BuiltinType::SChar:
6937 return UnsignedCharTy;
6938 case BuiltinType::Short:
6939 return UnsignedShortTy;
6940 case BuiltinType::Int:
6941 return UnsignedIntTy;
6942 case BuiltinType::Long:
6943 return UnsignedLongTy;
6944 case BuiltinType::LongLong:
6945 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006946 case BuiltinType::Int128:
6947 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006948 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006949 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006950 }
6951}
6952
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006953ASTMutationListener::~ASTMutationListener() { }
6954
Chris Lattner86df27b2009-06-14 00:45:47 +00006955
6956//===----------------------------------------------------------------------===//
6957// Builtin Type Computation
6958//===----------------------------------------------------------------------===//
6959
6960/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006961/// pointer over the consumed characters. This returns the resultant type. If
6962/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6963/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6964/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006965///
6966/// RequiresICE is filled in on return to indicate whether the value is required
6967/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006968static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006969 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006970 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006971 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006972 // Modifiers.
6973 int HowLong = 0;
6974 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006975 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006976
Chris Lattner33daae62010-10-01 22:42:38 +00006977 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006978 bool Done = false;
6979 while (!Done) {
6980 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006981 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006982 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006983 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006984 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006985 case 'S':
6986 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6987 assert(!Signed && "Can't use 'S' modifier multiple times!");
6988 Signed = true;
6989 break;
6990 case 'U':
6991 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6992 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6993 Unsigned = true;
6994 break;
6995 case 'L':
6996 assert(HowLong <= 2 && "Can't have LLLL modifier");
6997 ++HowLong;
6998 break;
6999 }
7000 }
7001
7002 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007003
Chris Lattner86df27b2009-06-14 00:45:47 +00007004 // Read the base type.
7005 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007006 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007007 case 'v':
7008 assert(HowLong == 0 && !Signed && !Unsigned &&
7009 "Bad modifiers used with 'v'!");
7010 Type = Context.VoidTy;
7011 break;
7012 case 'f':
7013 assert(HowLong == 0 && !Signed && !Unsigned &&
7014 "Bad modifiers used with 'f'!");
7015 Type = Context.FloatTy;
7016 break;
7017 case 'd':
7018 assert(HowLong < 2 && !Signed && !Unsigned &&
7019 "Bad modifiers used with 'd'!");
7020 if (HowLong)
7021 Type = Context.LongDoubleTy;
7022 else
7023 Type = Context.DoubleTy;
7024 break;
7025 case 's':
7026 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7027 if (Unsigned)
7028 Type = Context.UnsignedShortTy;
7029 else
7030 Type = Context.ShortTy;
7031 break;
7032 case 'i':
7033 if (HowLong == 3)
7034 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7035 else if (HowLong == 2)
7036 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7037 else if (HowLong == 1)
7038 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7039 else
7040 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7041 break;
7042 case 'c':
7043 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7044 if (Signed)
7045 Type = Context.SignedCharTy;
7046 else if (Unsigned)
7047 Type = Context.UnsignedCharTy;
7048 else
7049 Type = Context.CharTy;
7050 break;
7051 case 'b': // boolean
7052 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7053 Type = Context.BoolTy;
7054 break;
7055 case 'z': // size_t.
7056 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7057 Type = Context.getSizeType();
7058 break;
7059 case 'F':
7060 Type = Context.getCFConstantStringType();
7061 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007062 case 'G':
7063 Type = Context.getObjCIdType();
7064 break;
7065 case 'H':
7066 Type = Context.getObjCSelType();
7067 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007068 case 'a':
7069 Type = Context.getBuiltinVaListType();
7070 assert(!Type.isNull() && "builtin va list type not initialized!");
7071 break;
7072 case 'A':
7073 // This is a "reference" to a va_list; however, what exactly
7074 // this means depends on how va_list is defined. There are two
7075 // different kinds of va_list: ones passed by value, and ones
7076 // passed by reference. An example of a by-value va_list is
7077 // x86, where va_list is a char*. An example of by-ref va_list
7078 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7079 // we want this argument to be a char*&; for x86-64, we want
7080 // it to be a __va_list_tag*.
7081 Type = Context.getBuiltinVaListType();
7082 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007083 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007084 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007085 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007086 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007087 break;
7088 case 'V': {
7089 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007090 unsigned NumElements = strtoul(Str, &End, 10);
7091 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007092 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007093
Chris Lattner14e0e742010-10-01 22:53:11 +00007094 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7095 RequiresICE, false);
7096 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007097
7098 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007099 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007100 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007101 break;
7102 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007103 case 'E': {
7104 char *End;
7105
7106 unsigned NumElements = strtoul(Str, &End, 10);
7107 assert(End != Str && "Missing vector size");
7108
7109 Str = End;
7110
7111 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7112 false);
7113 Type = Context.getExtVectorType(ElementType, NumElements);
7114 break;
7115 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007116 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007117 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7118 false);
7119 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007120 Type = Context.getComplexType(ElementType);
7121 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007122 }
7123 case 'Y' : {
7124 Type = Context.getPointerDiffType();
7125 break;
7126 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007127 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007128 Type = Context.getFILEType();
7129 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007130 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007131 return QualType();
7132 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007133 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007134 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007135 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007136 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007137 else
7138 Type = Context.getjmp_bufType();
7139
Mike Stumpfd612db2009-07-28 23:47:15 +00007140 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007141 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007142 return QualType();
7143 }
7144 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007145 case 'K':
7146 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7147 Type = Context.getucontext_tType();
7148
7149 if (Type.isNull()) {
7150 Error = ASTContext::GE_Missing_ucontext;
7151 return QualType();
7152 }
7153 break;
Mike Stump782fa302009-07-28 02:25:19 +00007154 }
Mike Stump1eb44332009-09-09 15:08:12 +00007155
Chris Lattner33daae62010-10-01 22:42:38 +00007156 // If there are modifiers and if we're allowed to parse them, go for it.
7157 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007158 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007159 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007160 default: Done = true; --Str; break;
7161 case '*':
7162 case '&': {
7163 // Both pointers and references can have their pointee types
7164 // qualified with an address space.
7165 char *End;
7166 unsigned AddrSpace = strtoul(Str, &End, 10);
7167 if (End != Str && AddrSpace != 0) {
7168 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7169 Str = End;
7170 }
7171 if (c == '*')
7172 Type = Context.getPointerType(Type);
7173 else
7174 Type = Context.getLValueReferenceType(Type);
7175 break;
7176 }
7177 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7178 case 'C':
7179 Type = Type.withConst();
7180 break;
7181 case 'D':
7182 Type = Context.getVolatileType(Type);
7183 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007184 case 'R':
7185 Type = Type.withRestrict();
7186 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007187 }
7188 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007189
Chris Lattner14e0e742010-10-01 22:53:11 +00007190 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007191 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007192
Chris Lattner86df27b2009-06-14 00:45:47 +00007193 return Type;
7194}
7195
7196/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007197QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007198 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007199 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007200 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007201
Chris Lattner5f9e2722011-07-23 10:55:15 +00007202 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007203
Chris Lattner14e0e742010-10-01 22:53:11 +00007204 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007205 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007206 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7207 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007208 if (Error != GE_None)
7209 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007210
7211 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7212
Chris Lattner86df27b2009-06-14 00:45:47 +00007213 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007214 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007215 if (Error != GE_None)
7216 return QualType();
7217
Chris Lattner14e0e742010-10-01 22:53:11 +00007218 // If this argument is required to be an IntegerConstantExpression and the
7219 // caller cares, fill in the bitmask we return.
7220 if (RequiresICE && IntegerConstantArgs)
7221 *IntegerConstantArgs |= 1 << ArgTypes.size();
7222
Chris Lattner86df27b2009-06-14 00:45:47 +00007223 // Do array -> pointer decay. The builtin should use the decayed type.
7224 if (Ty->isArrayType())
7225 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007226
Chris Lattner86df27b2009-06-14 00:45:47 +00007227 ArgTypes.push_back(Ty);
7228 }
7229
7230 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7231 "'.' should only occur at end of builtin type list!");
7232
John McCall00ccbef2010-12-21 00:44:39 +00007233 FunctionType::ExtInfo EI;
7234 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7235
7236 bool Variadic = (TypeStr[0] == '.');
7237
7238 // We really shouldn't be making a no-proto type here, especially in C++.
7239 if (ArgTypes.empty() && Variadic)
7240 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007241
John McCalle23cf432010-12-14 08:05:40 +00007242 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007243 EPI.ExtInfo = EI;
7244 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007245
7246 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007247}
Eli Friedmana95d7572009-08-19 07:44:53 +00007248
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007249GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7250 GVALinkage External = GVA_StrongExternal;
7251
7252 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007253 switch (L) {
7254 case NoLinkage:
7255 case InternalLinkage:
7256 case UniqueExternalLinkage:
7257 return GVA_Internal;
7258
7259 case ExternalLinkage:
7260 switch (FD->getTemplateSpecializationKind()) {
7261 case TSK_Undeclared:
7262 case TSK_ExplicitSpecialization:
7263 External = GVA_StrongExternal;
7264 break;
7265
7266 case TSK_ExplicitInstantiationDefinition:
7267 return GVA_ExplicitTemplateInstantiation;
7268
7269 case TSK_ExplicitInstantiationDeclaration:
7270 case TSK_ImplicitInstantiation:
7271 External = GVA_TemplateInstantiation;
7272 break;
7273 }
7274 }
7275
7276 if (!FD->isInlined())
7277 return External;
7278
David Blaikie4e4d0842012-03-11 07:00:24 +00007279 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007280 // GNU or C99 inline semantics. Determine whether this symbol should be
7281 // externally visible.
7282 if (FD->isInlineDefinitionExternallyVisible())
7283 return External;
7284
7285 // C99 inline semantics, where the symbol is not externally visible.
7286 return GVA_C99Inline;
7287 }
7288
7289 // C++0x [temp.explicit]p9:
7290 // [ Note: The intent is that an inline function that is the subject of
7291 // an explicit instantiation declaration will still be implicitly
7292 // instantiated when used so that the body can be considered for
7293 // inlining, but that no out-of-line copy of the inline function would be
7294 // generated in the translation unit. -- end note ]
7295 if (FD->getTemplateSpecializationKind()
7296 == TSK_ExplicitInstantiationDeclaration)
7297 return GVA_C99Inline;
7298
7299 return GVA_CXXInline;
7300}
7301
7302GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7303 // If this is a static data member, compute the kind of template
7304 // specialization. Otherwise, this variable is not part of a
7305 // template.
7306 TemplateSpecializationKind TSK = TSK_Undeclared;
7307 if (VD->isStaticDataMember())
7308 TSK = VD->getTemplateSpecializationKind();
7309
7310 Linkage L = VD->getLinkage();
David Blaikie4e4d0842012-03-11 07:00:24 +00007311 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007312 VD->getType()->getLinkage() == UniqueExternalLinkage)
7313 L = UniqueExternalLinkage;
7314
7315 switch (L) {
7316 case NoLinkage:
7317 case InternalLinkage:
7318 case UniqueExternalLinkage:
7319 return GVA_Internal;
7320
7321 case ExternalLinkage:
7322 switch (TSK) {
7323 case TSK_Undeclared:
7324 case TSK_ExplicitSpecialization:
7325 return GVA_StrongExternal;
7326
7327 case TSK_ExplicitInstantiationDeclaration:
7328 llvm_unreachable("Variable should not be instantiated");
7329 // Fall through to treat this like any other instantiation.
7330
7331 case TSK_ExplicitInstantiationDefinition:
7332 return GVA_ExplicitTemplateInstantiation;
7333
7334 case TSK_ImplicitInstantiation:
7335 return GVA_TemplateInstantiation;
7336 }
7337 }
7338
David Blaikie7530c032012-01-17 06:56:22 +00007339 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007340}
7341
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007342bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007343 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7344 if (!VD->isFileVarDecl())
7345 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00007346 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007347 return false;
7348
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007349 // Weak references don't produce any output by themselves.
7350 if (D->hasAttr<WeakRefAttr>())
7351 return false;
7352
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007353 // Aliases and used decls are required.
7354 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7355 return true;
7356
7357 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7358 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007359 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007360 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007361
7362 // Constructors and destructors are required.
7363 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7364 return true;
7365
7366 // The key function for a class is required.
7367 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7368 const CXXRecordDecl *RD = MD->getParent();
7369 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7370 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7371 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7372 return true;
7373 }
7374 }
7375
7376 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7377
7378 // static, static inline, always_inline, and extern inline functions can
7379 // always be deferred. Normal inline functions can be deferred in C99/C++.
7380 // Implicit template instantiations can also be deferred in C++.
7381 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007382 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007383 return false;
7384 return true;
7385 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007386
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007387 const VarDecl *VD = cast<VarDecl>(D);
7388 assert(VD->isFileVarDecl() && "Expected file scoped var");
7389
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007390 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7391 return false;
7392
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007393 // Structs that have non-trivial constructors or destructors are required.
7394
7395 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00007396 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007397 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7398 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00007399 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7400 RD->hasTrivialCopyConstructor() &&
7401 RD->hasTrivialMoveConstructor() &&
7402 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007403 return true;
7404 }
7405 }
7406
7407 GVALinkage L = GetGVALinkageForVariable(VD);
7408 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7409 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7410 return false;
7411 }
7412
7413 return true;
7414}
Charles Davis071cc7d2010-08-16 03:33:14 +00007415
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007416CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007417 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007418 return ABI->getDefaultMethodCallConv(isVariadic);
7419}
7420
7421CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7422 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7423 return CC_Default;
7424 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007425}
7426
Jay Foad4ba2a172011-01-12 09:06:06 +00007427bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007428 // Pass through to the C++ ABI object
7429 return ABI->isNearlyEmpty(RD);
7430}
7431
Peter Collingbourne14110472011-01-13 18:57:25 +00007432MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007433 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00007434 case CXXABI_ARM:
7435 case CXXABI_Itanium:
7436 return createItaniumMangleContext(*this, getDiagnostics());
7437 case CXXABI_Microsoft:
7438 return createMicrosoftMangleContext(*this, getDiagnostics());
7439 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007440 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007441}
7442
Charles Davis071cc7d2010-08-16 03:33:14 +00007443CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007444
7445size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007446 return ASTRecordLayouts.getMemorySize()
7447 + llvm::capacity_in_bytes(ObjCLayouts)
7448 + llvm::capacity_in_bytes(KeyFunctions)
7449 + llvm::capacity_in_bytes(ObjCImpls)
7450 + llvm::capacity_in_bytes(BlockVarCopyInits)
7451 + llvm::capacity_in_bytes(DeclAttrs)
7452 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7453 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7454 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7455 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7456 + llvm::capacity_in_bytes(OverriddenMethods)
7457 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007458 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007459 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007460}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007461
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00007462unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7463 CXXRecordDecl *Lambda = CallOperator->getParent();
7464 return LambdaMangleContexts[Lambda->getDeclContext()]
7465 .getManglingNumber(CallOperator);
7466}
7467
7468
Ted Kremenekd211cb72011-10-06 05:00:56 +00007469void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7470 ParamIndices[D] = index;
7471}
7472
7473unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7474 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7475 assert(I != ParamIndices.end() &&
7476 "ParmIndices lacks entry set by ParmVarDecl");
7477 return I->second;
7478}