blob: a92f0052f0c6580c16ebb5237b7aa931b395525f [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000028#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000030#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000032#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000033#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000034#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000035#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000036#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000037#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000038#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000040#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000041#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000042#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000043
Chris Lattnerddc135e2006-11-10 06:34:16 +000044using namespace clang;
45
Douglas Gregor9672f922010-07-03 00:47:00 +000046unsigned ASTContext::NumImplicitDefaultConstructors;
47unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000048unsigned ASTContext::NumImplicitCopyConstructors;
49unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveConstructors;
51unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000052unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000054unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000056unsigned ASTContext::NumImplicitDestructors;
57unsigned ASTContext::NumImplicitDestructorsDeclared;
58
Steve Naroff0af91202007-04-27 21:51:21 +000059enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000061};
62
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000063RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000064 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +000066
67#ifndef NDEBUG
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
71#endif
72
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000073 CommentsLoaded = true;
74 }
75
76 assert(D);
77
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000078 // User can not attach documentation to implicit declarations.
79 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +000080 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000081
Dmitri Gribenkob2610882012-08-14 17:17:18 +000082 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000085 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +000086 }
87
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000088 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000091 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000092 }
93
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000096 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000097 }
98
Dmitri Gribenko01b06512013-01-27 21:18:39 +000099 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000104 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000105 }
106
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000109 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000110 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000115 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000116 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000119 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000120
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000121 // TODO: we could look up template parameter documentation in the template
122 // documentation.
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000126 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000127
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000128 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000129
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000132 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
137 // location".
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000142 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000145 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000146 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163 }
164 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000165 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000166
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000170 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
172 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000173 ArrayRef<RawComment *>::iterator Comment;
174 {
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
177 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
185 MaybeBeforeDecl--;
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187 }
188
189 if (Found) {
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
193 } else {
194 // Slow path.
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
197 }
198 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199
200 // Decompose the location for the declaration and find the beginning of the
201 // file buffer.
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000217 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000218 }
219 }
220
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000224 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000225 --Comment;
226
227 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234
235 // If the comment and the declaration aren't in the same file, then they
236 // aren't related.
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000238 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243 &Invalid).data();
244 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000245 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000246
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
250
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000253 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000254 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000255
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000256 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000257}
258
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000259namespace {
260/// If we have a 'templated' declaration for a template, adjust 'D' to
261/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000262/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000263const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000267 return FTD;
268
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271 return D;
272
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275 return FTD;
276
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
280 return MemberDecl;
281
282 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000283 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
286 // template?
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289 return MemberDecl;
290
291 return D;
292 }
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296 return CTD;
297
298 // Class is an implicit instantiation of a class template or partial
299 // specialization?
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303 return D;
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
311 }
312
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
317
318 return D;
319 }
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323 return MemberDecl;
324
325 return D;
326 }
327 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000328 return D;
329}
330} // unnamed namespace
331
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000332const RawComment *ASTContext::getRawCommentForAnyRedecl(
333 const Decl *D,
334 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000335 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000336
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337 // Check whether we have cached a comment for this declaration already.
338 {
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344 if (OriginalDecl)
345 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000349 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000350
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000351 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000356 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000361 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000362 break;
363 }
364 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 RawCommentAndCacheFlags Raw;
368 if (RC) {
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
371 } else
372 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000373 Raw.setOriginalDecl(I);
374 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000375 if (RC)
376 break;
377 }
378 }
379
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000380 // If we found a comment, it should be a documentation comment.
381 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000382
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000383 if (OriginalDecl)
384 *OriginalDecl = OriginalDeclForRC;
385
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 // Update cache for every declaration in the redeclaration chain.
387 RawCommentAndCacheFlags Raw;
388 Raw.setRaw(RC);
389 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000390 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000391
Aaron Ballman86c93902014-03-06 23:45:36 +0000392 for (auto I : D->redecls()) {
393 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000394 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
395 R = Raw;
396 }
397
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000398 return RC;
399}
400
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000401static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
402 SmallVectorImpl<const NamedDecl *> &Redeclared) {
403 const DeclContext *DC = ObjCMethod->getDeclContext();
404 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
405 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
406 if (!ID)
407 return;
408 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000409 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000410 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000411 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 ObjCMethod->isInstanceMethod()))
413 Redeclared.push_back(RedeclaredMethod);
414 }
415 }
416}
417
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000418comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
419 const Decl *D) const {
420 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
421 ThisDeclInfo->CommentDecl = D;
422 ThisDeclInfo->IsFilled = false;
423 ThisDeclInfo->fill();
424 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000425 if (!ThisDeclInfo->TemplateParameters)
426 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000427 comments::FullComment *CFC =
428 new (*this) comments::FullComment(FC->getBlocks(),
429 ThisDeclInfo);
430 return CFC;
431
432}
433
Richard Smithb39b9d52013-05-21 05:24:00 +0000434comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
435 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000436 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000437}
438
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000439comments::FullComment *ASTContext::getCommentForDecl(
440 const Decl *D,
441 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000442 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000443 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000444 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000445
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000446 const Decl *Canonical = D->getCanonicalDecl();
447 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
448 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000449
450 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000451 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000453 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000454 return CFC;
455 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000456 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000457 }
458
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000459 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000460
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000461 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462 if (!RC) {
463 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000464 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000465 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000466 if (OMD && OMD->isPropertyAccessor())
467 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
468 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
469 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000470 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000471 addRedeclaredMethods(OMD, Overridden);
472 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000473 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
474 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
475 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000476 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000477 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000478 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000479 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000480 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000481 if (const TagType *TT = QT->getAs<TagType>())
482 if (const Decl *TD = TT->getDecl())
483 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000484 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000485 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000486 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
487 while (IC->getSuperClass()) {
488 IC = IC->getSuperClass();
489 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
490 return cloneFullComment(FC, D);
491 }
492 }
493 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
494 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
495 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
496 return cloneFullComment(FC, D);
497 }
498 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
499 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000500 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000501 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000502 for (const auto &I : RD->bases()) {
503 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000504 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000505 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000506 if (Ty.isNull())
507 continue;
508 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
509 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
510 continue;
511
512 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
513 return cloneFullComment(FC, D);
514 }
515 }
516 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000517 for (const auto &I : RD->vbases()) {
518 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000519 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000520 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000521 if (Ty.isNull())
522 continue;
523 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
524 if (!(VirtualBase= VirtualBase->getDefinition()))
525 continue;
526 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
527 return cloneFullComment(FC, D);
528 }
529 }
530 }
Craig Topper36250ad2014-05-12 05:36:57 +0000531 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000532 }
533
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000534 // If the RawComment was attached to other redeclaration of this Decl, we
535 // should parse the comment in context of that other Decl. This is important
536 // because comments can contain references to parameter names which can be
537 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000538 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000539 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000540
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000541 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000542 ParsedComments[Canonical] = FC;
543 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000544}
545
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000546void
547ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
548 TemplateTemplateParmDecl *Parm) {
549 ID.AddInteger(Parm->getDepth());
550 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000551 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000552
553 TemplateParameterList *Params = Parm->getTemplateParameters();
554 ID.AddInteger(Params->size());
555 for (TemplateParameterList::const_iterator P = Params->begin(),
556 PEnd = Params->end();
557 P != PEnd; ++P) {
558 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
559 ID.AddInteger(0);
560 ID.AddBoolean(TTP->isParameterPack());
561 continue;
562 }
563
564 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
565 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000566 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000567 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000568 if (NTTP->isExpandedParameterPack()) {
569 ID.AddBoolean(true);
570 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000571 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
572 QualType T = NTTP->getExpansionType(I);
573 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
574 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000575 } else
576 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000577 continue;
578 }
579
580 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
581 ID.AddInteger(2);
582 Profile(ID, TTP);
583 }
584}
585
586TemplateTemplateParmDecl *
587ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000588 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000589 // Check if we already have a canonical template template parameter.
590 llvm::FoldingSetNodeID ID;
591 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000592 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000593 CanonicalTemplateTemplateParm *Canonical
594 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
595 if (Canonical)
596 return Canonical->getParam();
597
598 // Build a canonical template parameter list.
599 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000600 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000601 CanonParams.reserve(Params->size());
602 for (TemplateParameterList::const_iterator P = Params->begin(),
603 PEnd = Params->end();
604 P != PEnd; ++P) {
605 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
606 CanonParams.push_back(
607 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000608 SourceLocation(),
609 SourceLocation(),
610 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000611 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000612 TTP->isParameterPack()));
613 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000614 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
615 QualType T = getCanonicalType(NTTP->getType());
616 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
617 NonTypeTemplateParmDecl *Param;
618 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000619 SmallVector<QualType, 2> ExpandedTypes;
620 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000621 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
623 ExpandedTInfos.push_back(
624 getTrivialTypeSourceInfo(ExpandedTypes.back()));
625 }
626
627 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000628 SourceLocation(),
629 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000630 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000631 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000632 T,
633 TInfo,
634 ExpandedTypes.data(),
635 ExpandedTypes.size(),
636 ExpandedTInfos.data());
637 } else {
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000639 SourceLocation(),
640 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000641 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000642 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 T,
644 NTTP->isParameterPack(),
645 TInfo);
646 }
647 CanonParams.push_back(Param);
648
649 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
652 }
653
654 TemplateTemplateParmDecl *CanonTTP
655 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
656 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000657 TTP->getPosition(),
658 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000659 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000660 TemplateParameterList::Create(*this, SourceLocation(),
661 SourceLocation(),
662 CanonParams.data(),
663 CanonParams.size(),
664 SourceLocation()));
665
666 // Get the new insert position for the node we care about.
667 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000668 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669 (void)Canonical;
670
671 // Create the canonical template template parameter entry.
672 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
673 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
674 return CanonTTP;
675}
676
Charles Davis53c59df2010-08-16 03:33:14 +0000677CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000678 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000679
John McCall359b8852013-01-25 22:30:49 +0000680 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000681 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000682 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000683 case TargetCXXABI::iOS64:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000684 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000685 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000687 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000688 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000689 return CreateMicrosoftCXXABI(*this);
690 }
David Blaikie8a40f702012-01-17 06:56:22 +0000691 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000692}
693
Douglas Gregore8bbc122011-09-02 00:18:52 +0000694static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000695 const LangOptions &LOpts) {
696 if (LOpts.FakeAddressSpaceMap) {
697 // The fake address space map must have a distinct entry for each
698 // language-specific address space.
699 static const unsigned FakeAddrSpaceMap[] = {
700 1, // opencl_global
701 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000702 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000703 4, // opencl_generic
704 5, // cuda_device
705 6, // cuda_constant
706 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000707 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000708 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000709 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000710 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000711 }
712}
713
David Tweed31d09b02013-09-13 12:04:22 +0000714static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
715 const LangOptions &LangOpts) {
716 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000717 case LangOptions::ASMM_Target:
718 return TI.useAddressSpaceMapMangling();
719 case LangOptions::ASMM_On:
720 return true;
721 case LangOptions::ASMM_Off:
722 return false;
723 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000724 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000725}
726
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000727ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000728 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000729 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000730 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
731 DependentTemplateSpecializationTypes(this_()),
732 SubstTemplateTemplateParmPacks(this_()),
733 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
734 UInt128Decl(nullptr), Float128StubDecl(nullptr),
735 BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
736 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
737 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
738 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
739 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
740 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Richard Smithf19e1272015-03-07 00:04:49 +0000741 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
742 SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000743 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000744 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
745 Idents(idents), Selectors(sels), BuiltinInfo(builtins),
746 DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
747 Comments(SM), CommentsLoaded(false),
748 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000749 TUDecl = TranslationUnitDecl::Create(*this);
750}
751
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000752ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000753 ReleaseParentMapEntries();
754
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000755 // Release the DenseMaps associated with DeclContext objects.
756 // FIXME: Is this the ideal solution?
757 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000758
Manuel Klimeka7328992013-06-03 13:51:33 +0000759 // Call all of the deallocation functions on all of their targets.
760 for (DeallocationMap::const_iterator I = Deallocations.begin(),
761 E = Deallocations.end(); I != E; ++I)
762 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
763 (I->first)((I->second)[J]);
764
Ted Kremenek076baeb2010-06-08 23:00:58 +0000765 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000766 // because they can contain DenseMaps.
767 for (llvm::DenseMap<const ObjCContainerDecl*,
768 const ASTRecordLayout*>::iterator
769 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
770 // Increment in loop to prevent using deallocated memory.
771 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
772 R->Destroy(*this);
773
Ted Kremenek076baeb2010-06-08 23:00:58 +0000774 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
775 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
776 // Increment in loop to prevent using deallocated memory.
777 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
778 R->Destroy(*this);
779 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000780
781 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
782 AEnd = DeclAttrs.end();
783 A != AEnd; ++A)
784 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000785
Reid Kleckner588c9372014-02-19 23:44:52 +0000786 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000787}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000788
Manuel Klimek95403e62014-05-21 13:28:59 +0000789void ASTContext::ReleaseParentMapEntries() {
790 if (!AllParents) return;
791 for (const auto &Entry : *AllParents) {
792 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
793 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
794 } else {
795 assert(Entry.second.is<ParentVector *>());
796 delete Entry.second.get<ParentVector *>();
797 }
798 }
799}
800
Douglas Gregor1a809332010-05-23 18:26:36 +0000801void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000802 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000803}
804
Mike Stump11289f42009-09-09 15:08:12 +0000805void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000806ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
807 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000808}
809
Chris Lattner4eb445d2007-01-26 01:27:23 +0000810void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000811 llvm::errs() << "\n*** AST Context Stats:\n";
812 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000813
Douglas Gregora30d0462009-05-26 14:40:08 +0000814 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000815#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000816#define ABSTRACT_TYPE(Name, Parent)
817#include "clang/AST/TypeNodes.def"
818 0 // Extra
819 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000820
Chris Lattner4eb445d2007-01-26 01:27:23 +0000821 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
822 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000823 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000824 }
825
Douglas Gregora30d0462009-05-26 14:40:08 +0000826 unsigned Idx = 0;
827 unsigned TotalBytes = 0;
828#define TYPE(Name, Parent) \
829 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000830 llvm::errs() << " " << counts[Idx] << " " << #Name \
831 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000832 TotalBytes += counts[Idx] * sizeof(Name##Type); \
833 ++Idx;
834#define ABSTRACT_TYPE(Name, Parent)
835#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000836
Chandler Carruth3c147a72011-07-04 05:32:14 +0000837 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
838
Douglas Gregor7454c562010-07-02 20:37:36 +0000839 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000840 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
841 << NumImplicitDefaultConstructors
842 << " implicit default constructors created\n";
843 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
844 << NumImplicitCopyConstructors
845 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000846 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000847 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
848 << NumImplicitMoveConstructors
849 << " implicit move constructors created\n";
850 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
851 << NumImplicitCopyAssignmentOperators
852 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000853 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000854 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
855 << NumImplicitMoveAssignmentOperators
856 << " implicit move assignment operators created\n";
857 llvm::errs() << NumImplicitDestructorsDeclared << "/"
858 << NumImplicitDestructors
859 << " implicit destructors created\n";
860
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000861 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000862 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000863 ExternalSource->PrintStats();
864 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000865
Douglas Gregor5b11d492010-07-25 17:53:33 +0000866 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000867}
868
Richard Smith42413142015-05-15 20:05:43 +0000869void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
870 bool NotifyListeners) {
871 if (NotifyListeners)
872 if (auto *Listener = getASTMutationListener())
873 Listener->RedefinedHiddenDefinition(ND, M);
874
875 if (getLangOpts().ModulesLocalVisibility)
876 MergedDefModules[ND].push_back(M);
877 else
878 ND->setHidden(false);
879}
880
881void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
882 auto It = MergedDefModules.find(ND);
883 if (It == MergedDefModules.end())
884 return;
885
886 auto &Merged = It->second;
887 llvm::DenseSet<Module*> Found;
888 for (Module *&M : Merged)
889 if (!Found.insert(M).second)
890 M = nullptr;
891 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
892}
893
Richard Smithf19e1272015-03-07 00:04:49 +0000894ExternCContextDecl *ASTContext::getExternCContextDecl() const {
895 if (!ExternCContext)
896 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
897
898 return ExternCContext;
899}
900
Alp Toker2dea15b2013-12-17 01:22:38 +0000901RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
902 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000903 SourceLocation Loc;
904 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000905 if (getLangOpts().CPlusPlus)
906 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
907 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000908 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000909 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
910 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000911 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000912 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
913 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000914 return NewDecl;
915}
916
917TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
918 StringRef Name) const {
919 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
920 TypedefDecl *NewDecl = TypedefDecl::Create(
921 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
922 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
923 NewDecl->setImplicit();
924 return NewDecl;
925}
926
Douglas Gregor801c99d2011-08-12 06:49:56 +0000927TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000928 if (!Int128Decl)
929 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000930 return Int128Decl;
931}
932
933TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000934 if (!UInt128Decl)
935 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000936 return UInt128Decl;
937}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000938
Nico Webere1687c52013-06-20 21:44:55 +0000939TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000940 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000941 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000942 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000943
Nico Webere1687c52013-06-20 21:44:55 +0000944 return Float128StubDecl;
945}
946
John McCall48f2d582009-10-23 23:03:21 +0000947void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000948 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000949 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000950 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000951}
952
Douglas Gregore8bbc122011-09-02 00:18:52 +0000953void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
954 assert((!this->Target || this->Target == &Target) &&
955 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000956 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000957
Douglas Gregore8bbc122011-09-02 00:18:52 +0000958 this->Target = &Target;
959
960 ABI.reset(createCXXABI(Target));
961 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000962 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000963
Chris Lattner970e54e2006-11-12 00:37:36 +0000964 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000965 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000966
Chris Lattner970e54e2006-11-12 00:37:36 +0000967 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000968 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000969 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000970 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000971 InitBuiltinType(CharTy, BuiltinType::Char_S);
972 else
973 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000974 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000975 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
976 InitBuiltinType(ShortTy, BuiltinType::Short);
977 InitBuiltinType(IntTy, BuiltinType::Int);
978 InitBuiltinType(LongTy, BuiltinType::Long);
979 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000980
Chris Lattner970e54e2006-11-12 00:37:36 +0000981 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000982 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
983 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
984 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
985 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
986 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000987
Chris Lattner970e54e2006-11-12 00:37:36 +0000988 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000989 InitBuiltinType(FloatTy, BuiltinType::Float);
990 InitBuiltinType(DoubleTy, BuiltinType::Double);
991 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000992
Chris Lattnerf122cef2009-04-30 02:43:43 +0000993 // GNU extension, 128-bit integers.
994 InitBuiltinType(Int128Ty, BuiltinType::Int128);
995 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
996
Hans Wennborg0d81e012013-05-10 10:08:40 +0000997 // C++ 3.9.1p5
998 if (TargetInfo::isTypeSigned(Target.getWCharType()))
999 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1000 else // -fshort-wchar makes wchar_t be unsigned.
1001 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1002 if (LangOpts.CPlusPlus && LangOpts.WChar)
1003 WideCharTy = WCharTy;
1004 else {
1005 // C99 (or C++ using -fno-wchar).
1006 WideCharTy = getFromTargetType(Target.getWCharType());
1007 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001008
James Molloy36365542012-05-04 10:55:22 +00001009 WIntTy = getFromTargetType(Target.getWIntType());
1010
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001011 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1012 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1013 else // C99
1014 Char16Ty = getFromTargetType(Target.getChar16Type());
1015
1016 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1017 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1018 else // C99
1019 Char32Ty = getFromTargetType(Target.getChar32Type());
1020
Douglas Gregor4619e432008-12-05 23:32:09 +00001021 // Placeholder type for type-dependent expressions whose type is
1022 // completely unknown. No code should ever check a type against
1023 // DependentTy and users should never see it; however, it is here to
1024 // help diagnose failures to properly check for type-dependent
1025 // expressions.
1026 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001027
John McCall36e7fe32010-10-12 00:20:44 +00001028 // Placeholder type for functions.
1029 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1030
John McCall0009fcc2011-04-26 20:42:42 +00001031 // Placeholder type for bound members.
1032 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1033
John McCall526ab472011-10-25 17:37:35 +00001034 // Placeholder type for pseudo-objects.
1035 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1036
John McCall31996342011-04-07 08:22:57 +00001037 // "any" type; useful for debugger-like clients.
1038 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1039
John McCall8a6b59a2011-10-17 18:09:15 +00001040 // Placeholder type for unbridged ARC casts.
1041 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1042
Eli Friedman34866c72012-08-31 00:14:07 +00001043 // Placeholder type for builtin functions.
1044 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1045
Chris Lattner970e54e2006-11-12 00:37:36 +00001046 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001047 FloatComplexTy = getComplexType(FloatTy);
1048 DoubleComplexTy = getComplexType(DoubleTy);
1049 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001050
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001051 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001052 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1053 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001054 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001055
1056 if (LangOpts.OpenCL) {
1057 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1058 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1059 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1060 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1061 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1062 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001063
Guy Benyei61054192013-02-07 10:55:47 +00001064 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001065 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001066 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001067
1068 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001069 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1070 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001071
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001072 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001073
1074 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001075
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001076 // void * type
1077 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001078
1079 // nullptr type (C++0x 2.14.7)
1080 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001081
1082 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1083 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001084
1085 // Builtin type used to help define __builtin_va_list.
1086 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001087}
1088
David Blaikie9c902b52011-09-25 23:23:43 +00001089DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001090 return SourceMgr.getDiagnostics();
1091}
1092
Douglas Gregor561eceb2010-08-30 16:49:28 +00001093AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1094 AttrVec *&Result = DeclAttrs[D];
1095 if (!Result) {
1096 void *Mem = Allocate(sizeof(AttrVec));
1097 Result = new (Mem) AttrVec;
1098 }
1099
1100 return *Result;
1101}
1102
1103/// \brief Erase the attributes corresponding to the given declaration.
1104void ASTContext::eraseDeclAttrs(const Decl *D) {
1105 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1106 if (Pos != DeclAttrs.end()) {
1107 Pos->second->~AttrVec();
1108 DeclAttrs.erase(Pos);
1109 }
1110}
1111
Larisse Voufo39a1e502013-08-06 01:03:05 +00001112// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001113MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001114ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001115 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001116 return getTemplateOrSpecializationInfo(Var)
1117 .dyn_cast<MemberSpecializationInfo *>();
1118}
1119
1120ASTContext::TemplateOrSpecializationInfo
1121ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1122 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1123 TemplateOrInstantiation.find(Var);
1124 if (Pos == TemplateOrInstantiation.end())
1125 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001126
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001127 return Pos->second;
1128}
1129
Mike Stump11289f42009-09-09 15:08:12 +00001130void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001131ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001132 TemplateSpecializationKind TSK,
1133 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001134 assert(Inst->isStaticDataMember() && "Not a static data member");
1135 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001136 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1137 Tmpl, TSK, PointOfInstantiation));
1138}
1139
1140void
1141ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1142 TemplateOrSpecializationInfo TSI) {
1143 assert(!TemplateOrInstantiation[Inst] &&
1144 "Already noted what the variable was instantiated from");
1145 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001146}
1147
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001148FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1149 const FunctionDecl *FD){
1150 assert(FD && "Specialization is 0");
1151 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001152 = ClassScopeSpecializationPattern.find(FD);
1153 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001154 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001155
1156 return Pos->second;
1157}
1158
1159void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1160 FunctionDecl *Pattern) {
1161 assert(FD && "Specialization is 0");
1162 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001163 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001164}
1165
John McCalle61f2ba2009-11-18 02:36:19 +00001166NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001167ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001168 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001169 = InstantiatedFromUsingDecl.find(UUD);
1170 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001171 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001172
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001173 return Pos->second;
1174}
1175
1176void
John McCallb96ec562009-12-04 22:46:56 +00001177ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1178 assert((isa<UsingDecl>(Pattern) ||
1179 isa<UnresolvedUsingValueDecl>(Pattern) ||
1180 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1181 "pattern decl is not a using decl");
1182 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1183 InstantiatedFromUsingDecl[Inst] = Pattern;
1184}
1185
1186UsingShadowDecl *
1187ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1188 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1189 = InstantiatedFromUsingShadowDecl.find(Inst);
1190 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001191 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001192
1193 return Pos->second;
1194}
1195
1196void
1197ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1198 UsingShadowDecl *Pattern) {
1199 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1200 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001201}
1202
Anders Carlsson5da84842009-09-01 04:26:58 +00001203FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1204 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1205 = InstantiatedFromUnnamedFieldDecl.find(Field);
1206 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001207 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001208
Anders Carlsson5da84842009-09-01 04:26:58 +00001209 return Pos->second;
1210}
1211
1212void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1213 FieldDecl *Tmpl) {
1214 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1215 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1216 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1217 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001218
Anders Carlsson5da84842009-09-01 04:26:58 +00001219 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1220}
1221
Douglas Gregor832940b2010-03-02 23:58:15 +00001222ASTContext::overridden_cxx_method_iterator
1223ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1224 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001225 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001226 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001227 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001228
1229 return Pos->second.begin();
1230}
1231
1232ASTContext::overridden_cxx_method_iterator
1233ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1234 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001235 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001236 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001237 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001238
1239 return Pos->second.end();
1240}
1241
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001242unsigned
1243ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1244 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001245 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001246 if (Pos == OverriddenMethods.end())
1247 return 0;
1248
1249 return Pos->second.size();
1250}
1251
Douglas Gregor832940b2010-03-02 23:58:15 +00001252void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1253 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001254 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001255 OverriddenMethods[Method].push_back(Overridden);
1256}
1257
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001258void ASTContext::getOverriddenMethods(
1259 const NamedDecl *D,
1260 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001261 assert(D);
1262
1263 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001264 Overridden.append(overridden_methods_begin(CXXMethod),
1265 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001266 return;
1267 }
1268
1269 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1270 if (!Method)
1271 return;
1272
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001273 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1274 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001275 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001276}
1277
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001278void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1279 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1280 assert(!Import->isFromASTFile() && "Non-local import declaration");
1281 if (!FirstLocalImport) {
1282 FirstLocalImport = Import;
1283 LastLocalImport = Import;
1284 return;
1285 }
1286
1287 LastLocalImport->NextLocalImport = Import;
1288 LastLocalImport = Import;
1289}
1290
Chris Lattner53cfe802007-07-18 17:52:12 +00001291//===----------------------------------------------------------------------===//
1292// Type Sizing and Analysis
1293//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001294
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001295/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1296/// scalar floating point type.
1297const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001298 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001299 assert(BT && "Not a floating point type!");
1300 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001301 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001302 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001303 case BuiltinType::Float: return Target->getFloatFormat();
1304 case BuiltinType::Double: return Target->getDoubleFormat();
1305 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001306 }
1307}
1308
Rafael Espindola71eccb32013-08-08 19:53:46 +00001309CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001310 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001311
John McCall94268702010-10-08 18:24:19 +00001312 bool UseAlignAttrOnly = false;
1313 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1314 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001315
John McCall94268702010-10-08 18:24:19 +00001316 // __attribute__((aligned)) can increase or decrease alignment
1317 // *except* on a struct or struct member, where it only increases
1318 // alignment unless 'packed' is also specified.
1319 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001320 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001321 // ignore that possibility; Sema should diagnose it.
1322 if (isa<FieldDecl>(D)) {
1323 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1324 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1325 } else {
1326 UseAlignAttrOnly = true;
1327 }
1328 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001329 else if (isa<FieldDecl>(D))
1330 UseAlignAttrOnly =
1331 D->hasAttr<PackedAttr>() ||
1332 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001333
John McCall4e819612011-01-20 07:57:12 +00001334 // If we're using the align attribute only, just ignore everything
1335 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001336 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001337 // do nothing
1338
John McCall94268702010-10-08 18:24:19 +00001339 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001340 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001341 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001342 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001343 T = RT->getPointeeType();
1344 else
1345 T = getPointerType(RT->getPointeeType());
1346 }
Richard Smithf6d70302014-06-10 23:34:28 +00001347 QualType BaseT = getBaseElementType(T);
1348 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001349 // Adjust alignments of declarations with array type by the
1350 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001351 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001352 unsigned MinWidth = Target->getLargeArrayMinWidth();
1353 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001354 if (isa<VariableArrayType>(arrayType))
1355 Align = std::max(Align, Target->getLargeArrayAlign());
1356 else if (isa<ConstantArrayType>(arrayType) &&
1357 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1358 Align = std::max(Align, Target->getLargeArrayAlign());
1359 }
John McCall33ddac02011-01-19 10:06:00 +00001360 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001361 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001362 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001363 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001364 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1365 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001366 }
John McCall4e819612011-01-20 07:57:12 +00001367
1368 // Fields can be subject to extra alignment constraints, like if
1369 // the field is packed, the struct is packed, or the struct has a
1370 // a max-field-alignment constraint (#pragma pack). So calculate
1371 // the actual alignment of the field within the struct, and then
1372 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001373 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1374 const RecordDecl *Parent = Field->getParent();
1375 // We can only produce a sensible answer if the record is valid.
1376 if (!Parent->isInvalidDecl()) {
1377 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001378
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001379 // Start with the record's overall alignment.
1380 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001381
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001382 // Use the GCD of that and the offset within the record.
1383 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1384 if (Offset > 0) {
1385 // Alignment is always a power of 2, so the GCD will be a power of 2,
1386 // which means we get to do this crazy thing instead of Euclid's.
1387 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1388 if (LowBitOfOffset < FieldAlign)
1389 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1390 }
1391
1392 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001393 }
Charles Davis3fc51072010-02-23 04:52:00 +00001394 }
Chris Lattner68061312009-01-24 21:53:27 +00001395 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001396
Ken Dyckcc56c542011-01-15 18:38:59 +00001397 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001398}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001399
John McCallf1249922012-08-21 04:10:00 +00001400// getTypeInfoDataSizeInChars - Return the size of a type, in
1401// chars. If the type is a record, its data size is returned. This is
1402// the size of the memcpy that's performed when assigning this type
1403// using a trivial copy/move assignment operator.
1404std::pair<CharUnits, CharUnits>
1405ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1406 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1407
1408 // In C++, objects can sometimes be allocated into the tail padding
1409 // of a base-class subobject. We decide whether that's possible
1410 // during class layout, so here we can just trust the layout results.
1411 if (getLangOpts().CPlusPlus) {
1412 if (const RecordType *RT = T->getAs<RecordType>()) {
1413 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1414 sizeAndAlign.first = layout.getDataSize();
1415 }
1416 }
1417
1418 return sizeAndAlign;
1419}
1420
Richard Trieu04d2d942013-05-14 21:59:17 +00001421/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1422/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1423std::pair<CharUnits, CharUnits>
1424static getConstantArrayInfoInChars(const ASTContext &Context,
1425 const ConstantArrayType *CAT) {
1426 std::pair<CharUnits, CharUnits> EltInfo =
1427 Context.getTypeInfoInChars(CAT->getElementType());
1428 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001429 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1430 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001431 "Overflow in array type char size evaluation");
1432 uint64_t Width = EltInfo.first.getQuantity() * Size;
1433 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001434 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1435 Context.getTargetInfo().getPointerWidth(0) == 64)
1436 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001437 return std::make_pair(CharUnits::fromQuantity(Width),
1438 CharUnits::fromQuantity(Align));
1439}
1440
John McCall87fe5d52010-05-20 01:18:31 +00001441std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001442ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001443 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1444 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001445 TypeInfo Info = getTypeInfo(T);
1446 return std::make_pair(toCharUnitsFromBits(Info.Width),
1447 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001448}
1449
1450std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001451ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001452 return getTypeInfoInChars(T.getTypePtr());
1453}
1454
David Majnemer34b57492014-07-30 01:30:47 +00001455bool ASTContext::isAlignmentRequired(const Type *T) const {
1456 return getTypeInfo(T).AlignIsRequired;
1457}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001458
David Majnemer34b57492014-07-30 01:30:47 +00001459bool ASTContext::isAlignmentRequired(QualType T) const {
1460 return isAlignmentRequired(T.getTypePtr());
1461}
1462
1463TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001464 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1465 if (I != MemoizedTypeInfo.end())
1466 return I->second;
1467
1468 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1469 TypeInfo TI = getTypeInfoImpl(T);
1470 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001471 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001472}
1473
1474/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1475/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001476///
1477/// FIXME: Pointers into different addr spaces could have different sizes and
1478/// alignment requirements: getPointerInfo should take an AddrSpace, this
1479/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001480TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1481 uint64_t Width = 0;
1482 unsigned Align = 8;
1483 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001484 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001485#define TYPE(Class, Base)
1486#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001487#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001488#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001489#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1490 case Type::Class: \
1491 assert(!T->isDependentType() && "should not see dependent types here"); \
1492 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001493#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001494 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001495
Chris Lattner355332d2007-07-13 22:27:08 +00001496 case Type::FunctionNoProto:
1497 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001498 // GCC extension: alignof(function) = 32 bits
1499 Width = 0;
1500 Align = 32;
1501 break;
1502
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001503 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001504 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001505 Width = 0;
1506 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1507 break;
1508
Steve Naroff5c131802007-08-30 01:06:46 +00001509 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001510 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001511
David Majnemer34b57492014-07-30 01:30:47 +00001512 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001513 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001514 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001515 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001516 Width = EltInfo.Width * Size;
1517 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001518 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1519 getTargetInfo().getPointerWidth(0) == 64)
1520 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001521 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001522 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001523 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001524 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001525 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001526 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1527 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001528 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001529 // If the alignment is not a power of 2, round up to the next power of 2.
1530 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001531 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001532 Align = llvm::NextPowerOf2(Align);
1533 Width = llvm::RoundUpToAlignment(Width, Align);
1534 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001535 // Adjust the alignment based on the target max.
1536 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1537 if (TargetVectorAlign && TargetVectorAlign < Align)
1538 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001539 break;
1540 }
Chris Lattner647fb222007-07-18 18:26:58 +00001541
Chris Lattner7570e9c2008-03-08 08:52:55 +00001542 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001543 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001544 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001545 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001546 // GCC extension: alignof(void) = 8 bits.
1547 Width = 0;
1548 Align = 8;
1549 break;
1550
Chris Lattner6a4f7452007-12-19 19:23:28 +00001551 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001552 Width = Target->getBoolWidth();
1553 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001554 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001555 case BuiltinType::Char_S:
1556 case BuiltinType::Char_U:
1557 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001558 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001559 Width = Target->getCharWidth();
1560 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001561 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001562 case BuiltinType::WChar_S:
1563 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001564 Width = Target->getWCharWidth();
1565 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001566 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001567 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001568 Width = Target->getChar16Width();
1569 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001570 break;
1571 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001572 Width = Target->getChar32Width();
1573 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001574 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001575 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001576 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001577 Width = Target->getShortWidth();
1578 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001579 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001580 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001581 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001582 Width = Target->getIntWidth();
1583 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001584 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001585 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001586 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001587 Width = Target->getLongWidth();
1588 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001589 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001590 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001591 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001592 Width = Target->getLongLongWidth();
1593 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001594 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001595 case BuiltinType::Int128:
1596 case BuiltinType::UInt128:
1597 Width = 128;
1598 Align = 128; // int128_t is 128-bit aligned on all targets.
1599 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001600 case BuiltinType::Half:
1601 Width = Target->getHalfWidth();
1602 Align = Target->getHalfAlign();
1603 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001604 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001605 Width = Target->getFloatWidth();
1606 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001607 break;
1608 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001609 Width = Target->getDoubleWidth();
1610 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001611 break;
1612 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001613 Width = Target->getLongDoubleWidth();
1614 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001615 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001616 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001617 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1618 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001619 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001620 case BuiltinType::ObjCId:
1621 case BuiltinType::ObjCClass:
1622 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001623 Width = Target->getPointerWidth(0);
1624 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001625 break;
Guy Benyei61054192013-02-07 10:55:47 +00001626 case BuiltinType::OCLSampler:
1627 // Samplers are modeled as integers.
1628 Width = Target->getIntWidth();
1629 Align = Target->getIntAlign();
1630 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001631 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001632 case BuiltinType::OCLImage1d:
1633 case BuiltinType::OCLImage1dArray:
1634 case BuiltinType::OCLImage1dBuffer:
1635 case BuiltinType::OCLImage2d:
1636 case BuiltinType::OCLImage2dArray:
1637 case BuiltinType::OCLImage3d:
1638 // Currently these types are pointers to opaque types.
1639 Width = Target->getPointerWidth(0);
1640 Align = Target->getPointerAlign(0);
1641 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001642 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001643 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001644 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001645 Width = Target->getPointerWidth(0);
1646 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001647 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001648 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001649 unsigned AS = getTargetAddressSpace(
1650 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001651 Width = Target->getPointerWidth(AS);
1652 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001653 break;
1654 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001655 case Type::LValueReference:
1656 case Type::RValueReference: {
1657 // alignof and sizeof should never enter this code path here, so we go
1658 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001659 unsigned AS = getTargetAddressSpace(
1660 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001661 Width = Target->getPointerWidth(AS);
1662 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001663 break;
1664 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001665 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001666 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001667 Width = Target->getPointerWidth(AS);
1668 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001669 break;
1670 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001671 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001672 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001673 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001674 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001675 }
Chris Lattner647fb222007-07-18 18:26:58 +00001676 case Type::Complex: {
1677 // Complex types have the same alignment as their elements, but twice the
1678 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001679 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1680 Width = EltInfo.Width * 2;
1681 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001682 break;
1683 }
John McCall8b07ec22010-05-15 11:32:37 +00001684 case Type::ObjCObject:
1685 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001686 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001687 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001688 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001689 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001690 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001691 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001692 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001693 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001694 break;
1695 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001696 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001697 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001698 const TagType *TT = cast<TagType>(T);
1699
1700 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001701 Width = 8;
1702 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001703 break;
1704 }
Mike Stump11289f42009-09-09 15:08:12 +00001705
David Majnemer475b25e2015-01-21 10:54:38 +00001706 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1707 const EnumDecl *ED = ET->getDecl();
1708 TypeInfo Info =
1709 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1710 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1711 Info.Align = AttrAlign;
1712 Info.AlignIsRequired = true;
1713 }
1714 return Info;
1715 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001716
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001717 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001718 const RecordDecl *RD = RT->getDecl();
1719 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001720 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001721 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001722 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001723 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001724 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001725
Chris Lattner63d2b362009-10-22 05:17:15 +00001726 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001727 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1728 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001729
Richard Smith30482bc2011-02-20 03:19:35 +00001730 case Type::Auto: {
1731 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001732 assert(!A->getDeducedType().isNull() &&
1733 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001734 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001735 }
1736
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001737 case Type::Paren:
1738 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1739
Douglas Gregoref462e62009-04-30 17:32:17 +00001740 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001741 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001742 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001743 // If the typedef has an aligned attribute on it, it overrides any computed
1744 // alignment we have. This violates the GCC documentation (which says that
1745 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001746 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001747 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001748 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001749 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001750 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001751 AlignIsRequired = Info.AlignIsRequired;
1752 }
David Majnemer34b57492014-07-30 01:30:47 +00001753 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001754 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001755 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001756
Abramo Bagnara6150c882010-05-11 21:36:43 +00001757 case Type::Elaborated:
1758 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001759
John McCall81904512011-01-06 01:58:22 +00001760 case Type::Attributed:
1761 return getTypeInfo(
1762 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1763
Eli Friedman0dfb8892011-10-06 23:00:33 +00001764 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001765 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001766 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1767 Width = Info.Width;
1768 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001769
1770 // If the size of the type doesn't exceed the platform's max
1771 // atomic promotion width, make the size and alignment more
1772 // favorable to atomic operations:
1773 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1774 // Round the size up to a power of 2.
1775 if (!llvm::isPowerOf2_64(Width))
1776 Width = llvm::NextPowerOf2(Width);
1777
1778 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001779 Align = static_cast<unsigned>(Width);
1780 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001781 }
1782
Douglas Gregoref462e62009-04-30 17:32:17 +00001783 }
Mike Stump11289f42009-09-09 15:08:12 +00001784
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001785 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001786 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001787}
1788
Alexey Bataev00396512015-07-02 03:40:19 +00001789unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1790 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1791 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1792 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1793 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1794 getTargetInfo().getABI() == "elfv1-qpx" &&
1795 T->isSpecificBuiltinType(BuiltinType::Double))
1796 SimdAlign = 256;
1797 return SimdAlign;
1798}
1799
Ken Dyckcc56c542011-01-15 18:38:59 +00001800/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1801CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1802 return CharUnits::fromQuantity(BitSize / getCharWidth());
1803}
1804
Ken Dyckb0fcc592011-02-11 01:54:29 +00001805/// toBits - Convert a size in characters to a size in characters.
1806int64_t ASTContext::toBits(CharUnits CharSize) const {
1807 return CharSize.getQuantity() * getCharWidth();
1808}
1809
Ken Dyck8c89d592009-12-22 14:23:30 +00001810/// getTypeSizeInChars - Return the size of the specified type, in characters.
1811/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001812CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001813 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001814}
Jay Foad39c79802011-01-12 09:06:06 +00001815CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001816 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001817}
1818
Ken Dycka6046ab2010-01-26 17:25:18 +00001819/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001820/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001821CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001822 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001823}
Jay Foad39c79802011-01-12 09:06:06 +00001824CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001825 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001826}
1827
Chris Lattnera3402cd2009-01-27 18:08:34 +00001828/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1829/// type for the current target in bits. This can be different than the ABI
1830/// alignment in cases where it is beneficial for performance to overalign
1831/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001832unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001833 TypeInfo TI = getTypeInfo(T);
1834 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001835
David Majnemere1544562015-04-24 01:25:05 +00001836 T = T->getBaseElementTypeUnsafe();
1837
1838 // The preferred alignment of member pointers is that of a pointer.
1839 if (T->isMemberPointerType())
1840 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1841
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001842 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1843 return ABIAlign; // Never overalign on XCore.
1844
Eli Friedman7ab09572009-05-25 21:27:19 +00001845 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001846 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001847 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001848 if (const EnumType *ET = T->getAs<EnumType>())
1849 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001850 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001851 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1852 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001853 // Don't increase the alignment if an alignment attribute was specified on a
1854 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001855 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001856 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001857
Chris Lattnera3402cd2009-01-27 18:08:34 +00001858 return ABIAlign;
1859}
1860
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001861/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1862/// for __attribute__((aligned)) on this target, to be used if no alignment
1863/// value is specified.
1864unsigned ASTContext::getTargetDefaultAlignForAttributeAligned(void) const {
1865 return getTargetInfo().getDefaultAlignForAttributeAligned();
1866}
1867
Ulrich Weigandfa806422013-05-06 16:23:57 +00001868/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1869/// to a global variable of the specified type.
1870unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1871 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1872}
1873
1874/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1875/// should be given to a global variable of the specified type.
1876CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1877 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1878}
1879
David Majnemer08ef2ba2015-06-23 20:34:18 +00001880CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1881 CharUnits Offset = CharUnits::Zero();
1882 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1883 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1884 Offset += Layout->getBaseClassOffset(Base);
1885 Layout = &getASTRecordLayout(Base);
1886 }
1887 return Offset;
1888}
1889
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001890/// DeepCollectObjCIvars -
1891/// This routine first collects all declared, but not synthesized, ivars in
1892/// super class and then collects all ivars, including those synthesized for
1893/// current class. This routine is used for implementation of current class
1894/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001895///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001896void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1897 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001898 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001899 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1900 DeepCollectObjCIvars(SuperClass, false, Ivars);
1901 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001902 for (const auto *I : OI->ivars())
1903 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001904 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001905 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001906 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001907 Iv= Iv->getNextIvar())
1908 Ivars.push_back(Iv);
1909 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001910}
1911
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001912/// CollectInheritedProtocols - Collect all protocols in current class and
1913/// those inherited by it.
1914void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001915 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001916 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001917 // We can use protocol_iterator here instead of
1918 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001919 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001920 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001921 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001922
1923 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001924 for (const auto *Cat : OI->visible_categories())
1925 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001926
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001927 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1928 while (SD) {
1929 CollectInheritedProtocols(SD, Protocols);
1930 SD = SD->getSuperClass();
1931 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001932 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001933 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001934 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001935 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001936 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001937 // Insert the protocol.
1938 if (!Protocols.insert(
1939 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1940 return;
1941
1942 for (auto *Proto : OP->protocols())
1943 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001944 }
1945}
1946
Jay Foad39c79802011-01-12 09:06:06 +00001947unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001948 unsigned count = 0;
1949 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001950 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001951 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001952
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001953 // Count ivar defined in this class's implementation. This
1954 // includes synthesized ivars.
1955 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001956 count += ImplDecl->ivar_size();
1957
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001958 return count;
1959}
1960
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001961bool ASTContext::isSentinelNullExpr(const Expr *E) {
1962 if (!E)
1963 return false;
1964
1965 // nullptr_t is always treated as null.
1966 if (E->getType()->isNullPtrType()) return true;
1967
1968 if (E->getType()->isAnyPointerType() &&
1969 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1970 Expr::NPC_ValueDependentIsNull))
1971 return true;
1972
1973 // Unfortunately, __null has type 'int'.
1974 if (isa<GNUNullExpr>(E)) return true;
1975
1976 return false;
1977}
1978
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001979/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1980ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1981 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1982 I = ObjCImpls.find(D);
1983 if (I != ObjCImpls.end())
1984 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001985 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001986}
1987/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1988ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1989 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1990 I = ObjCImpls.find(D);
1991 if (I != ObjCImpls.end())
1992 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001993 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001994}
1995
1996/// \brief Set the implementation of ObjCInterfaceDecl.
1997void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1998 ObjCImplementationDecl *ImplD) {
1999 assert(IFaceD && ImplD && "Passed null params");
2000 ObjCImpls[IFaceD] = ImplD;
2001}
2002/// \brief Set the implementation of ObjCCategoryDecl.
2003void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2004 ObjCCategoryImplDecl *ImplD) {
2005 assert(CatD && ImplD && "Passed null params");
2006 ObjCImpls[CatD] = ImplD;
2007}
2008
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002009const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2010 const NamedDecl *ND) const {
2011 if (const ObjCInterfaceDecl *ID =
2012 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002013 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002014 if (const ObjCCategoryDecl *CD =
2015 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002016 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002017 if (const ObjCImplDecl *IMD =
2018 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002019 return IMD->getClassInterface();
2020
Craig Topper36250ad2014-05-12 05:36:57 +00002021 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002022}
2023
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002024/// \brief Get the copy initialization expression of VarDecl,or NULL if
2025/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002026Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002027 assert(VD && "Passed null params");
2028 assert(VD->hasAttr<BlocksAttr>() &&
2029 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002030 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002031 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002032 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002033}
2034
2035/// \brief Set the copy inialization expression of a block var decl.
2036void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2037 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002038 assert(VD->hasAttr<BlocksAttr>() &&
2039 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002040 BlockVarCopyInits[VD] = Init;
2041}
2042
John McCallbcd03502009-12-07 02:54:59 +00002043TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002044 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002045 if (!DataSize)
2046 DataSize = TypeLoc::getFullDataSizeForType(T);
2047 else
2048 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002049 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002050
John McCallbcd03502009-12-07 02:54:59 +00002051 TypeSourceInfo *TInfo =
2052 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2053 new (TInfo) TypeSourceInfo(T);
2054 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002055}
2056
John McCallbcd03502009-12-07 02:54:59 +00002057TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002058 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002059 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002060 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002061 return DI;
2062}
2063
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002064const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002065ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002066 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002067}
2068
2069const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002070ASTContext::getASTObjCImplementationLayout(
2071 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002072 return getObjCLayout(D->getClassInterface(), D);
2073}
2074
Chris Lattner983a8bb2007-07-13 22:13:22 +00002075//===----------------------------------------------------------------------===//
2076// Type creation/memoization methods
2077//===----------------------------------------------------------------------===//
2078
Jay Foad39c79802011-01-12 09:06:06 +00002079QualType
John McCall33ddac02011-01-19 10:06:00 +00002080ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2081 unsigned fastQuals = quals.getFastQualifiers();
2082 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002083
2084 // Check if we've already instantiated this type.
2085 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002086 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002087 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002088 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2089 assert(eq->getQualifiers() == quals);
2090 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002091 }
2092
John McCall33ddac02011-01-19 10:06:00 +00002093 // If the base type is not canonical, make the appropriate canonical type.
2094 QualType canon;
2095 if (!baseType->isCanonicalUnqualified()) {
2096 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002097 canonSplit.Quals.addConsistentQualifiers(quals);
2098 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002099
2100 // Re-find the insert position.
2101 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2102 }
2103
2104 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2105 ExtQualNodes.InsertNode(eq, insertPos);
2106 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002107}
2108
Jay Foad39c79802011-01-12 09:06:06 +00002109QualType
2110ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002111 QualType CanT = getCanonicalType(T);
2112 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002113 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002114
John McCall8ccfcb52009-09-24 19:53:00 +00002115 // If we are composing extended qualifiers together, merge together
2116 // into one ExtQuals node.
2117 QualifierCollector Quals;
2118 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002119
John McCall8ccfcb52009-09-24 19:53:00 +00002120 // If this type already has an address space specified, it cannot get
2121 // another one.
2122 assert(!Quals.hasAddressSpace() &&
2123 "Type cannot be in multiple addr spaces!");
2124 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002125
John McCall8ccfcb52009-09-24 19:53:00 +00002126 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002127}
2128
Chris Lattnerd60183d2009-02-18 22:53:11 +00002129QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002130 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002131 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002132 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002133 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002134
John McCall53fa7142010-12-24 02:08:15 +00002135 if (const PointerType *ptr = T->getAs<PointerType>()) {
2136 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002137 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002138 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2139 return getPointerType(ResultType);
2140 }
2141 }
Mike Stump11289f42009-09-09 15:08:12 +00002142
John McCall8ccfcb52009-09-24 19:53:00 +00002143 // If we are composing extended qualifiers together, merge together
2144 // into one ExtQuals node.
2145 QualifierCollector Quals;
2146 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002147
John McCall8ccfcb52009-09-24 19:53:00 +00002148 // If this type already has an ObjCGC specified, it cannot get
2149 // another one.
2150 assert(!Quals.hasObjCGCAttr() &&
2151 "Type cannot have multiple ObjCGCs!");
2152 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002153
John McCall8ccfcb52009-09-24 19:53:00 +00002154 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002155}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002156
John McCall4f5019e2010-12-19 02:44:49 +00002157const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2158 FunctionType::ExtInfo Info) {
2159 if (T->getExtInfo() == Info)
2160 return T;
2161
2162 QualType Result;
2163 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002164 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002165 } else {
2166 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2167 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2168 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002169 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002170 }
2171
2172 return cast<FunctionType>(Result.getTypePtr());
2173}
2174
Richard Smith2a7d4812013-05-04 07:00:32 +00002175void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2176 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002177 FD = FD->getMostRecentDecl();
2178 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002179 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2180 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002181 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002182 if (FunctionDecl *Next = FD->getPreviousDecl())
2183 FD = Next;
2184 else
2185 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002186 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002187 if (ASTMutationListener *L = getASTMutationListener())
2188 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002189}
2190
Richard Smith0b3a4622014-11-13 20:01:57 +00002191/// Get a function type and produce the equivalent function type with the
2192/// specified exception specification. Type sugar that can be present on a
2193/// declaration of a function with an exception specification is permitted
2194/// and preserved. Other type sugar (for instance, typedefs) is not.
2195static QualType getFunctionTypeWithExceptionSpec(
2196 ASTContext &Context, QualType Orig,
2197 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2198 // Might have some parens.
2199 if (auto *PT = dyn_cast<ParenType>(Orig))
2200 return Context.getParenType(
2201 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2202
2203 // Might have a calling-convention attribute.
2204 if (auto *AT = dyn_cast<AttributedType>(Orig))
2205 return Context.getAttributedType(
2206 AT->getAttrKind(),
2207 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2208 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2209 ESI));
2210
2211 // Anything else must be a function type. Rebuild it with the new exception
2212 // specification.
2213 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2214 return Context.getFunctionType(
2215 Proto->getReturnType(), Proto->getParamTypes(),
2216 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2217}
2218
2219void ASTContext::adjustExceptionSpec(
2220 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2221 bool AsWritten) {
2222 // Update the type.
2223 QualType Updated =
2224 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2225 FD->setType(Updated);
2226
2227 if (!AsWritten)
2228 return;
2229
2230 // Update the type in the type source information too.
2231 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2232 // If the type and the type-as-written differ, we may need to update
2233 // the type-as-written too.
2234 if (TSInfo->getType() != FD->getType())
2235 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2236
2237 // FIXME: When we get proper type location information for exceptions,
2238 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2239 // up the TypeSourceInfo;
2240 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2241 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2242 "TypeLoc size mismatch from updating exception specification");
2243 TSInfo->overrideType(Updated);
2244 }
2245}
2246
Chris Lattnerc6395932007-06-22 20:56:16 +00002247/// getComplexType - Return the uniqued reference to the type for a complex
2248/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002249QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002250 // Unique pointers, to guarantee there is only one pointer of a particular
2251 // structure.
2252 llvm::FoldingSetNodeID ID;
2253 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002254
Craig Topper36250ad2014-05-12 05:36:57 +00002255 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002256 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2257 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002258
Chris Lattnerc6395932007-06-22 20:56:16 +00002259 // If the pointee type isn't canonical, this won't be a canonical type either,
2260 // so fill in the canonical type field.
2261 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002262 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002263 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002264
Chris Lattnerc6395932007-06-22 20:56:16 +00002265 // Get the new insert position for the node we care about.
2266 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002267 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002268 }
John McCall90d1c2d2009-09-24 23:30:46 +00002269 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002270 Types.push_back(New);
2271 ComplexTypes.InsertNode(New, InsertPos);
2272 return QualType(New, 0);
2273}
2274
Chris Lattner970e54e2006-11-12 00:37:36 +00002275/// getPointerType - Return the uniqued reference to the type for a pointer to
2276/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002277QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002278 // Unique pointers, to guarantee there is only one pointer of a particular
2279 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002280 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002281 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002282
Craig Topper36250ad2014-05-12 05:36:57 +00002283 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002284 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002285 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002286
Chris Lattner7ccecb92006-11-12 08:50:50 +00002287 // If the pointee type isn't canonical, this won't be a canonical type either,
2288 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002289 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002290 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002291 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002292
Bob Wilsonc8541f22013-03-15 17:12:43 +00002293 // Get the new insert position for the node we care about.
2294 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002295 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002296 }
John McCall90d1c2d2009-09-24 23:30:46 +00002297 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002298 Types.push_back(New);
2299 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002300 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002301}
2302
Reid Kleckner0503a872013-12-05 01:23:43 +00002303QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2304 llvm::FoldingSetNodeID ID;
2305 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002306 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002307 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2308 if (AT)
2309 return QualType(AT, 0);
2310
2311 QualType Canonical = getCanonicalType(New);
2312
2313 // Get the new insert position for the node we care about.
2314 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002315 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002316
2317 AT = new (*this, TypeAlignment)
2318 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2319 Types.push_back(AT);
2320 AdjustedTypes.InsertNode(AT, InsertPos);
2321 return QualType(AT, 0);
2322}
2323
Reid Kleckner8a365022013-06-24 17:51:48 +00002324QualType ASTContext::getDecayedType(QualType T) const {
2325 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2326
Reid Kleckner8a365022013-06-24 17:51:48 +00002327 QualType Decayed;
2328
2329 // C99 6.7.5.3p7:
2330 // A declaration of a parameter as "array of type" shall be
2331 // adjusted to "qualified pointer to type", where the type
2332 // qualifiers (if any) are those specified within the [ and ] of
2333 // the array type derivation.
2334 if (T->isArrayType())
2335 Decayed = getArrayDecayedType(T);
2336
2337 // C99 6.7.5.3p8:
2338 // A declaration of a parameter as "function returning type"
2339 // shall be adjusted to "pointer to function returning type", as
2340 // in 6.3.2.1.
2341 if (T->isFunctionType())
2342 Decayed = getPointerType(T);
2343
Reid Kleckner0503a872013-12-05 01:23:43 +00002344 llvm::FoldingSetNodeID ID;
2345 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002346 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002347 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2348 if (AT)
2349 return QualType(AT, 0);
2350
Reid Kleckner8a365022013-06-24 17:51:48 +00002351 QualType Canonical = getCanonicalType(Decayed);
2352
2353 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002354 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002355 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002356
Reid Kleckner0503a872013-12-05 01:23:43 +00002357 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2358 Types.push_back(AT);
2359 AdjustedTypes.InsertNode(AT, InsertPos);
2360 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002361}
2362
Mike Stump11289f42009-09-09 15:08:12 +00002363/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002364/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002365QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002366 assert(T->isFunctionType() && "block of function types only");
2367 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002368 // structure.
2369 llvm::FoldingSetNodeID ID;
2370 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002371
Craig Topper36250ad2014-05-12 05:36:57 +00002372 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002373 if (BlockPointerType *PT =
2374 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2375 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002376
2377 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002378 // type either so fill in the canonical type field.
2379 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002380 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002381 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002382
Steve Naroffec33ed92008-08-27 16:04:49 +00002383 // Get the new insert position for the node we care about.
2384 BlockPointerType *NewIP =
2385 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002386 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002387 }
John McCall90d1c2d2009-09-24 23:30:46 +00002388 BlockPointerType *New
2389 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002390 Types.push_back(New);
2391 BlockPointerTypes.InsertNode(New, InsertPos);
2392 return QualType(New, 0);
2393}
2394
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002395/// getLValueReferenceType - Return the uniqued reference to the type for an
2396/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002397QualType
2398ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002399 assert(getCanonicalType(T) != OverloadTy &&
2400 "Unresolved overloaded function type");
2401
Bill Wendling3708c182007-05-27 10:15:43 +00002402 // Unique pointers, to guarantee there is only one pointer of a particular
2403 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002404 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002405 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002406
Craig Topper36250ad2014-05-12 05:36:57 +00002407 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002408 if (LValueReferenceType *RT =
2409 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002410 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002411
John McCallfc93cf92009-10-22 22:37:11 +00002412 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2413
Bill Wendling3708c182007-05-27 10:15:43 +00002414 // If the referencee type isn't canonical, this won't be a canonical type
2415 // either, so fill in the canonical type field.
2416 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002417 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2418 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2419 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002420
Bill Wendling3708c182007-05-27 10:15:43 +00002421 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002422 LValueReferenceType *NewIP =
2423 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002424 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002425 }
2426
John McCall90d1c2d2009-09-24 23:30:46 +00002427 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002428 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2429 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002430 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002431 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002432
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002433 return QualType(New, 0);
2434}
2435
2436/// getRValueReferenceType - Return the uniqued reference to the type for an
2437/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002438QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002439 // Unique pointers, to guarantee there is only one pointer of a particular
2440 // structure.
2441 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002442 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002443
Craig Topper36250ad2014-05-12 05:36:57 +00002444 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002445 if (RValueReferenceType *RT =
2446 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2447 return QualType(RT, 0);
2448
John McCallfc93cf92009-10-22 22:37:11 +00002449 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2450
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002451 // If the referencee type isn't canonical, this won't be a canonical type
2452 // either, so fill in the canonical type field.
2453 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002454 if (InnerRef || !T.isCanonical()) {
2455 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2456 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002457
2458 // Get the new insert position for the node we care about.
2459 RValueReferenceType *NewIP =
2460 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002461 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002462 }
2463
John McCall90d1c2d2009-09-24 23:30:46 +00002464 RValueReferenceType *New
2465 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002466 Types.push_back(New);
2467 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002468 return QualType(New, 0);
2469}
2470
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002471/// getMemberPointerType - Return the uniqued reference to the type for a
2472/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002473QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002474 // Unique pointers, to guarantee there is only one pointer of a particular
2475 // structure.
2476 llvm::FoldingSetNodeID ID;
2477 MemberPointerType::Profile(ID, T, Cls);
2478
Craig Topper36250ad2014-05-12 05:36:57 +00002479 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002480 if (MemberPointerType *PT =
2481 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2482 return QualType(PT, 0);
2483
2484 // If the pointee or class type isn't canonical, this won't be a canonical
2485 // type either, so fill in the canonical type field.
2486 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002487 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002488 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2489
2490 // Get the new insert position for the node we care about.
2491 MemberPointerType *NewIP =
2492 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002493 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002494 }
John McCall90d1c2d2009-09-24 23:30:46 +00002495 MemberPointerType *New
2496 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002497 Types.push_back(New);
2498 MemberPointerTypes.InsertNode(New, InsertPos);
2499 return QualType(New, 0);
2500}
2501
Mike Stump11289f42009-09-09 15:08:12 +00002502/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002503/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002504QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002505 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002506 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002507 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002508 assert((EltTy->isDependentType() ||
2509 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002510 "Constant array of VLAs is illegal!");
2511
Chris Lattnere2df3f92009-05-13 04:12:56 +00002512 // Convert the array size into a canonical width matching the pointer size for
2513 // the target.
2514 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002515 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002516 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002517
Chris Lattner23b7eb62007-06-15 23:05:46 +00002518 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002519 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002520
Craig Topper36250ad2014-05-12 05:36:57 +00002521 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002522 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002523 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002524 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002525
John McCall33ddac02011-01-19 10:06:00 +00002526 // If the element type isn't canonical or has qualifiers, this won't
2527 // be a canonical type either, so fill in the canonical type field.
2528 QualType Canon;
2529 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2530 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002531 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002532 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002533 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002534
Chris Lattner36f8e652007-01-27 08:31:04 +00002535 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002536 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002537 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002538 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002539 }
Mike Stump11289f42009-09-09 15:08:12 +00002540
John McCall90d1c2d2009-09-24 23:30:46 +00002541 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002542 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002543 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002544 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002545 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002546}
2547
John McCall06549462011-01-18 08:40:38 +00002548/// getVariableArrayDecayedType - Turns the given type, which may be
2549/// variably-modified, into the corresponding type with all the known
2550/// sizes replaced with [*].
2551QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2552 // Vastly most common case.
2553 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002554
John McCall06549462011-01-18 08:40:38 +00002555 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002556
John McCall06549462011-01-18 08:40:38 +00002557 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002558 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002559 switch (ty->getTypeClass()) {
2560#define TYPE(Class, Base)
2561#define ABSTRACT_TYPE(Class, Base)
2562#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2563#include "clang/AST/TypeNodes.def"
2564 llvm_unreachable("didn't desugar past all non-canonical types?");
2565
2566 // These types should never be variably-modified.
2567 case Type::Builtin:
2568 case Type::Complex:
2569 case Type::Vector:
2570 case Type::ExtVector:
2571 case Type::DependentSizedExtVector:
2572 case Type::ObjCObject:
2573 case Type::ObjCInterface:
2574 case Type::ObjCObjectPointer:
2575 case Type::Record:
2576 case Type::Enum:
2577 case Type::UnresolvedUsing:
2578 case Type::TypeOfExpr:
2579 case Type::TypeOf:
2580 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002581 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002582 case Type::DependentName:
2583 case Type::InjectedClassName:
2584 case Type::TemplateSpecialization:
2585 case Type::DependentTemplateSpecialization:
2586 case Type::TemplateTypeParm:
2587 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002588 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002589 case Type::PackExpansion:
2590 llvm_unreachable("type should never be variably-modified");
2591
2592 // These types can be variably-modified but should never need to
2593 // further decay.
2594 case Type::FunctionNoProto:
2595 case Type::FunctionProto:
2596 case Type::BlockPointer:
2597 case Type::MemberPointer:
2598 return type;
2599
2600 // These types can be variably-modified. All these modifications
2601 // preserve structure except as noted by comments.
2602 // TODO: if we ever care about optimizing VLAs, there are no-op
2603 // optimizations available here.
2604 case Type::Pointer:
2605 result = getPointerType(getVariableArrayDecayedType(
2606 cast<PointerType>(ty)->getPointeeType()));
2607 break;
2608
2609 case Type::LValueReference: {
2610 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2611 result = getLValueReferenceType(
2612 getVariableArrayDecayedType(lv->getPointeeType()),
2613 lv->isSpelledAsLValue());
2614 break;
2615 }
2616
2617 case Type::RValueReference: {
2618 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2619 result = getRValueReferenceType(
2620 getVariableArrayDecayedType(lv->getPointeeType()));
2621 break;
2622 }
2623
Eli Friedman0dfb8892011-10-06 23:00:33 +00002624 case Type::Atomic: {
2625 const AtomicType *at = cast<AtomicType>(ty);
2626 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2627 break;
2628 }
2629
John McCall06549462011-01-18 08:40:38 +00002630 case Type::ConstantArray: {
2631 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2632 result = getConstantArrayType(
2633 getVariableArrayDecayedType(cat->getElementType()),
2634 cat->getSize(),
2635 cat->getSizeModifier(),
2636 cat->getIndexTypeCVRQualifiers());
2637 break;
2638 }
2639
2640 case Type::DependentSizedArray: {
2641 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2642 result = getDependentSizedArrayType(
2643 getVariableArrayDecayedType(dat->getElementType()),
2644 dat->getSizeExpr(),
2645 dat->getSizeModifier(),
2646 dat->getIndexTypeCVRQualifiers(),
2647 dat->getBracketsRange());
2648 break;
2649 }
2650
2651 // Turn incomplete types into [*] types.
2652 case Type::IncompleteArray: {
2653 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2654 result = getVariableArrayType(
2655 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002656 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002657 ArrayType::Normal,
2658 iat->getIndexTypeCVRQualifiers(),
2659 SourceRange());
2660 break;
2661 }
2662
2663 // Turn VLA types into [*] types.
2664 case Type::VariableArray: {
2665 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2666 result = getVariableArrayType(
2667 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002668 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002669 ArrayType::Star,
2670 vat->getIndexTypeCVRQualifiers(),
2671 vat->getBracketsRange());
2672 break;
2673 }
2674 }
2675
2676 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002677 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002678}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002679
Steve Naroffcadebd02007-08-30 18:14:25 +00002680/// getVariableArrayType - Returns a non-unique reference to the type for a
2681/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002682QualType ASTContext::getVariableArrayType(QualType EltTy,
2683 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002684 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002685 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002686 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002687 // Since we don't unique expressions, it isn't possible to unique VLA's
2688 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002689 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002690
John McCall33ddac02011-01-19 10:06:00 +00002691 // Be sure to pull qualifiers off the element type.
2692 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2693 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002694 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002695 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002696 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002697 }
2698
John McCall90d1c2d2009-09-24 23:30:46 +00002699 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002700 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002701
2702 VariableArrayTypes.push_back(New);
2703 Types.push_back(New);
2704 return QualType(New, 0);
2705}
2706
Douglas Gregor4619e432008-12-05 23:32:09 +00002707/// getDependentSizedArrayType - Returns a non-unique reference to
2708/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002709/// type.
John McCall33ddac02011-01-19 10:06:00 +00002710QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2711 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002712 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002713 unsigned elementTypeQuals,
2714 SourceRange brackets) const {
2715 assert((!numElements || numElements->isTypeDependent() ||
2716 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002717 "Size must be type- or value-dependent!");
2718
John McCall33ddac02011-01-19 10:06:00 +00002719 // Dependently-sized array types that do not have a specified number
2720 // of elements will have their sizes deduced from a dependent
2721 // initializer. We do no canonicalization here at all, which is okay
2722 // because they can't be used in most locations.
2723 if (!numElements) {
2724 DependentSizedArrayType *newType
2725 = new (*this, TypeAlignment)
2726 DependentSizedArrayType(*this, elementType, QualType(),
2727 numElements, ASM, elementTypeQuals,
2728 brackets);
2729 Types.push_back(newType);
2730 return QualType(newType, 0);
2731 }
2732
2733 // Otherwise, we actually build a new type every time, but we
2734 // also build a canonical type.
2735
2736 SplitQualType canonElementType = getCanonicalType(elementType).split();
2737
Craig Topper36250ad2014-05-12 05:36:57 +00002738 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002739 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002740 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002741 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002742 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002743
John McCall33ddac02011-01-19 10:06:00 +00002744 // Look for an existing type with these properties.
2745 DependentSizedArrayType *canonTy =
2746 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002747
John McCall33ddac02011-01-19 10:06:00 +00002748 // If we don't have one, build one.
2749 if (!canonTy) {
2750 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002751 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002752 QualType(), numElements, ASM, elementTypeQuals,
2753 brackets);
2754 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2755 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002756 }
2757
John McCall33ddac02011-01-19 10:06:00 +00002758 // Apply qualifiers from the element type to the array.
2759 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002760 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002761
John McCall33ddac02011-01-19 10:06:00 +00002762 // If we didn't need extra canonicalization for the element type,
2763 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002764 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002765 return canon;
2766
2767 // Otherwise, we need to build a type which follows the spelling
2768 // of the element type.
2769 DependentSizedArrayType *sugaredType
2770 = new (*this, TypeAlignment)
2771 DependentSizedArrayType(*this, elementType, canon, numElements,
2772 ASM, elementTypeQuals, brackets);
2773 Types.push_back(sugaredType);
2774 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002775}
2776
John McCall33ddac02011-01-19 10:06:00 +00002777QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002778 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002779 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002780 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002781 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002782
Craig Topper36250ad2014-05-12 05:36:57 +00002783 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002784 if (IncompleteArrayType *iat =
2785 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2786 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002787
2788 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002789 // either, so fill in the canonical type field. We also have to pull
2790 // qualifiers off the element type.
2791 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002792
John McCall33ddac02011-01-19 10:06:00 +00002793 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2794 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002795 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002796 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002797 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002798
2799 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002800 IncompleteArrayType *existing =
2801 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2802 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002803 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002804
John McCall33ddac02011-01-19 10:06:00 +00002805 IncompleteArrayType *newType = new (*this, TypeAlignment)
2806 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002807
John McCall33ddac02011-01-19 10:06:00 +00002808 IncompleteArrayTypes.InsertNode(newType, insertPos);
2809 Types.push_back(newType);
2810 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002811}
2812
Steve Naroff91fcddb2007-07-18 18:00:27 +00002813/// getVectorType - Return the unique reference to a vector type of
2814/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002815QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002816 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002817 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002818
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002819 // Check if we've already instantiated a vector of this type.
2820 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002821 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002822
Craig Topper36250ad2014-05-12 05:36:57 +00002823 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002824 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2825 return QualType(VTP, 0);
2826
2827 // If the element type isn't canonical, this won't be a canonical type either,
2828 // so fill in the canonical type field.
2829 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002830 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002831 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002832
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002833 // Get the new insert position for the node we care about.
2834 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002835 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002836 }
John McCall90d1c2d2009-09-24 23:30:46 +00002837 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002838 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002839 VectorTypes.InsertNode(New, InsertPos);
2840 Types.push_back(New);
2841 return QualType(New, 0);
2842}
2843
Nate Begemance4d7fc2008-04-18 23:10:10 +00002844/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002845/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002846QualType
2847ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002848 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002849
Steve Naroff91fcddb2007-07-18 18:00:27 +00002850 // Check if we've already instantiated a vector of this type.
2851 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002852 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002853 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002854 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002855 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2856 return QualType(VTP, 0);
2857
2858 // If the element type isn't canonical, this won't be a canonical type either,
2859 // so fill in the canonical type field.
2860 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002861 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002862 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002863
Steve Naroff91fcddb2007-07-18 18:00:27 +00002864 // Get the new insert position for the node we care about.
2865 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002866 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002867 }
John McCall90d1c2d2009-09-24 23:30:46 +00002868 ExtVectorType *New = new (*this, TypeAlignment)
2869 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002870 VectorTypes.InsertNode(New, InsertPos);
2871 Types.push_back(New);
2872 return QualType(New, 0);
2873}
2874
Jay Foad39c79802011-01-12 09:06:06 +00002875QualType
2876ASTContext::getDependentSizedExtVectorType(QualType vecType,
2877 Expr *SizeExpr,
2878 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002879 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002880 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002881 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002882
Craig Topper36250ad2014-05-12 05:36:57 +00002883 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002884 DependentSizedExtVectorType *Canon
2885 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2886 DependentSizedExtVectorType *New;
2887 if (Canon) {
2888 // We already have a canonical version of this array type; use it as
2889 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002890 New = new (*this, TypeAlignment)
2891 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2892 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002893 } else {
2894 QualType CanonVecTy = getCanonicalType(vecType);
2895 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002896 New = new (*this, TypeAlignment)
2897 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2898 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002899
2900 DependentSizedExtVectorType *CanonCheck
2901 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2902 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2903 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002904 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2905 } else {
2906 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2907 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002908 New = new (*this, TypeAlignment)
2909 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002910 }
2911 }
Mike Stump11289f42009-09-09 15:08:12 +00002912
Douglas Gregor758a8692009-06-17 21:51:59 +00002913 Types.push_back(New);
2914 return QualType(New, 0);
2915}
2916
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002917/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002918///
Jay Foad39c79802011-01-12 09:06:06 +00002919QualType
2920ASTContext::getFunctionNoProtoType(QualType ResultTy,
2921 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002922 const CallingConv CallConv = Info.getCC();
2923
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002924 // Unique functions, to guarantee there is only one function of a particular
2925 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002926 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002927 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002928
Craig Topper36250ad2014-05-12 05:36:57 +00002929 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002930 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002931 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002932 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002933
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002934 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002935 if (!ResultTy.isCanonical()) {
2936 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002937
Chris Lattner47955de2007-01-27 08:37:20 +00002938 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002939 FunctionNoProtoType *NewIP =
2940 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002941 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002942 }
Mike Stump11289f42009-09-09 15:08:12 +00002943
Roman Divacky65b88cd2011-03-01 17:40:53 +00002944 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002945 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002946 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002947 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002948 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002949 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002950}
2951
Douglas Gregorcd780372013-01-17 23:36:45 +00002952/// \brief Determine whether \p T is canonical as the result type of a function.
2953static bool isCanonicalResultType(QualType T) {
2954 return T.isCanonical() &&
2955 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2956 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2957}
2958
Jay Foad39c79802011-01-12 09:06:06 +00002959QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002960ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002961 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002962 size_t NumArgs = ArgArray.size();
2963
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002964 // Unique functions, to guarantee there is only one function of a particular
2965 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002966 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002967 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2968 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002969
Craig Topper36250ad2014-05-12 05:36:57 +00002970 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002971 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002972 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002973 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002974
2975 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002976 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00002977 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002978 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002979 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002980 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002981 isCanonical = false;
2982
2983 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002984 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002985 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002986 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002987 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002988 CanonicalArgs.reserve(NumArgs);
2989 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002990 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002991
John McCalldb40c7f2010-12-14 08:05:40 +00002992 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002993 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00002994 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00002995
Douglas Gregorcd780372013-01-17 23:36:45 +00002996 // Result types do not have ARC lifetime qualifiers.
2997 QualType CanResultTy = getCanonicalType(ResultTy);
2998 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2999 Qualifiers Qs = CanResultTy.getQualifiers();
3000 Qs.removeObjCLifetime();
3001 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
3002 }
3003
Jordan Rose5c382722013-03-08 21:51:21 +00003004 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003005
Chris Lattnerfd4de792007-01-27 01:15:32 +00003006 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003007 FunctionProtoType *NewIP =
3008 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003009 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003010 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003011
John McCall31168b02011-06-15 23:02:42 +00003012 // FunctionProtoType objects are allocated with extra bytes after
3013 // them for three variable size arrays at the end:
3014 // - parameter types
3015 // - exception types
3016 // - consumed-arguments flags
3017 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003018 // expression, or information used to resolve the exception
3019 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003020 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003021 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00003022 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3023 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3024 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003025 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003026 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003027 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003028 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003029 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003030 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003031 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00003032 Size += NumArgs * sizeof(bool);
3033
John McCalldb40c7f2010-12-14 08:05:40 +00003034 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003035 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003036 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003037 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003038 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003039 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003040}
Chris Lattneref51c202006-11-10 07:17:23 +00003041
John McCalle78aac42010-03-10 03:28:59 +00003042#ifndef NDEBUG
3043static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3044 if (!isa<CXXRecordDecl>(D)) return false;
3045 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3046 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3047 return true;
3048 if (RD->getDescribedClassTemplate() &&
3049 !isa<ClassTemplateSpecializationDecl>(RD))
3050 return true;
3051 return false;
3052}
3053#endif
3054
3055/// getInjectedClassNameType - Return the unique reference to the
3056/// injected class name type for the specified templated declaration.
3057QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003058 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003059 assert(NeedsInjectedClassNameType(Decl));
3060 if (Decl->TypeForDecl) {
3061 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003062 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003063 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3064 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3065 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3066 } else {
John McCall424cec92011-01-19 06:33:43 +00003067 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003068 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003069 Decl->TypeForDecl = newType;
3070 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003071 }
3072 return QualType(Decl->TypeForDecl, 0);
3073}
3074
Douglas Gregor83a586e2008-04-13 21:07:44 +00003075/// getTypeDeclType - Return the unique reference to the type for the
3076/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003077QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003078 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003079 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003080
Richard Smithdda56e42011-04-15 14:24:37 +00003081 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003082 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003083
John McCall96f0b5f2010-03-10 06:48:02 +00003084 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3085 "Template type parameter types are always available.");
3086
John McCall81e38502010-02-16 03:57:14 +00003087 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003088 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003089 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003090 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003091 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003092 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003093 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003094 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003095 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003096 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3097 Decl->TypeForDecl = newType;
3098 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003099 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003100 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003101
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003102 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003103}
3104
Chris Lattner32d920b2007-01-26 02:01:53 +00003105/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003106/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003107QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003108ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3109 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003110 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003111
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003112 if (Canonical.isNull())
3113 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003114 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003115 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003116 Decl->TypeForDecl = newType;
3117 Types.push_back(newType);
3118 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003119}
3120
Jay Foad39c79802011-01-12 09:06:06 +00003121QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003122 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3123
Douglas Gregorec9fd132012-01-14 16:38:05 +00003124 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003125 if (PrevDecl->TypeForDecl)
3126 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3127
John McCall424cec92011-01-19 06:33:43 +00003128 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3129 Decl->TypeForDecl = newType;
3130 Types.push_back(newType);
3131 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003132}
3133
Jay Foad39c79802011-01-12 09:06:06 +00003134QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003135 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3136
Douglas Gregorec9fd132012-01-14 16:38:05 +00003137 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003138 if (PrevDecl->TypeForDecl)
3139 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3140
John McCall424cec92011-01-19 06:33:43 +00003141 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3142 Decl->TypeForDecl = newType;
3143 Types.push_back(newType);
3144 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003145}
3146
John McCall81904512011-01-06 01:58:22 +00003147QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3148 QualType modifiedType,
3149 QualType equivalentType) {
3150 llvm::FoldingSetNodeID id;
3151 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3152
Craig Topper36250ad2014-05-12 05:36:57 +00003153 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003154 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3155 if (type) return QualType(type, 0);
3156
3157 QualType canon = getCanonicalType(equivalentType);
3158 type = new (*this, TypeAlignment)
3159 AttributedType(canon, attrKind, modifiedType, equivalentType);
3160
3161 Types.push_back(type);
3162 AttributedTypes.InsertNode(type, insertPos);
3163
3164 return QualType(type, 0);
3165}
3166
3167
John McCallcebee162009-10-18 09:09:24 +00003168/// \brief Retrieve a substitution-result type.
3169QualType
3170ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003171 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003172 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003173 && "replacement types must always be canonical");
3174
3175 llvm::FoldingSetNodeID ID;
3176 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003177 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003178 SubstTemplateTypeParmType *SubstParm
3179 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3180
3181 if (!SubstParm) {
3182 SubstParm = new (*this, TypeAlignment)
3183 SubstTemplateTypeParmType(Parm, Replacement);
3184 Types.push_back(SubstParm);
3185 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3186 }
3187
3188 return QualType(SubstParm, 0);
3189}
3190
Douglas Gregorada4b792011-01-14 02:55:32 +00003191/// \brief Retrieve a
3192QualType ASTContext::getSubstTemplateTypeParmPackType(
3193 const TemplateTypeParmType *Parm,
3194 const TemplateArgument &ArgPack) {
3195#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003196 for (const auto &P : ArgPack.pack_elements()) {
3197 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3198 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003199 }
3200#endif
3201
3202 llvm::FoldingSetNodeID ID;
3203 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003204 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003205 if (SubstTemplateTypeParmPackType *SubstParm
3206 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3207 return QualType(SubstParm, 0);
3208
3209 QualType Canon;
3210 if (!Parm->isCanonicalUnqualified()) {
3211 Canon = getCanonicalType(QualType(Parm, 0));
3212 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3213 ArgPack);
3214 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3215 }
3216
3217 SubstTemplateTypeParmPackType *SubstParm
3218 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3219 ArgPack);
3220 Types.push_back(SubstParm);
3221 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3222 return QualType(SubstParm, 0);
3223}
3224
Douglas Gregoreff93e02009-02-05 23:33:38 +00003225/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003226/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003227/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003228QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003229 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003230 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003231 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003232 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003233 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003234 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003235 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3236
3237 if (TypeParm)
3238 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003239
Chandler Carruth08836322011-05-01 00:51:33 +00003240 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003241 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003242 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003243
3244 TemplateTypeParmType *TypeCheck
3245 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3246 assert(!TypeCheck && "Template type parameter canonical type broken");
3247 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003248 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003249 TypeParm = new (*this, TypeAlignment)
3250 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003251
3252 Types.push_back(TypeParm);
3253 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3254
3255 return QualType(TypeParm, 0);
3256}
3257
John McCalle78aac42010-03-10 03:28:59 +00003258TypeSourceInfo *
3259ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3260 SourceLocation NameLoc,
3261 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003262 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003263 assert(!Name.getAsDependentTemplateName() &&
3264 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003265 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003266
3267 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003268 TemplateSpecializationTypeLoc TL =
3269 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003270 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003271 TL.setTemplateNameLoc(NameLoc);
3272 TL.setLAngleLoc(Args.getLAngleLoc());
3273 TL.setRAngleLoc(Args.getRAngleLoc());
3274 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3275 TL.setArgLocInfo(i, Args[i].getLocInfo());
3276 return DI;
3277}
3278
Mike Stump11289f42009-09-09 15:08:12 +00003279QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003280ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003281 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003282 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003283 assert(!Template.getAsDependentTemplateName() &&
3284 "No dependent template names here!");
3285
John McCall6b51f282009-11-23 01:53:49 +00003286 unsigned NumArgs = Args.size();
3287
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003288 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003289 ArgVec.reserve(NumArgs);
3290 for (unsigned i = 0; i != NumArgs; ++i)
3291 ArgVec.push_back(Args[i].getArgument());
3292
John McCall2408e322010-04-27 00:57:59 +00003293 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003294 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003295}
3296
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003297#ifndef NDEBUG
3298static bool hasAnyPackExpansions(const TemplateArgument *Args,
3299 unsigned NumArgs) {
3300 for (unsigned I = 0; I != NumArgs; ++I)
3301 if (Args[I].isPackExpansion())
3302 return true;
3303
3304 return true;
3305}
3306#endif
3307
John McCall0ad16662009-10-29 08:12:44 +00003308QualType
3309ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003310 const TemplateArgument *Args,
3311 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003312 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003313 assert(!Template.getAsDependentTemplateName() &&
3314 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003315 // Look through qualified template names.
3316 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3317 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003318
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003319 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003320 Template.getAsTemplateDecl() &&
3321 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003322 QualType CanonType;
3323 if (!Underlying.isNull())
3324 CanonType = getCanonicalType(Underlying);
3325 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003326 // We can get here with an alias template when the specialization contains
3327 // a pack expansion that does not match up with a parameter pack.
3328 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3329 "Caller must compute aliased type");
3330 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003331 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3332 NumArgs);
3333 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003334
Douglas Gregora8e02e72009-07-28 23:00:59 +00003335 // Allocate the (non-canonical) template specialization type, but don't
3336 // try to unique it: these types typically have location information that
3337 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003338 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3339 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003340 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003341 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003342 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003343 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3344 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003345
Douglas Gregor8bf42052009-02-09 18:46:07 +00003346 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003347 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003348}
3349
Mike Stump11289f42009-09-09 15:08:12 +00003350QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003351ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3352 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003353 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003354 assert(!Template.getAsDependentTemplateName() &&
3355 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003356
Douglas Gregore29139c2011-03-03 17:04:51 +00003357 // Look through qualified template names.
3358 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3359 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003360
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003361 // Build the canonical template specialization type.
3362 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003363 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003364 CanonArgs.reserve(NumArgs);
3365 for (unsigned I = 0; I != NumArgs; ++I)
3366 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3367
3368 // Determine whether this canonical template specialization type already
3369 // exists.
3370 llvm::FoldingSetNodeID ID;
3371 TemplateSpecializationType::Profile(ID, CanonTemplate,
3372 CanonArgs.data(), NumArgs, *this);
3373
Craig Topper36250ad2014-05-12 05:36:57 +00003374 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003375 TemplateSpecializationType *Spec
3376 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3377
3378 if (!Spec) {
3379 // Allocate a new canonical template specialization type.
3380 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3381 sizeof(TemplateArgument) * NumArgs),
3382 TypeAlignment);
3383 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3384 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003385 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003386 Types.push_back(Spec);
3387 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3388 }
3389
3390 assert(Spec->isDependentType() &&
3391 "Non-dependent template-id type must have a canonical type");
3392 return QualType(Spec, 0);
3393}
3394
3395QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003396ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3397 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003398 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003399 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003400 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003401
Craig Topper36250ad2014-05-12 05:36:57 +00003402 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003403 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003404 if (T)
3405 return QualType(T, 0);
3406
Douglas Gregorc42075a2010-02-04 18:10:26 +00003407 QualType Canon = NamedType;
3408 if (!Canon.isCanonical()) {
3409 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003410 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3411 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003412 (void)CheckT;
3413 }
3414
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003415 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003416 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003417 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003418 return QualType(T, 0);
3419}
3420
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003421QualType
Jay Foad39c79802011-01-12 09:06:06 +00003422ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003423 llvm::FoldingSetNodeID ID;
3424 ParenType::Profile(ID, InnerType);
3425
Craig Topper36250ad2014-05-12 05:36:57 +00003426 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003427 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3428 if (T)
3429 return QualType(T, 0);
3430
3431 QualType Canon = InnerType;
3432 if (!Canon.isCanonical()) {
3433 Canon = getCanonicalType(InnerType);
3434 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3435 assert(!CheckT && "Paren canonical type broken");
3436 (void)CheckT;
3437 }
3438
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003439 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003440 Types.push_back(T);
3441 ParenTypes.InsertNode(T, InsertPos);
3442 return QualType(T, 0);
3443}
3444
Douglas Gregor02085352010-03-31 20:19:30 +00003445QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3446 NestedNameSpecifier *NNS,
3447 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003448 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003449 if (Canon.isNull()) {
3450 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003451 ElaboratedTypeKeyword CanonKeyword = Keyword;
3452 if (Keyword == ETK_None)
3453 CanonKeyword = ETK_Typename;
3454
3455 if (CanonNNS != NNS || CanonKeyword != Keyword)
3456 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003457 }
3458
3459 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003460 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003461
Craig Topper36250ad2014-05-12 05:36:57 +00003462 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003463 DependentNameType *T
3464 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003465 if (T)
3466 return QualType(T, 0);
3467
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003468 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003469 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003470 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003471 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003472}
3473
Mike Stump11289f42009-09-09 15:08:12 +00003474QualType
John McCallc392f372010-06-11 00:33:02 +00003475ASTContext::getDependentTemplateSpecializationType(
3476 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003477 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003478 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003479 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003480 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003481 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003482 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3483 ArgCopy.push_back(Args[I].getArgument());
3484 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3485 ArgCopy.size(),
3486 ArgCopy.data());
3487}
3488
3489QualType
3490ASTContext::getDependentTemplateSpecializationType(
3491 ElaboratedTypeKeyword Keyword,
3492 NestedNameSpecifier *NNS,
3493 const IdentifierInfo *Name,
3494 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003495 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003496 assert((!NNS || NNS->isDependent()) &&
3497 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003498
Douglas Gregorc42075a2010-02-04 18:10:26 +00003499 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003500 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3501 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003502
Craig Topper36250ad2014-05-12 05:36:57 +00003503 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003504 DependentTemplateSpecializationType *T
3505 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003506 if (T)
3507 return QualType(T, 0);
3508
John McCallc392f372010-06-11 00:33:02 +00003509 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003510
John McCallc392f372010-06-11 00:33:02 +00003511 ElaboratedTypeKeyword CanonKeyword = Keyword;
3512 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3513
3514 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003515 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003516 for (unsigned I = 0; I != NumArgs; ++I) {
3517 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3518 if (!CanonArgs[I].structurallyEquals(Args[I]))
3519 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003520 }
3521
John McCallc392f372010-06-11 00:33:02 +00003522 QualType Canon;
3523 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3524 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3525 Name, NumArgs,
3526 CanonArgs.data());
3527
3528 // Find the insert position again.
3529 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3530 }
3531
3532 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3533 sizeof(TemplateArgument) * NumArgs),
3534 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003535 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003536 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003537 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003538 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003539 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003540}
3541
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003542QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003543 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003544 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003545 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003546
3547 assert(Pattern->containsUnexpandedParameterPack() &&
3548 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003549 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003550 PackExpansionType *T
3551 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3552 if (T)
3553 return QualType(T, 0);
3554
3555 QualType Canon;
3556 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003557 Canon = getCanonicalType(Pattern);
3558 // The canonical type might not contain an unexpanded parameter pack, if it
3559 // contains an alias template specialization which ignores one of its
3560 // parameters.
3561 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003562 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003563
Richard Smith68eea502012-07-16 00:20:35 +00003564 // Find the insert position again, in case we inserted an element into
3565 // PackExpansionTypes and invalidated our insert position.
3566 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3567 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003568 }
3569
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003570 T = new (*this, TypeAlignment)
3571 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003572 Types.push_back(T);
3573 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003574 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003575}
3576
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003577/// CmpProtocolNames - Comparison predicate for sorting protocols
3578/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003579static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3580 ObjCProtocolDecl *const *RHS) {
3581 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003582}
3583
John McCall8b07ec22010-05-15 11:32:37 +00003584static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003585 unsigned NumProtocols) {
3586 if (NumProtocols == 0) return true;
3587
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003588 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3589 return false;
3590
John McCallfc93cf92009-10-22 22:37:11 +00003591 for (unsigned i = 1; i != NumProtocols; ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003592 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003593 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003594 return false;
3595 return true;
3596}
3597
3598static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003599 unsigned &NumProtocols) {
3600 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003601
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003602 // Sort protocols, keyed by name.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003603 llvm::array_pod_sort(Protocols, ProtocolsEnd, CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003604
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003605 // Canonicalize.
3606 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3607 Protocols[I] = Protocols[I]->getCanonicalDecl();
3608
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003609 // Remove duplicates.
3610 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3611 NumProtocols = ProtocolsEnd-Protocols;
3612}
3613
John McCall8b07ec22010-05-15 11:32:37 +00003614QualType ASTContext::getObjCObjectType(QualType BaseType,
3615 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003616 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003617 return getObjCObjectType(BaseType, { },
3618 llvm::makeArrayRef(Protocols, NumProtocols));
3619}
3620
3621QualType ASTContext::getObjCObjectType(
3622 QualType baseType,
3623 ArrayRef<QualType> typeArgs,
3624 ArrayRef<ObjCProtocolDecl *> protocols) const {
3625 // If the base type is an interface and there aren't any protocols or
3626 // type arguments to add, then the interface type will do just fine.
3627 if (typeArgs.empty() && protocols.empty() && isa<ObjCInterfaceType>(baseType))
3628 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003629
3630 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003631 llvm::FoldingSetNodeID ID;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003632 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols);
Craig Topper36250ad2014-05-12 05:36:57 +00003633 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003634 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3635 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003636
Douglas Gregore9d95f12015-07-07 03:57:35 +00003637 // Determine the type arguments to be used for canonicalization,
3638 // which may be explicitly specified here or written on the base
3639 // type.
3640 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3641 if (effectiveTypeArgs.empty()) {
3642 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3643 effectiveTypeArgs = baseObject->getTypeArgs();
3644 }
John McCallfc93cf92009-10-22 22:37:11 +00003645
Douglas Gregore9d95f12015-07-07 03:57:35 +00003646 // Build the canonical type, which has the canonical base type and a
3647 // sorted-and-uniqued list of protocols and the type arguments
3648 // canonicalized.
3649 QualType canonical;
3650 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3651 effectiveTypeArgs.end(),
3652 [&](QualType type) {
3653 return type.isCanonical();
3654 });
3655 bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3656 protocols.size());
3657 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3658 // Determine the canonical type arguments.
3659 ArrayRef<QualType> canonTypeArgs;
3660 SmallVector<QualType, 4> canonTypeArgsVec;
3661 if (!typeArgsAreCanonical) {
3662 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3663 for (auto typeArg : effectiveTypeArgs)
3664 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3665 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003666 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003667 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003668 }
3669
Douglas Gregore9d95f12015-07-07 03:57:35 +00003670 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3671 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3672 if (!protocolsSorted) {
3673 canonProtocolsVec.insert(canonProtocolsVec.begin(),
3674 protocols.begin(),
3675 protocols.end());
3676 unsigned uniqueCount = protocols.size();
3677 SortAndUniqueProtocols(&canonProtocolsVec[0], uniqueCount);
3678 canonProtocols = llvm::makeArrayRef(&canonProtocolsVec[0], uniqueCount);
3679 } else {
3680 canonProtocols = protocols;
3681 }
3682
3683 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
3684 canonProtocols);
3685
John McCallfc93cf92009-10-22 22:37:11 +00003686 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003687 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3688 }
3689
Douglas Gregore9d95f12015-07-07 03:57:35 +00003690 unsigned size = sizeof(ObjCObjectTypeImpl);
3691 size += typeArgs.size() * sizeof(QualType);
3692 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3693 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003694 ObjCObjectTypeImpl *T =
Douglas Gregore9d95f12015-07-07 03:57:35 +00003695 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols);
John McCall8b07ec22010-05-15 11:32:37 +00003696
3697 Types.push_back(T);
3698 ObjCObjectTypes.InsertNode(T, InsertPos);
3699 return QualType(T, 0);
3700}
3701
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003702/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3703/// protocol list adopt all protocols in QT's qualified-id protocol
3704/// list.
3705bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3706 ObjCInterfaceDecl *IC) {
3707 if (!QT->isObjCQualifiedIdType())
3708 return false;
3709
3710 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3711 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003712 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003713 if (!IC->ClassImplementsProtocol(Proto, false))
3714 return false;
3715 }
3716 return true;
3717 }
3718 return false;
3719}
3720
3721/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3722/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3723/// of protocols.
3724bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3725 ObjCInterfaceDecl *IDecl) {
3726 if (!QT->isObjCQualifiedIdType())
3727 return false;
3728 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3729 if (!OPT)
3730 return false;
3731 if (!IDecl->hasDefinition())
3732 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003733 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3734 CollectInheritedProtocols(IDecl, InheritedProtocols);
3735 if (InheritedProtocols.empty())
3736 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003737 // Check that if every protocol in list of id<plist> conforms to a protcol
3738 // of IDecl's, then bridge casting is ok.
3739 bool Conforms = false;
3740 for (auto *Proto : OPT->quals()) {
3741 Conforms = false;
3742 for (auto *PI : InheritedProtocols) {
3743 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3744 Conforms = true;
3745 break;
3746 }
3747 }
3748 if (!Conforms)
3749 break;
3750 }
3751 if (Conforms)
3752 return true;
3753
Aaron Ballman83731462014-03-17 16:14:00 +00003754 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003755 // If both the right and left sides have qualifiers.
3756 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003757 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003758 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003759 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003760 break;
3761 }
3762 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003763 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003764 }
3765 return true;
3766}
3767
John McCall8b07ec22010-05-15 11:32:37 +00003768/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3769/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003770QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003771 llvm::FoldingSetNodeID ID;
3772 ObjCObjectPointerType::Profile(ID, ObjectT);
3773
Craig Topper36250ad2014-05-12 05:36:57 +00003774 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003775 if (ObjCObjectPointerType *QT =
3776 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3777 return QualType(QT, 0);
3778
3779 // Find the canonical object type.
3780 QualType Canonical;
3781 if (!ObjectT.isCanonical()) {
3782 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3783
3784 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003785 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3786 }
3787
Douglas Gregorf85bee62010-02-08 22:59:26 +00003788 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003789 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3790 ObjCObjectPointerType *QType =
3791 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003792
Steve Narofffb4330f2009-06-17 22:40:22 +00003793 Types.push_back(QType);
3794 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003795 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003796}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003797
Douglas Gregor1c283312010-08-11 12:19:30 +00003798/// getObjCInterfaceType - Return the unique reference to the type for the
3799/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003800QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3801 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003802 if (Decl->TypeForDecl)
3803 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003804
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003805 if (PrevDecl) {
3806 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3807 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3808 return QualType(PrevDecl->TypeForDecl, 0);
3809 }
3810
Douglas Gregor7671e532011-12-16 16:34:57 +00003811 // Prefer the definition, if there is one.
3812 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3813 Decl = Def;
3814
Douglas Gregor1c283312010-08-11 12:19:30 +00003815 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3816 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3817 Decl->TypeForDecl = T;
3818 Types.push_back(T);
3819 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003820}
3821
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003822/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3823/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003824/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003825/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003826/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003827QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003828 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003829 if (tofExpr->isTypeDependent()) {
3830 llvm::FoldingSetNodeID ID;
3831 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003832
Craig Topper36250ad2014-05-12 05:36:57 +00003833 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003834 DependentTypeOfExprType *Canon
3835 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3836 if (Canon) {
3837 // We already have a "canonical" version of an identical, dependent
3838 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003839 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003840 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003841 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003842 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003843 Canon
3844 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003845 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3846 toe = Canon;
3847 }
3848 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003849 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003850 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003851 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003852 Types.push_back(toe);
3853 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003854}
3855
Steve Naroffa773cd52007-08-01 18:02:17 +00003856/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003857/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003858/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003859/// an issue. This doesn't affect the type checker, since it operates
3860/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003861QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003862 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003863 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003864 Types.push_back(tot);
3865 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003866}
3867
Anders Carlssonad6bd352009-06-24 21:24:56 +00003868
Richard Smith8eb1d322014-06-05 20:13:13 +00003869/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3870/// nodes. This would never be helpful, since each such type has its own
3871/// expression, and would not give a significant memory saving, since there
3872/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003873QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003874 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003875
3876 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003877 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003878 // unique dependent type. Two such decltype-specifiers refer to the same
3879 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003880 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003881 llvm::FoldingSetNodeID ID;
3882 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003883
Craig Topper36250ad2014-05-12 05:36:57 +00003884 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003885 DependentDecltypeType *Canon
3886 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003887 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003888 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003889 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003890 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003891 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003892 dt = new (*this, TypeAlignment)
3893 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003894 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003895 dt = new (*this, TypeAlignment)
3896 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003897 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003898 Types.push_back(dt);
3899 return QualType(dt, 0);
3900}
3901
Alexis Hunte852b102011-05-24 22:41:36 +00003902/// getUnaryTransformationType - We don't unique these, since the memory
3903/// savings are minimal and these are rare.
3904QualType ASTContext::getUnaryTransformType(QualType BaseType,
3905 QualType UnderlyingType,
3906 UnaryTransformType::UTTKind Kind)
3907 const {
3908 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003909 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3910 Kind,
3911 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003912 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003913 Types.push_back(Ty);
3914 return QualType(Ty, 0);
3915}
3916
Richard Smith2a7d4812013-05-04 07:00:32 +00003917/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3918/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3919/// canonical deduced-but-dependent 'auto' type.
3920QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003921 bool IsDependent) const {
3922 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003923 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003924
Richard Smith2a7d4812013-05-04 07:00:32 +00003925 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003926 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003927 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003928 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003929 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3930 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003931
Richard Smith74aeef52013-04-26 16:15:35 +00003932 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003933 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003934 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003935 Types.push_back(AT);
3936 if (InsertPos)
3937 AutoTypes.InsertNode(AT, InsertPos);
3938 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003939}
3940
Eli Friedman0dfb8892011-10-06 23:00:33 +00003941/// getAtomicType - Return the uniqued reference to the atomic type for
3942/// the given value type.
3943QualType ASTContext::getAtomicType(QualType T) const {
3944 // Unique pointers, to guarantee there is only one pointer of a particular
3945 // structure.
3946 llvm::FoldingSetNodeID ID;
3947 AtomicType::Profile(ID, T);
3948
Craig Topper36250ad2014-05-12 05:36:57 +00003949 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003950 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3951 return QualType(AT, 0);
3952
3953 // If the atomic value type isn't canonical, this won't be a canonical type
3954 // either, so fill in the canonical type field.
3955 QualType Canonical;
3956 if (!T.isCanonical()) {
3957 Canonical = getAtomicType(getCanonicalType(T));
3958
3959 // Get the new insert position for the node we care about.
3960 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003961 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003962 }
3963 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3964 Types.push_back(New);
3965 AtomicTypes.InsertNode(New, InsertPos);
3966 return QualType(New, 0);
3967}
3968
Richard Smith02e85f32011-04-14 22:09:26 +00003969/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3970QualType ASTContext::getAutoDeductType() const {
3971 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003972 AutoDeductTy = QualType(
3973 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003974 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003975 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003976 return AutoDeductTy;
3977}
3978
3979/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3980QualType ASTContext::getAutoRRefDeductType() const {
3981 if (AutoRRefDeductTy.isNull())
3982 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3983 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3984 return AutoRRefDeductTy;
3985}
3986
Chris Lattnerfb072462007-01-23 05:45:31 +00003987/// getTagDeclType - Return the unique reference to the type for the
3988/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003989QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003990 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003991 // FIXME: What is the design on getTagDeclType when it requires casting
3992 // away const? mutable?
3993 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003994}
3995
Mike Stump11289f42009-09-09 15:08:12 +00003996/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3997/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3998/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003999CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004000 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004001}
Chris Lattnerfb072462007-01-23 05:45:31 +00004002
Hans Wennborg27541db2011-10-27 08:29:09 +00004003/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4004CanQualType ASTContext::getIntMaxType() const {
4005 return getFromTargetType(Target->getIntMaxType());
4006}
4007
4008/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4009CanQualType ASTContext::getUIntMaxType() const {
4010 return getFromTargetType(Target->getUIntMaxType());
4011}
4012
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004013/// getSignedWCharType - Return the type of "signed wchar_t".
4014/// Used when in C++, as a GCC extension.
4015QualType ASTContext::getSignedWCharType() const {
4016 // FIXME: derive from "Target" ?
4017 return WCharTy;
4018}
4019
4020/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4021/// Used when in C++, as a GCC extension.
4022QualType ASTContext::getUnsignedWCharType() const {
4023 // FIXME: derive from "Target" ?
4024 return UnsignedIntTy;
4025}
4026
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004027QualType ASTContext::getIntPtrType() const {
4028 return getFromTargetType(Target->getIntPtrType());
4029}
4030
4031QualType ASTContext::getUIntPtrType() const {
4032 return getCorrespondingUnsignedType(getIntPtrType());
4033}
4034
Hans Wennborg27541db2011-10-27 08:29:09 +00004035/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004036/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4037QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004038 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004039}
4040
Eli Friedman4e91899e2012-11-27 02:58:24 +00004041/// \brief Return the unique type for "pid_t" defined in
4042/// <sys/types.h>. We need this to compute the correct type for vfork().
4043QualType ASTContext::getProcessIDType() const {
4044 return getFromTargetType(Target->getProcessIDType());
4045}
4046
Chris Lattnera21ad802008-04-02 05:18:44 +00004047//===----------------------------------------------------------------------===//
4048// Type Operators
4049//===----------------------------------------------------------------------===//
4050
Jay Foad39c79802011-01-12 09:06:06 +00004051CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004052 // Push qualifiers into arrays, and then discard any remaining
4053 // qualifiers.
4054 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004055 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004056 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004057 QualType Result;
4058 if (isa<ArrayType>(Ty)) {
4059 Result = getArrayDecayedType(QualType(Ty,0));
4060 } else if (isa<FunctionType>(Ty)) {
4061 Result = getPointerType(QualType(Ty, 0));
4062 } else {
4063 Result = QualType(Ty, 0);
4064 }
4065
4066 return CanQualType::CreateUnsafe(Result);
4067}
4068
John McCall6c9dd522011-01-18 07:41:22 +00004069QualType ASTContext::getUnqualifiedArrayType(QualType type,
4070 Qualifiers &quals) {
4071 SplitQualType splitType = type.getSplitUnqualifiedType();
4072
4073 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4074 // the unqualified desugared type and then drops it on the floor.
4075 // We then have to strip that sugar back off with
4076 // getUnqualifiedDesugaredType(), which is silly.
4077 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004078 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004079
4080 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004081 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004082 quals = splitType.Quals;
4083 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004084 }
4085
John McCall6c9dd522011-01-18 07:41:22 +00004086 // Otherwise, recurse on the array's element type.
4087 QualType elementType = AT->getElementType();
4088 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4089
4090 // If that didn't change the element type, AT has no qualifiers, so we
4091 // can just use the results in splitType.
4092 if (elementType == unqualElementType) {
4093 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004094 quals = splitType.Quals;
4095 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004096 }
4097
4098 // Otherwise, add in the qualifiers from the outermost type, then
4099 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004100 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004101
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004102 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004103 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004104 CAT->getSizeModifier(), 0);
4105 }
4106
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004107 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004108 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004109 }
4110
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004111 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004112 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004113 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004114 VAT->getSizeModifier(),
4115 VAT->getIndexTypeCVRQualifiers(),
4116 VAT->getBracketsRange());
4117 }
4118
4119 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004120 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004121 DSAT->getSizeModifier(), 0,
4122 SourceRange());
4123}
4124
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004125/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4126/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4127/// they point to and return true. If T1 and T2 aren't pointer types
4128/// or pointer-to-member types, or if they are not similar at this
4129/// level, returns false and leaves T1 and T2 unchanged. Top-level
4130/// qualifiers on T1 and T2 are ignored. This function will typically
4131/// be called in a loop that successively "unwraps" pointer and
4132/// pointer-to-member types to compare them at each level.
4133bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4134 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4135 *T2PtrType = T2->getAs<PointerType>();
4136 if (T1PtrType && T2PtrType) {
4137 T1 = T1PtrType->getPointeeType();
4138 T2 = T2PtrType->getPointeeType();
4139 return true;
4140 }
4141
4142 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4143 *T2MPType = T2->getAs<MemberPointerType>();
4144 if (T1MPType && T2MPType &&
4145 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4146 QualType(T2MPType->getClass(), 0))) {
4147 T1 = T1MPType->getPointeeType();
4148 T2 = T2MPType->getPointeeType();
4149 return true;
4150 }
4151
David Blaikiebbafb8a2012-03-11 07:00:24 +00004152 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004153 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4154 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4155 if (T1OPType && T2OPType) {
4156 T1 = T1OPType->getPointeeType();
4157 T2 = T2OPType->getPointeeType();
4158 return true;
4159 }
4160 }
4161
4162 // FIXME: Block pointers, too?
4163
4164 return false;
4165}
4166
Jay Foad39c79802011-01-12 09:06:06 +00004167DeclarationNameInfo
4168ASTContext::getNameForTemplate(TemplateName Name,
4169 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004170 switch (Name.getKind()) {
4171 case TemplateName::QualifiedTemplate:
4172 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004173 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004174 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4175 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004176
John McCalld9dfe3a2011-06-30 08:33:18 +00004177 case TemplateName::OverloadedTemplate: {
4178 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4179 // DNInfo work in progress: CHECKME: what about DNLoc?
4180 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4181 }
4182
4183 case TemplateName::DependentTemplate: {
4184 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004185 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004186 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004187 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4188 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004189 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004190 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4191 // DNInfo work in progress: FIXME: source locations?
4192 DeclarationNameLoc DNLoc;
4193 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4194 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4195 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004196 }
4197 }
4198
John McCalld9dfe3a2011-06-30 08:33:18 +00004199 case TemplateName::SubstTemplateTemplateParm: {
4200 SubstTemplateTemplateParmStorage *subst
4201 = Name.getAsSubstTemplateTemplateParm();
4202 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4203 NameLoc);
4204 }
4205
4206 case TemplateName::SubstTemplateTemplateParmPack: {
4207 SubstTemplateTemplateParmPackStorage *subst
4208 = Name.getAsSubstTemplateTemplateParmPack();
4209 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4210 NameLoc);
4211 }
4212 }
4213
4214 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004215}
4216
Jay Foad39c79802011-01-12 09:06:06 +00004217TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004218 switch (Name.getKind()) {
4219 case TemplateName::QualifiedTemplate:
4220 case TemplateName::Template: {
4221 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004222 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004223 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004224 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4225
4226 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004227 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004228 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004229
John McCalld9dfe3a2011-06-30 08:33:18 +00004230 case TemplateName::OverloadedTemplate:
4231 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004232
John McCalld9dfe3a2011-06-30 08:33:18 +00004233 case TemplateName::DependentTemplate: {
4234 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4235 assert(DTN && "Non-dependent template names must refer to template decls.");
4236 return DTN->CanonicalTemplateName;
4237 }
4238
4239 case TemplateName::SubstTemplateTemplateParm: {
4240 SubstTemplateTemplateParmStorage *subst
4241 = Name.getAsSubstTemplateTemplateParm();
4242 return getCanonicalTemplateName(subst->getReplacement());
4243 }
4244
4245 case TemplateName::SubstTemplateTemplateParmPack: {
4246 SubstTemplateTemplateParmPackStorage *subst
4247 = Name.getAsSubstTemplateTemplateParmPack();
4248 TemplateTemplateParmDecl *canonParameter
4249 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4250 TemplateArgument canonArgPack
4251 = getCanonicalTemplateArgument(subst->getArgumentPack());
4252 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4253 }
4254 }
4255
4256 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004257}
4258
Douglas Gregoradee3e32009-11-11 23:06:43 +00004259bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4260 X = getCanonicalTemplateName(X);
4261 Y = getCanonicalTemplateName(Y);
4262 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4263}
4264
Mike Stump11289f42009-09-09 15:08:12 +00004265TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004266ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004267 switch (Arg.getKind()) {
4268 case TemplateArgument::Null:
4269 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004270
Douglas Gregora8e02e72009-07-28 23:00:59 +00004271 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004272 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004273
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004274 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004275 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004276 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004277 }
Mike Stump11289f42009-09-09 15:08:12 +00004278
Eli Friedmanb826a002012-09-26 02:36:12 +00004279 case TemplateArgument::NullPtr:
4280 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4281 /*isNullPtr*/true);
4282
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004283 case TemplateArgument::Template:
4284 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004285
4286 case TemplateArgument::TemplateExpansion:
4287 return TemplateArgument(getCanonicalTemplateName(
4288 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004289 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004290
Douglas Gregora8e02e72009-07-28 23:00:59 +00004291 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004292 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004293
Douglas Gregora8e02e72009-07-28 23:00:59 +00004294 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004295 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004296
Douglas Gregora8e02e72009-07-28 23:00:59 +00004297 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004298 if (Arg.pack_size() == 0)
4299 return Arg;
4300
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004301 TemplateArgument *CanonArgs
4302 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004303 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004304 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004305 AEnd = Arg.pack_end();
4306 A != AEnd; (void)++A, ++Idx)
4307 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004308
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004309 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004310 }
4311 }
4312
4313 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004314 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004315}
4316
Douglas Gregor333489b2009-03-27 23:10:48 +00004317NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004318ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004319 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004320 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004321
4322 switch (NNS->getKind()) {
4323 case NestedNameSpecifier::Identifier:
4324 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004325 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004326 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4327 NNS->getAsIdentifier());
4328
4329 case NestedNameSpecifier::Namespace:
4330 // A namespace is canonical; build a nested-name-specifier with
4331 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004332 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004333 NNS->getAsNamespace()->getOriginalNamespace());
4334
4335 case NestedNameSpecifier::NamespaceAlias:
4336 // A namespace is canonical; build a nested-name-specifier with
4337 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004338 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004339 NNS->getAsNamespaceAlias()->getNamespace()
4340 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004341
4342 case NestedNameSpecifier::TypeSpec:
4343 case NestedNameSpecifier::TypeSpecWithTemplate: {
4344 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004345
4346 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4347 // break it apart into its prefix and identifier, then reconsititute those
4348 // as the canonical nested-name-specifier. This is required to canonicalize
4349 // a dependent nested-name-specifier involving typedefs of dependent-name
4350 // types, e.g.,
4351 // typedef typename T::type T1;
4352 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004353 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4354 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004355 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004356
Eli Friedman5358a0a2012-03-03 04:09:56 +00004357 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4358 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4359 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004360 return NestedNameSpecifier::Create(*this, nullptr, false,
4361 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004362 }
4363
4364 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004365 case NestedNameSpecifier::Super:
4366 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004367 return NNS;
4368 }
4369
David Blaikie8a40f702012-01-17 06:56:22 +00004370 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004371}
4372
Chris Lattner7adf0762008-08-04 07:31:14 +00004373
Jay Foad39c79802011-01-12 09:06:06 +00004374const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004375 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004376 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004377 // Handle the common positive case fast.
4378 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4379 return AT;
4380 }
Mike Stump11289f42009-09-09 15:08:12 +00004381
John McCall8ccfcb52009-09-24 19:53:00 +00004382 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004383 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004384 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004385
John McCall8ccfcb52009-09-24 19:53:00 +00004386 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004387 // implements C99 6.7.3p8: "If the specification of an array type includes
4388 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004389
Chris Lattner7adf0762008-08-04 07:31:14 +00004390 // If we get here, we either have type qualifiers on the type, or we have
4391 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004392 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004393
John McCall33ddac02011-01-19 10:06:00 +00004394 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004395 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004396
Chris Lattner7adf0762008-08-04 07:31:14 +00004397 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004398 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004399 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004400 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004401
Chris Lattner7adf0762008-08-04 07:31:14 +00004402 // Otherwise, we have an array and we have qualifiers on it. Push the
4403 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004404 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004405
Chris Lattner7adf0762008-08-04 07:31:14 +00004406 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4407 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4408 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004409 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004410 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4411 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4412 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004413 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004414
Mike Stump11289f42009-09-09 15:08:12 +00004415 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004416 = dyn_cast<DependentSizedArrayType>(ATy))
4417 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004418 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004419 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004420 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004421 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004422 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004423
Chris Lattner7adf0762008-08-04 07:31:14 +00004424 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004425 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004426 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004427 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004428 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004429 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004430}
4431
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004432QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004433 if (T->isArrayType() || T->isFunctionType())
4434 return getDecayedType(T);
4435 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004436}
4437
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004438QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004439 T = getVariableArrayDecayedType(T);
4440 T = getAdjustedParameterType(T);
4441 return T.getUnqualifiedType();
4442}
4443
David Majnemerd09a51c2015-03-03 01:50:05 +00004444QualType ASTContext::getExceptionObjectType(QualType T) const {
4445 // C++ [except.throw]p3:
4446 // A throw-expression initializes a temporary object, called the exception
4447 // object, the type of which is determined by removing any top-level
4448 // cv-qualifiers from the static type of the operand of throw and adjusting
4449 // the type from "array of T" or "function returning T" to "pointer to T"
4450 // or "pointer to function returning T", [...]
4451 T = getVariableArrayDecayedType(T);
4452 if (T->isArrayType() || T->isFunctionType())
4453 T = getDecayedType(T);
4454 return T.getUnqualifiedType();
4455}
4456
Chris Lattnera21ad802008-04-02 05:18:44 +00004457/// getArrayDecayedType - Return the properly qualified result of decaying the
4458/// specified array type to a pointer. This operation is non-trivial when
4459/// handling typedefs etc. The canonical type of "T" must be an array type,
4460/// this returns a pointer to a properly qualified element of the array.
4461///
4462/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004463QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004464 // Get the element type with 'getAsArrayType' so that we don't lose any
4465 // typedefs in the element type of the array. This also handles propagation
4466 // of type qualifiers from the array type into the element type if present
4467 // (C99 6.7.3p8).
4468 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4469 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004470
Chris Lattner7adf0762008-08-04 07:31:14 +00004471 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004472
4473 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004474 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004475}
4476
John McCall33ddac02011-01-19 10:06:00 +00004477QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4478 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004479}
4480
John McCall33ddac02011-01-19 10:06:00 +00004481QualType ASTContext::getBaseElementType(QualType type) const {
4482 Qualifiers qs;
4483 while (true) {
4484 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004485 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004486 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004487
John McCall33ddac02011-01-19 10:06:00 +00004488 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004489 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004490 }
Mike Stump11289f42009-09-09 15:08:12 +00004491
John McCall33ddac02011-01-19 10:06:00 +00004492 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004493}
4494
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004495/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004496uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004497ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4498 uint64_t ElementCount = 1;
4499 do {
4500 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004501 CA = dyn_cast_or_null<ConstantArrayType>(
4502 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004503 } while (CA);
4504 return ElementCount;
4505}
4506
Steve Naroff0af91202007-04-27 21:51:21 +00004507/// getFloatingRank - Return a relative rank for floating point types.
4508/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004509static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004510 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004511 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004512
John McCall9dd450b2009-09-21 23:43:11 +00004513 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4514 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004515 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004516 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004517 case BuiltinType::Float: return FloatRank;
4518 case BuiltinType::Double: return DoubleRank;
4519 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004520 }
4521}
4522
Mike Stump11289f42009-09-09 15:08:12 +00004523/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4524/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004525/// 'typeDomain' is a real floating point or complex type.
4526/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004527QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4528 QualType Domain) const {
4529 FloatingRank EltRank = getFloatingRank(Size);
4530 if (Domain->isComplexType()) {
4531 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004532 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004533 case FloatRank: return FloatComplexTy;
4534 case DoubleRank: return DoubleComplexTy;
4535 case LongDoubleRank: return LongDoubleComplexTy;
4536 }
Steve Naroff0af91202007-04-27 21:51:21 +00004537 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004538
4539 assert(Domain->isRealFloatingType() && "Unknown domain!");
4540 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004541 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004542 case FloatRank: return FloatTy;
4543 case DoubleRank: return DoubleTy;
4544 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004545 }
David Blaikief47fa302012-01-17 02:30:50 +00004546 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004547}
4548
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004549/// getFloatingTypeOrder - Compare the rank of the two specified floating
4550/// point types, ignoring the domain of the type (i.e. 'double' ==
4551/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004552/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004553int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004554 FloatingRank LHSR = getFloatingRank(LHS);
4555 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004556
Chris Lattnerb90739d2008-04-06 23:38:49 +00004557 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004558 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004559 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004560 return 1;
4561 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004562}
4563
Chris Lattner76a00cf2008-04-06 22:59:24 +00004564/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4565/// routine will assert if passed a built-in type that isn't an integer or enum,
4566/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004567unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004568 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004569
Chris Lattner76a00cf2008-04-06 22:59:24 +00004570 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004571 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004572 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004573 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004574 case BuiltinType::Char_S:
4575 case BuiltinType::Char_U:
4576 case BuiltinType::SChar:
4577 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004578 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004579 case BuiltinType::Short:
4580 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004581 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004582 case BuiltinType::Int:
4583 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004584 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004585 case BuiltinType::Long:
4586 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004587 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004588 case BuiltinType::LongLong:
4589 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004590 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004591 case BuiltinType::Int128:
4592 case BuiltinType::UInt128:
4593 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004594 }
4595}
4596
Eli Friedman629ffb92009-08-20 04:21:42 +00004597/// \brief Whether this is a promotable bitfield reference according
4598/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4599///
4600/// \returns the type this bit-field will promote to, or NULL if no
4601/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004602QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004603 if (E->isTypeDependent() || E->isValueDependent())
4604 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004605
4606 // FIXME: We should not do this unless E->refersToBitField() is true. This
4607 // matters in C where getSourceBitField() will find bit-fields for various
4608 // cases where the source expression is not a bit-field designator.
4609
John McCalld25db7e2013-05-06 21:39:12 +00004610 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004611 if (!Field)
4612 return QualType();
4613
4614 QualType FT = Field->getType();
4615
Richard Smithcaf33902011-10-10 18:28:20 +00004616 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004617 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004618 // C++ [conv.prom]p5:
4619 // A prvalue for an integral bit-field can be converted to a prvalue of type
4620 // int if int can represent all the values of the bit-field; otherwise, it
4621 // can be converted to unsigned int if unsigned int can represent all the
4622 // values of the bit-field. If the bit-field is larger yet, no integral
4623 // promotion applies to it.
4624 // C11 6.3.1.1/2:
4625 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4626 // If an int can represent all values of the original type (as restricted by
4627 // the width, for a bit-field), the value is converted to an int; otherwise,
4628 // it is converted to an unsigned int.
4629 //
4630 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4631 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004632 if (BitWidth < IntSize)
4633 return IntTy;
4634
4635 if (BitWidth == IntSize)
4636 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4637
4638 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004639 // like the base type. GCC has some weird bugs in this area that we
4640 // deliberately do not follow (GCC follows a pre-standard resolution to
4641 // C's DR315 which treats bit-width as being part of the type, and this leaks
4642 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004643 return QualType();
4644}
4645
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004646/// getPromotedIntegerType - Returns the type that Promotable will
4647/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4648/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004649QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004650 assert(!Promotable.isNull());
4651 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004652 if (const EnumType *ET = Promotable->getAs<EnumType>())
4653 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004654
4655 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4656 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4657 // (3.9.1) can be converted to a prvalue of the first of the following
4658 // types that can represent all the values of its underlying type:
4659 // int, unsigned int, long int, unsigned long int, long long int, or
4660 // unsigned long long int [...]
4661 // FIXME: Is there some better way to compute this?
4662 if (BT->getKind() == BuiltinType::WChar_S ||
4663 BT->getKind() == BuiltinType::WChar_U ||
4664 BT->getKind() == BuiltinType::Char16 ||
4665 BT->getKind() == BuiltinType::Char32) {
4666 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4667 uint64_t FromSize = getTypeSize(BT);
4668 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4669 LongLongTy, UnsignedLongLongTy };
4670 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4671 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4672 if (FromSize < ToSize ||
4673 (FromSize == ToSize &&
4674 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4675 return PromoteTypes[Idx];
4676 }
4677 llvm_unreachable("char type should fit into long long");
4678 }
4679 }
4680
4681 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004682 if (Promotable->isSignedIntegerType())
4683 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004684 uint64_t PromotableSize = getIntWidth(Promotable);
4685 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004686 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4687 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4688}
4689
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004690/// \brief Recurses in pointer/array types until it finds an objc retainable
4691/// type and returns its ownership.
4692Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4693 while (!T.isNull()) {
4694 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4695 return T.getObjCLifetime();
4696 if (T->isArrayType())
4697 T = getBaseElementType(T);
4698 else if (const PointerType *PT = T->getAs<PointerType>())
4699 T = PT->getPointeeType();
4700 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004701 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004702 else
4703 break;
4704 }
4705
4706 return Qualifiers::OCL_None;
4707}
4708
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004709static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4710 // Incomplete enum types are not treated as integer types.
4711 // FIXME: In C++, enum types are never integer types.
4712 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4713 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004714 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004715}
4716
Mike Stump11289f42009-09-09 15:08:12 +00004717/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004718/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004719/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004720int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004721 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4722 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004723
4724 // Unwrap enums to their underlying type.
4725 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4726 LHSC = getIntegerTypeForEnum(ET);
4727 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4728 RHSC = getIntegerTypeForEnum(ET);
4729
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004730 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004731
Chris Lattner76a00cf2008-04-06 22:59:24 +00004732 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4733 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004734
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004735 unsigned LHSRank = getIntegerRank(LHSC);
4736 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004737
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004738 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4739 if (LHSRank == RHSRank) return 0;
4740 return LHSRank > RHSRank ? 1 : -1;
4741 }
Mike Stump11289f42009-09-09 15:08:12 +00004742
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004743 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4744 if (LHSUnsigned) {
4745 // If the unsigned [LHS] type is larger, return it.
4746 if (LHSRank >= RHSRank)
4747 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004748
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004749 // If the signed type can represent all values of the unsigned type, it
4750 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004751 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004752 return -1;
4753 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004754
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004755 // If the unsigned [RHS] type is larger, return it.
4756 if (RHSRank >= LHSRank)
4757 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004758
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004759 // If the signed type can represent all values of the unsigned type, it
4760 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004761 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004762 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004763}
Anders Carlsson98f07902007-08-17 05:31:46 +00004764
Mike Stump11289f42009-09-09 15:08:12 +00004765// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004766QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004767 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004768 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004769 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004770
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004771 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004772
Anders Carlsson98f07902007-08-17 05:31:46 +00004773 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004774 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004775 // int flags;
4776 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004777 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004778 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004779 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004780 FieldTypes[3] = LongTy;
4781
Anders Carlsson98f07902007-08-17 05:31:46 +00004782 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004783 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004784 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004785 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004786 SourceLocation(), nullptr,
4787 FieldTypes[i], /*TInfo=*/nullptr,
4788 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004789 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004790 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004791 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004792 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004793 }
4794
Douglas Gregord5058122010-02-11 01:19:42 +00004795 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004796 }
Mike Stump11289f42009-09-09 15:08:12 +00004797
Anders Carlsson98f07902007-08-17 05:31:46 +00004798 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004799}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004800
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004801QualType ASTContext::getObjCSuperType() const {
4802 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004803 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004804 TUDecl->addDecl(ObjCSuperTypeDecl);
4805 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4806 }
4807 return ObjCSuperType;
4808}
4809
Douglas Gregor512b0772009-04-23 22:29:11 +00004810void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004811 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004812 assert(Rec && "Invalid CFConstantStringType");
4813 CFConstantStringTypeDecl = Rec->getDecl();
4814}
4815
Jay Foad39c79802011-01-12 09:06:06 +00004816QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004817 if (BlockDescriptorType)
4818 return getTagDeclType(BlockDescriptorType);
4819
Alp Toker2dea15b2013-12-17 01:22:38 +00004820 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004821 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004822 RD = buildImplicitRecord("__block_descriptor");
4823 RD->startDefinition();
4824
Mike Stumpd0153282009-10-20 02:12:22 +00004825 QualType FieldTypes[] = {
4826 UnsignedLongTy,
4827 UnsignedLongTy,
4828 };
4829
Craig Topperd6d31ac2013-07-15 08:24:27 +00004830 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004831 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004832 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004833 };
4834
4835 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004836 FieldDecl *Field = FieldDecl::Create(
4837 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004838 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4839 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004840 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004841 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004842 }
4843
Alp Toker2dea15b2013-12-17 01:22:38 +00004844 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004845
Alp Toker2dea15b2013-12-17 01:22:38 +00004846 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004847
4848 return getTagDeclType(BlockDescriptorType);
4849}
4850
Jay Foad39c79802011-01-12 09:06:06 +00004851QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004852 if (BlockDescriptorExtendedType)
4853 return getTagDeclType(BlockDescriptorExtendedType);
4854
Alp Toker2dea15b2013-12-17 01:22:38 +00004855 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004856 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004857 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4858 RD->startDefinition();
4859
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004860 QualType FieldTypes[] = {
4861 UnsignedLongTy,
4862 UnsignedLongTy,
4863 getPointerType(VoidPtrTy),
4864 getPointerType(VoidPtrTy)
4865 };
4866
Craig Topperd6d31ac2013-07-15 08:24:27 +00004867 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004868 "reserved",
4869 "Size",
4870 "CopyFuncPtr",
4871 "DestroyFuncPtr"
4872 };
4873
4874 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004875 FieldDecl *Field = FieldDecl::Create(
4876 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004877 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4878 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004879 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004880 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004881 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004882 }
4883
Alp Toker2dea15b2013-12-17 01:22:38 +00004884 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004885
Alp Toker2dea15b2013-12-17 01:22:38 +00004886 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004887 return getTagDeclType(BlockDescriptorExtendedType);
4888}
4889
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004890/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4891/// requires copy/dispose. Note that this must match the logic
4892/// in buildByrefHelpers.
4893bool ASTContext::BlockRequiresCopying(QualType Ty,
4894 const VarDecl *D) {
4895 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4896 const Expr *copyExpr = getBlockVarCopyInits(D);
4897 if (!copyExpr && record->hasTrivialDestructor()) return false;
4898
Mike Stump94967902009-10-21 18:16:27 +00004899 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004900 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004901
4902 if (!Ty->isObjCRetainableType()) return false;
4903
4904 Qualifiers qs = Ty.getQualifiers();
4905
4906 // If we have lifetime, that dominates.
4907 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4908 assert(getLangOpts().ObjCAutoRefCount);
4909
4910 switch (lifetime) {
4911 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4912
4913 // These are just bits as far as the runtime is concerned.
4914 case Qualifiers::OCL_ExplicitNone:
4915 case Qualifiers::OCL_Autoreleasing:
4916 return false;
4917
4918 // Tell the runtime that this is ARC __weak, called by the
4919 // byref routines.
4920 case Qualifiers::OCL_Weak:
4921 // ARC __strong __block variables need to be retained.
4922 case Qualifiers::OCL_Strong:
4923 return true;
4924 }
4925 llvm_unreachable("fell out of lifetime switch!");
4926 }
4927 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4928 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004929}
4930
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004931bool ASTContext::getByrefLifetime(QualType Ty,
4932 Qualifiers::ObjCLifetime &LifeTime,
4933 bool &HasByrefExtendedLayout) const {
4934
4935 if (!getLangOpts().ObjC1 ||
4936 getLangOpts().getGC() != LangOptions::NonGC)
4937 return false;
4938
4939 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004940 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004941 HasByrefExtendedLayout = true;
4942 LifeTime = Qualifiers::OCL_None;
4943 }
4944 else if (getLangOpts().ObjCAutoRefCount)
4945 LifeTime = Ty.getObjCLifetime();
4946 // MRR.
4947 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4948 LifeTime = Qualifiers::OCL_ExplicitNone;
4949 else
4950 LifeTime = Qualifiers::OCL_None;
4951 return true;
4952}
4953
Douglas Gregorbab8a962011-09-08 01:46:34 +00004954TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4955 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004956 ObjCInstanceTypeDecl =
4957 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004958 return ObjCInstanceTypeDecl;
4959}
4960
Anders Carlsson18acd442007-10-29 06:33:42 +00004961// This returns true if a type has been typedefed to BOOL:
4962// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004963static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004964 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004965 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4966 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004967
Anders Carlssond8499822007-10-29 05:01:08 +00004968 return false;
4969}
4970
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004971/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004972/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004973CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004974 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4975 return CharUnits::Zero();
4976
Ken Dyck40775002010-01-11 17:06:35 +00004977 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004978
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004979 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004980 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004981 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004982 // Treat arrays as pointers, since that's how they're passed in.
4983 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004984 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004985 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004986}
4987
Hans Wennborg56fc62b2014-07-17 20:25:23 +00004988bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4989 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4990 VD->getType()->isIntegralOrEnumerationType() &&
Alexey Bataev15413ea2015-05-20 11:57:02 +00004991 VD->isFirstDecl() && !VD->isOutOfLine() && VD->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00004992}
4993
Ken Dyck40775002010-01-11 17:06:35 +00004994static inline
4995std::string charUnitsToString(const CharUnits &CU) {
4996 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004997}
4998
John McCall351762c2011-02-07 10:33:21 +00004999/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005000/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005001std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5002 std::string S;
5003
David Chisnall950a9512009-11-17 19:33:30 +00005004 const BlockDecl *Decl = Expr->getBlockDecl();
5005 QualType BlockTy =
5006 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5007 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005008 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005009 getObjCEncodingForMethodParameter(
5010 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5011 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005012 else
Alp Toker314cc812014-01-25 16:55:45 +00005013 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005014 // Compute size of all parameters.
5015 // Start with computing size of a pointer in number of bytes.
5016 // FIXME: There might(should) be a better way of doing this computation!
5017 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005018 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5019 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005020 for (auto PI : Decl->params()) {
5021 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005022 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005023 if (sz.isZero())
5024 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005025 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005026 ParmOffset += sz;
5027 }
5028 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005029 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005030 // Block pointer and offset.
5031 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005032
5033 // Argument types.
5034 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005035 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00005036 QualType PType = PVDecl->getOriginalType();
5037 if (const ArrayType *AT =
5038 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5039 // Use array's original type only if it has known number of
5040 // elements.
5041 if (!isa<ConstantArrayType>(AT))
5042 PType = PVDecl->getType();
5043 } else if (PType->isFunctionType())
5044 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005045 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005046 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5047 S, true /*Extended*/);
5048 else
5049 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005050 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005051 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005052 }
John McCall351762c2011-02-07 10:33:21 +00005053
5054 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005055}
5056
Douglas Gregora9d84932011-05-27 01:19:52 +00005057bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005058 std::string& S) {
5059 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005060 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005061 CharUnits ParmOffset;
5062 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005063 for (auto PI : Decl->params()) {
5064 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005065 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005066 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005067 continue;
5068
David Chisnall50e4eba2010-12-30 14:05:53 +00005069 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005070 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005071 ParmOffset += sz;
5072 }
5073 S += charUnitsToString(ParmOffset);
5074 ParmOffset = CharUnits::Zero();
5075
5076 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005077 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005078 QualType PType = PVDecl->getOriginalType();
5079 if (const ArrayType *AT =
5080 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5081 // Use array's original type only if it has known number of
5082 // elements.
5083 if (!isa<ConstantArrayType>(AT))
5084 PType = PVDecl->getType();
5085 } else if (PType->isFunctionType())
5086 PType = PVDecl->getType();
5087 getObjCEncodingForType(PType, S);
5088 S += charUnitsToString(ParmOffset);
5089 ParmOffset += getObjCEncodingTypeSize(PType);
5090 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005091
5092 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005093}
5094
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005095/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5096/// method parameter or return type. If Extended, include class names and
5097/// block object types.
5098void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5099 QualType T, std::string& S,
5100 bool Extended) const {
5101 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5102 getObjCEncodingForTypeQualifier(QT, S);
5103 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005104 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005105 true /*OutermostType*/,
5106 false /*EncodingProperty*/,
5107 false /*StructField*/,
5108 Extended /*EncodeBlockParameters*/,
5109 Extended /*EncodeClassNames*/);
5110}
5111
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005112/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005113/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005114bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005115 std::string& S,
5116 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005117 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005118 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005119 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5120 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005121 // Compute size of all parameters.
5122 // Start with computing size of a pointer in number of bytes.
5123 // FIXME: There might(should) be a better way of doing this computation!
5124 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005125 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005126 // The first two arguments (self and _cmd) are pointers; account for
5127 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005128 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005129 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005130 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005131 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005132 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005133 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005134 continue;
5135
Ken Dyck40775002010-01-11 17:06:35 +00005136 assert (sz.isPositive() &&
5137 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005138 ParmOffset += sz;
5139 }
Ken Dyck40775002010-01-11 17:06:35 +00005140 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005141 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005142 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005143
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005144 // Argument types.
5145 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005146 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005147 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005148 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005149 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005150 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005151 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5152 // Use array's original type only if it has known number of
5153 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005154 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005155 PType = PVDecl->getType();
5156 } else if (PType->isFunctionType())
5157 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005158 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5159 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005160 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005161 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005162 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005163
5164 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005165}
5166
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005167ObjCPropertyImplDecl *
5168ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5169 const ObjCPropertyDecl *PD,
5170 const Decl *Container) const {
5171 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005172 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005173 if (const ObjCCategoryImplDecl *CID =
5174 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005175 for (auto *PID : CID->property_impls())
5176 if (PID->getPropertyDecl() == PD)
5177 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005178 } else {
5179 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5180 for (auto *PID : OID->property_impls())
5181 if (PID->getPropertyDecl() == PD)
5182 return PID;
5183 }
5184 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005185}
5186
Daniel Dunbar4932b362008-08-28 04:38:10 +00005187/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005188/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005189/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5190/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005191/// Property attributes are stored as a comma-delimited C string. The simple
5192/// attributes readonly and bycopy are encoded as single characters. The
5193/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5194/// encoded as single characters, followed by an identifier. Property types
5195/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005196/// these attributes are defined by the following enumeration:
5197/// @code
5198/// enum PropertyAttributes {
5199/// kPropertyReadOnly = 'R', // property is read-only.
5200/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5201/// kPropertyByref = '&', // property is a reference to the value last assigned
5202/// kPropertyDynamic = 'D', // property is dynamic
5203/// kPropertyGetter = 'G', // followed by getter selector name
5204/// kPropertySetter = 'S', // followed by setter selector name
5205/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005206/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005207/// kPropertyWeak = 'W' // 'weak' property
5208/// kPropertyStrong = 'P' // property GC'able
5209/// kPropertyNonAtomic = 'N' // property non-atomic
5210/// };
5211/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005212void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005213 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005214 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005215 // Collect information from the property implementation decl(s).
5216 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005217 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005218
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005219 if (ObjCPropertyImplDecl *PropertyImpDecl =
5220 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5221 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5222 Dynamic = true;
5223 else
5224 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005225 }
5226
5227 // FIXME: This is not very efficient.
5228 S = "T";
5229
5230 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005231 // GCC has some special rules regarding encoding of properties which
5232 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005233 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005234
5235 if (PD->isReadOnly()) {
5236 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005237 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5238 S += ",C";
5239 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5240 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005241 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5242 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005243 } else {
5244 switch (PD->getSetterKind()) {
5245 case ObjCPropertyDecl::Assign: break;
5246 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005247 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005248 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005249 }
5250 }
5251
5252 // It really isn't clear at all what this means, since properties
5253 // are "dynamic by default".
5254 if (Dynamic)
5255 S += ",D";
5256
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005257 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5258 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005259
Daniel Dunbar4932b362008-08-28 04:38:10 +00005260 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5261 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005262 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005263 }
5264
5265 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5266 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005267 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005268 }
5269
5270 if (SynthesizePID) {
5271 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5272 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005273 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005274 }
5275
5276 // FIXME: OBJCGC: weak & strong
5277}
5278
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005279/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005280/// Another legacy compatibility encoding: 32-bit longs are encoded as
5281/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005282/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5283///
5284void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005285 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005286 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005287 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005288 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005289 else
Jay Foad39c79802011-01-12 09:06:06 +00005290 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005291 PointeeTy = IntTy;
5292 }
5293 }
5294}
5295
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005296void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005297 const FieldDecl *Field,
5298 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005299 // We follow the behavior of gcc, expanding structures which are
5300 // directly pointed to, and expanding embedded structures. Note that
5301 // these rules are sufficient to prevent recursive encoding of the
5302 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005303 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005304 true /* outermost type */, false, false,
5305 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005306}
5307
Joe Groff98ac7d22014-07-07 22:25:15 +00005308void ASTContext::getObjCEncodingForPropertyType(QualType T,
5309 std::string& S) const {
5310 // Encode result type.
5311 // GCC has some special rules regarding encoding of properties which
5312 // closely resembles encoding of ivars.
5313 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5314 true /* outermost type */,
5315 true /* encoding property */);
5316}
5317
John McCall393a78d2012-12-20 02:45:14 +00005318static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5319 BuiltinType::Kind kind) {
5320 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005321 case BuiltinType::Void: return 'v';
5322 case BuiltinType::Bool: return 'B';
5323 case BuiltinType::Char_U:
5324 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005325 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005326 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005327 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005328 case BuiltinType::UInt: return 'I';
5329 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005330 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005331 case BuiltinType::UInt128: return 'T';
5332 case BuiltinType::ULongLong: return 'Q';
5333 case BuiltinType::Char_S:
5334 case BuiltinType::SChar: return 'c';
5335 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005336 case BuiltinType::WChar_S:
5337 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005338 case BuiltinType::Int: return 'i';
5339 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005340 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005341 case BuiltinType::LongLong: return 'q';
5342 case BuiltinType::Int128: return 't';
5343 case BuiltinType::Float: return 'f';
5344 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005345 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005346 case BuiltinType::NullPtr: return '*'; // like char*
5347
5348 case BuiltinType::Half:
5349 // FIXME: potentially need @encodes for these!
5350 return ' ';
5351
5352 case BuiltinType::ObjCId:
5353 case BuiltinType::ObjCClass:
5354 case BuiltinType::ObjCSel:
5355 llvm_unreachable("@encoding ObjC primitive type");
5356
5357 // OpenCL and placeholder types don't need @encodings.
5358 case BuiltinType::OCLImage1d:
5359 case BuiltinType::OCLImage1dArray:
5360 case BuiltinType::OCLImage1dBuffer:
5361 case BuiltinType::OCLImage2d:
5362 case BuiltinType::OCLImage2dArray:
5363 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005364 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005365 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005366 case BuiltinType::Dependent:
5367#define BUILTIN_TYPE(KIND, ID)
5368#define PLACEHOLDER_TYPE(KIND, ID) \
5369 case BuiltinType::KIND:
5370#include "clang/AST/BuiltinTypes.def"
5371 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005372 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005373 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005374}
5375
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005376static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5377 EnumDecl *Enum = ET->getDecl();
5378
5379 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5380 if (!Enum->isFixed())
5381 return 'i';
5382
5383 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005384 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5385 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005386}
5387
Jay Foad39c79802011-01-12 09:06:06 +00005388static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005389 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005390 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005391 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005392 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5393 // The GNU runtime requires more information; bitfields are encoded as b,
5394 // then the offset (in bits) of the first element, then the type of the
5395 // bitfield, then the size in bits. For example, in this structure:
5396 //
5397 // struct
5398 // {
5399 // int integer;
5400 // int flags:2;
5401 // };
5402 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5403 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5404 // information is not especially sensible, but we're stuck with it for
5405 // compatibility with GCC, although providing it breaks anything that
5406 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005407 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005408 const RecordDecl *RD = FD->getParent();
5409 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005410 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005411 if (const EnumType *ET = T->getAs<EnumType>())
5412 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005413 else {
5414 const BuiltinType *BT = T->castAs<BuiltinType>();
5415 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5416 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005417 }
Richard Smithcaf33902011-10-10 18:28:20 +00005418 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005419}
5420
Daniel Dunbar07d07852009-10-18 21:17:35 +00005421// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005422void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5423 bool ExpandPointedToStructures,
5424 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005425 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005426 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005427 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005428 bool StructField,
5429 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005430 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005431 bool EncodePointerToObjCTypedef,
5432 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005433 CanQualType CT = getCanonicalType(T);
5434 switch (CT->getTypeClass()) {
5435 case Type::Builtin:
5436 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005437 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005438 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005439 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5440 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5441 else
5442 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005443 return;
Mike Stump11289f42009-09-09 15:08:12 +00005444
John McCall393a78d2012-12-20 02:45:14 +00005445 case Type::Complex: {
5446 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005447 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005448 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005449 return;
5450 }
John McCall393a78d2012-12-20 02:45:14 +00005451
5452 case Type::Atomic: {
5453 const AtomicType *AT = T->castAs<AtomicType>();
5454 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005455 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005456 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005457 }
John McCall393a78d2012-12-20 02:45:14 +00005458
5459 // encoding for pointer or reference types.
5460 case Type::Pointer:
5461 case Type::LValueReference:
5462 case Type::RValueReference: {
5463 QualType PointeeTy;
5464 if (isa<PointerType>(CT)) {
5465 const PointerType *PT = T->castAs<PointerType>();
5466 if (PT->isObjCSelType()) {
5467 S += ':';
5468 return;
5469 }
5470 PointeeTy = PT->getPointeeType();
5471 } else {
5472 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5473 }
5474
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005475 bool isReadOnly = false;
5476 // For historical/compatibility reasons, the read-only qualifier of the
5477 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5478 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005479 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005480 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005481 if (OutermostType && T.isConstQualified()) {
5482 isReadOnly = true;
5483 S += 'r';
5484 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005485 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005486 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005487 while (P->getAs<PointerType>())
5488 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005489 if (P.isConstQualified()) {
5490 isReadOnly = true;
5491 S += 'r';
5492 }
5493 }
5494 if (isReadOnly) {
5495 // Another legacy compatibility encoding. Some ObjC qualifier and type
5496 // combinations need to be rearranged.
5497 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005498 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005499 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005500 }
Mike Stump11289f42009-09-09 15:08:12 +00005501
Anders Carlssond8499822007-10-29 05:01:08 +00005502 if (PointeeTy->isCharType()) {
5503 // char pointer types should be encoded as '*' unless it is a
5504 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005505 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005506 S += '*';
5507 return;
5508 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005509 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005510 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5511 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5512 S += '#';
5513 return;
5514 }
5515 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5516 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5517 S += '@';
5518 return;
5519 }
5520 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005521 }
Anders Carlssond8499822007-10-29 05:01:08 +00005522 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005523 getLegacyIntegralTypeEncoding(PointeeTy);
5524
Mike Stump11289f42009-09-09 15:08:12 +00005525 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005526 nullptr, false, false, false, false, false, false,
5527 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005528 return;
5529 }
John McCall393a78d2012-12-20 02:45:14 +00005530
5531 case Type::ConstantArray:
5532 case Type::IncompleteArray:
5533 case Type::VariableArray: {
5534 const ArrayType *AT = cast<ArrayType>(CT);
5535
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005536 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005537 // Incomplete arrays are encoded as a pointer to the array element.
5538 S += '^';
5539
Mike Stump11289f42009-09-09 15:08:12 +00005540 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005541 false, ExpandStructures, FD);
5542 } else {
5543 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005544
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005545 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5546 S += llvm::utostr(CAT->getSize().getZExtValue());
5547 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005548 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005549 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5550 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005551 S += '0';
5552 }
Mike Stump11289f42009-09-09 15:08:12 +00005553
5554 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005555 false, ExpandStructures, FD,
5556 false, false, false, false, false, false,
5557 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005558 S += ']';
5559 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005560 return;
5561 }
Mike Stump11289f42009-09-09 15:08:12 +00005562
John McCall393a78d2012-12-20 02:45:14 +00005563 case Type::FunctionNoProto:
5564 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005565 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005566 return;
Mike Stump11289f42009-09-09 15:08:12 +00005567
John McCall393a78d2012-12-20 02:45:14 +00005568 case Type::Record: {
5569 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005570 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005571 // Anonymous structures print as '?'
5572 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5573 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005574 if (ClassTemplateSpecializationDecl *Spec
5575 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5576 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005577 llvm::raw_string_ostream OS(S);
5578 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005579 TemplateArgs.data(),
5580 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005581 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005582 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005583 } else {
5584 S += '?';
5585 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005586 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005587 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005588 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005589 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005590 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005591 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005592 if (FD) {
5593 S += '"';
5594 S += Field->getNameAsString();
5595 S += '"';
5596 }
Mike Stump11289f42009-09-09 15:08:12 +00005597
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005598 // Special case bit-fields.
5599 if (Field->isBitField()) {
5600 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005601 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005602 } else {
5603 QualType qt = Field->getType();
5604 getLegacyIntegralTypeEncoding(qt);
5605 getObjCEncodingForTypeImpl(qt, S, false, true,
5606 FD, /*OutermostType*/false,
5607 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005608 /*StructField*/true,
5609 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005610 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005611 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005612 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005613 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005614 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005615 return;
5616 }
Mike Stump11289f42009-09-09 15:08:12 +00005617
John McCall393a78d2012-12-20 02:45:14 +00005618 case Type::BlockPointer: {
5619 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005620 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005621 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005622 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005623
5624 S += '<';
5625 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005626 getObjCEncodingForTypeImpl(
5627 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5628 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005629 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5630 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005631 // Block self
5632 S += "@?";
5633 // Block parameters
5634 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005635 for (const auto &I : FPT->param_types())
5636 getObjCEncodingForTypeImpl(
5637 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5638 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005639 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5640 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005641 }
5642 S += '>';
5643 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005644 return;
5645 }
Mike Stump11289f42009-09-09 15:08:12 +00005646
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005647 case Type::ObjCObject: {
5648 // hack to match legacy encoding of *id and *Class
5649 QualType Ty = getObjCObjectPointerType(CT);
5650 if (Ty->isObjCIdType()) {
5651 S += "{objc_object=}";
5652 return;
5653 }
5654 else if (Ty->isObjCClassType()) {
5655 S += "{objc_class=}";
5656 return;
5657 }
5658 }
5659
John McCall393a78d2012-12-20 02:45:14 +00005660 case Type::ObjCInterface: {
5661 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005662 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005663 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005664 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005665 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005666 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005667 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005668 DeepCollectObjCIvars(OI, true, Ivars);
5669 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005670 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005671 if (Field->isBitField())
5672 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005673 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005674 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5675 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005676 EncodePointerToObjCTypedef,
5677 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005678 }
5679 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005680 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005681 }
Mike Stump11289f42009-09-09 15:08:12 +00005682
John McCall393a78d2012-12-20 02:45:14 +00005683 case Type::ObjCObjectPointer: {
5684 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005685 if (OPT->isObjCIdType()) {
5686 S += '@';
5687 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005688 }
Mike Stump11289f42009-09-09 15:08:12 +00005689
Steve Narofff0c86112009-10-28 22:03:49 +00005690 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5691 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5692 // Since this is a binary compatibility issue, need to consult with runtime
5693 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005694 S += '#';
5695 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005696 }
Mike Stump11289f42009-09-09 15:08:12 +00005697
Chris Lattnere7cabb92009-07-13 00:10:46 +00005698 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005699 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005700 ExpandPointedToStructures,
5701 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005702 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005703 // Note that we do extended encoding of protocol qualifer list
5704 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005705 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005706 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005707 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005708 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005709 S += '>';
5710 }
5711 S += '"';
5712 }
5713 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005714 }
Mike Stump11289f42009-09-09 15:08:12 +00005715
Chris Lattnere7cabb92009-07-13 00:10:46 +00005716 QualType PointeeTy = OPT->getPointeeType();
5717 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005718 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5719 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005720 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005721 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005722 // {...};
5723 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005724 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005725 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005726 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5727 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5728 DeepCollectObjCIvars(OI, true, Ivars);
5729 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5730 if (cast<FieldDecl>(Ivars[i]) == FD) {
5731 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005732 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005733 S += '}';
5734 return;
5735 }
5736 }
5737 }
Mike Stump11289f42009-09-09 15:08:12 +00005738 getObjCEncodingForTypeImpl(PointeeTy, S,
5739 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005740 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005741 false, false, false, false, false,
5742 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005743 return;
5744 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005745
5746 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005747 if (OPT->getInterfaceDecl() &&
5748 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005749 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005750 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005751 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005752 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005753 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005754 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005755 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005756 S += '"';
5757 }
5758 return;
5759 }
Mike Stump11289f42009-09-09 15:08:12 +00005760
John McCalla9e6e8d2010-05-17 23:56:34 +00005761 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005762 // FIXME: we shoul do better than that. 'M' is available.
5763 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005764 // This matches gcc's encoding, even though technically it is insufficient.
5765 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005766 case Type::Vector:
5767 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005768 // Until we have a coherent encoding of these three types, issue warning.
5769 { if (NotEncodedT)
5770 *NotEncodedT = T;
5771 return;
5772 }
5773
5774 // We could see an undeduced auto type here during error recovery.
5775 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005776 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005777 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005778
Richard Smith27d807c2013-04-30 13:56:41 +00005779
John McCall393a78d2012-12-20 02:45:14 +00005780#define ABSTRACT_TYPE(KIND, BASE)
5781#define TYPE(KIND, BASE)
5782#define DEPENDENT_TYPE(KIND, BASE) \
5783 case Type::KIND:
5784#define NON_CANONICAL_TYPE(KIND, BASE) \
5785 case Type::KIND:
5786#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5787 case Type::KIND:
5788#include "clang/AST/TypeNodes.def"
5789 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005790 }
John McCall393a78d2012-12-20 02:45:14 +00005791 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005792}
5793
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005794void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5795 std::string &S,
5796 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005797 bool includeVBases,
5798 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005799 assert(RDecl && "Expected non-null RecordDecl");
5800 assert(!RDecl->isUnion() && "Should not be called for unions");
5801 if (!RDecl->getDefinition())
5802 return;
5803
5804 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5805 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5806 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5807
5808 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005809 for (const auto &BI : CXXRec->bases()) {
5810 if (!BI.isVirtual()) {
5811 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005812 if (base->isEmpty())
5813 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005814 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005815 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5816 std::make_pair(offs, base));
5817 }
5818 }
5819 }
5820
5821 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005822 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005823 uint64_t offs = layout.getFieldOffset(i);
5824 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005825 std::make_pair(offs, Field));
5826 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005827 }
5828
5829 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005830 for (const auto &BI : CXXRec->vbases()) {
5831 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005832 if (base->isEmpty())
5833 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005834 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005835 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5836 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005837 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5838 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005839 }
5840 }
5841
5842 CharUnits size;
5843 if (CXXRec) {
5844 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5845 } else {
5846 size = layout.getSize();
5847 }
5848
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005849#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005850 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005851#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005852 std::multimap<uint64_t, NamedDecl *>::iterator
5853 CurLayObj = FieldOrBaseOffsets.begin();
5854
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005855 if (CXXRec && CXXRec->isDynamicClass() &&
5856 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005857 if (FD) {
5858 S += "\"_vptr$";
5859 std::string recname = CXXRec->getNameAsString();
5860 if (recname.empty()) recname = "?";
5861 S += recname;
5862 S += '"';
5863 }
5864 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005865#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005866 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005867#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005868 }
5869
5870 if (!RDecl->hasFlexibleArrayMember()) {
5871 // Mark the end of the structure.
5872 uint64_t offs = toBits(size);
5873 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005874 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005875 }
5876
5877 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005878#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005879 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005880 if (CurOffs < CurLayObj->first) {
5881 uint64_t padding = CurLayObj->first - CurOffs;
5882 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5883 // packing/alignment of members is different that normal, in which case
5884 // the encoding will be out-of-sync with the real layout.
5885 // If the runtime switches to just consider the size of types without
5886 // taking into account alignment, we could make padding explicit in the
5887 // encoding (e.g. using arrays of chars). The encoding strings would be
5888 // longer then though.
5889 CurOffs += padding;
5890 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005891#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005892
5893 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005894 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005895 break; // reached end of structure.
5896
5897 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5898 // We expand the bases without their virtual bases since those are going
5899 // in the initial structure. Note that this differs from gcc which
5900 // expands virtual bases each time one is encountered in the hierarchy,
5901 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005902 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5903 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005904 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005905#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005906 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005907#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005908 } else {
5909 FieldDecl *field = cast<FieldDecl>(dcl);
5910 if (FD) {
5911 S += '"';
5912 S += field->getNameAsString();
5913 S += '"';
5914 }
5915
5916 if (field->isBitField()) {
5917 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005918#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005919 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005920#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005921 } else {
5922 QualType qt = field->getType();
5923 getLegacyIntegralTypeEncoding(qt);
5924 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5925 /*OutermostType*/false,
5926 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005927 /*StructField*/true,
5928 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005929#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005930 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005931#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005932 }
5933 }
5934 }
5935}
5936
Mike Stump11289f42009-09-09 15:08:12 +00005937void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005938 std::string& S) const {
5939 if (QT & Decl::OBJC_TQ_In)
5940 S += 'n';
5941 if (QT & Decl::OBJC_TQ_Inout)
5942 S += 'N';
5943 if (QT & Decl::OBJC_TQ_Out)
5944 S += 'o';
5945 if (QT & Decl::OBJC_TQ_Bycopy)
5946 S += 'O';
5947 if (QT & Decl::OBJC_TQ_Byref)
5948 S += 'R';
5949 if (QT & Decl::OBJC_TQ_Oneway)
5950 S += 'V';
5951}
5952
Douglas Gregor3ea72692011-08-12 05:46:01 +00005953TypedefDecl *ASTContext::getObjCIdDecl() const {
5954 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00005955 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00005956 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005957 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005958 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005959 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005960}
5961
Douglas Gregor52e02802011-08-12 06:17:30 +00005962TypedefDecl *ASTContext::getObjCSelDecl() const {
5963 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005964 QualType T = getPointerType(ObjCBuiltinSelTy);
5965 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005966 }
5967 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005968}
5969
Douglas Gregor0a586182011-08-12 05:59:41 +00005970TypedefDecl *ASTContext::getObjCClassDecl() const {
5971 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00005972 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00005973 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005974 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005975 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005976 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005977}
5978
Douglas Gregord53ae832012-01-17 18:09:05 +00005979ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5980 if (!ObjCProtocolClassDecl) {
5981 ObjCProtocolClassDecl
5982 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5983 SourceLocation(),
5984 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00005985 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00005986 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00005987 SourceLocation(), true);
5988 }
5989
5990 return ObjCProtocolClassDecl;
5991}
5992
Meador Inge5d3fb222012-06-16 03:34:49 +00005993//===----------------------------------------------------------------------===//
5994// __builtin_va_list Construction Functions
5995//===----------------------------------------------------------------------===//
5996
5997static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5998 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005999 QualType T = Context->getPointerType(Context->CharTy);
6000 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006001}
6002
6003static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6004 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006005 QualType T = Context->getPointerType(Context->VoidTy);
6006 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006007}
6008
Tim Northover9bb857a2013-01-31 12:13:10 +00006009static TypedefDecl *
6010CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006011 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006012 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006013 if (Context->getLangOpts().CPlusPlus) {
6014 // namespace std { struct __va_list {
6015 NamespaceDecl *NS;
6016 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6017 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006018 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006019 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006020 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006021 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006022 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006023 }
6024
6025 VaListTagDecl->startDefinition();
6026
6027 const size_t NumFields = 5;
6028 QualType FieldTypes[NumFields];
6029 const char *FieldNames[NumFields];
6030
6031 // void *__stack;
6032 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6033 FieldNames[0] = "__stack";
6034
6035 // void *__gr_top;
6036 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6037 FieldNames[1] = "__gr_top";
6038
6039 // void *__vr_top;
6040 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6041 FieldNames[2] = "__vr_top";
6042
6043 // int __gr_offs;
6044 FieldTypes[3] = Context->IntTy;
6045 FieldNames[3] = "__gr_offs";
6046
6047 // int __vr_offs;
6048 FieldTypes[4] = Context->IntTy;
6049 FieldNames[4] = "__vr_offs";
6050
6051 // Create fields
6052 for (unsigned i = 0; i < NumFields; ++i) {
6053 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6054 VaListTagDecl,
6055 SourceLocation(),
6056 SourceLocation(),
6057 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006058 FieldTypes[i], /*TInfo=*/nullptr,
6059 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006060 /*Mutable=*/false,
6061 ICIS_NoInit);
6062 Field->setAccess(AS_public);
6063 VaListTagDecl->addDecl(Field);
6064 }
6065 VaListTagDecl->completeDefinition();
6066 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6067 Context->VaListTagTy = VaListTagType;
6068
6069 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006070 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006071}
6072
Meador Inge5d3fb222012-06-16 03:34:49 +00006073static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6074 // typedef struct __va_list_tag {
6075 RecordDecl *VaListTagDecl;
6076
Alp Toker2dea15b2013-12-17 01:22:38 +00006077 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006078 VaListTagDecl->startDefinition();
6079
6080 const size_t NumFields = 5;
6081 QualType FieldTypes[NumFields];
6082 const char *FieldNames[NumFields];
6083
6084 // unsigned char gpr;
6085 FieldTypes[0] = Context->UnsignedCharTy;
6086 FieldNames[0] = "gpr";
6087
6088 // unsigned char fpr;
6089 FieldTypes[1] = Context->UnsignedCharTy;
6090 FieldNames[1] = "fpr";
6091
6092 // unsigned short reserved;
6093 FieldTypes[2] = Context->UnsignedShortTy;
6094 FieldNames[2] = "reserved";
6095
6096 // void* overflow_arg_area;
6097 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6098 FieldNames[3] = "overflow_arg_area";
6099
6100 // void* reg_save_area;
6101 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6102 FieldNames[4] = "reg_save_area";
6103
6104 // Create fields
6105 for (unsigned i = 0; i < NumFields; ++i) {
6106 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6107 SourceLocation(),
6108 SourceLocation(),
6109 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006110 FieldTypes[i], /*TInfo=*/nullptr,
6111 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006112 /*Mutable=*/false,
6113 ICIS_NoInit);
6114 Field->setAccess(AS_public);
6115 VaListTagDecl->addDecl(Field);
6116 }
6117 VaListTagDecl->completeDefinition();
6118 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006119 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006120
6121 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006122 TypedefDecl *VaListTagTypedefDecl =
6123 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6124
Meador Inge5d3fb222012-06-16 03:34:49 +00006125 QualType VaListTagTypedefType =
6126 Context->getTypedefType(VaListTagTypedefDecl);
6127
6128 // typedef __va_list_tag __builtin_va_list[1];
6129 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6130 QualType VaListTagArrayType
6131 = Context->getConstantArrayType(VaListTagTypedefType,
6132 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006133 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006134}
6135
6136static TypedefDecl *
6137CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6138 // typedef struct __va_list_tag {
6139 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006140 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006141 VaListTagDecl->startDefinition();
6142
6143 const size_t NumFields = 4;
6144 QualType FieldTypes[NumFields];
6145 const char *FieldNames[NumFields];
6146
6147 // unsigned gp_offset;
6148 FieldTypes[0] = Context->UnsignedIntTy;
6149 FieldNames[0] = "gp_offset";
6150
6151 // unsigned fp_offset;
6152 FieldTypes[1] = Context->UnsignedIntTy;
6153 FieldNames[1] = "fp_offset";
6154
6155 // void* overflow_arg_area;
6156 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6157 FieldNames[2] = "overflow_arg_area";
6158
6159 // void* reg_save_area;
6160 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6161 FieldNames[3] = "reg_save_area";
6162
6163 // Create fields
6164 for (unsigned i = 0; i < NumFields; ++i) {
6165 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6166 VaListTagDecl,
6167 SourceLocation(),
6168 SourceLocation(),
6169 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006170 FieldTypes[i], /*TInfo=*/nullptr,
6171 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006172 /*Mutable=*/false,
6173 ICIS_NoInit);
6174 Field->setAccess(AS_public);
6175 VaListTagDecl->addDecl(Field);
6176 }
6177 VaListTagDecl->completeDefinition();
6178 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006179 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006180
6181 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006182 TypedefDecl *VaListTagTypedefDecl =
6183 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6184
Meador Inge5d3fb222012-06-16 03:34:49 +00006185 QualType VaListTagTypedefType =
6186 Context->getTypedefType(VaListTagTypedefDecl);
6187
6188 // typedef __va_list_tag __builtin_va_list[1];
6189 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6190 QualType VaListTagArrayType
6191 = Context->getConstantArrayType(VaListTagTypedefType,
6192 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006193 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006194}
6195
6196static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6197 // typedef int __builtin_va_list[4];
6198 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6199 QualType IntArrayType
6200 = Context->getConstantArrayType(Context->IntTy,
6201 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006202 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006203}
6204
Logan Chien57086ce2012-10-10 06:56:20 +00006205static TypedefDecl *
6206CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006207 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006208 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006209 if (Context->getLangOpts().CPlusPlus) {
6210 // namespace std { struct __va_list {
6211 NamespaceDecl *NS;
6212 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6213 Context->getTranslationUnitDecl(),
6214 /*Inline*/false, SourceLocation(),
6215 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006216 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006217 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006218 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006219 }
6220
6221 VaListDecl->startDefinition();
6222
6223 // void * __ap;
6224 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6225 VaListDecl,
6226 SourceLocation(),
6227 SourceLocation(),
6228 &Context->Idents.get("__ap"),
6229 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006230 /*TInfo=*/nullptr,
6231 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006232 /*Mutable=*/false,
6233 ICIS_NoInit);
6234 Field->setAccess(AS_public);
6235 VaListDecl->addDecl(Field);
6236
6237 // };
6238 VaListDecl->completeDefinition();
6239
6240 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006241 QualType T = Context->getRecordType(VaListDecl);
6242 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006243}
6244
Ulrich Weigand47445072013-05-06 16:26:41 +00006245static TypedefDecl *
6246CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6247 // typedef struct __va_list_tag {
6248 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006249 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006250 VaListTagDecl->startDefinition();
6251
6252 const size_t NumFields = 4;
6253 QualType FieldTypes[NumFields];
6254 const char *FieldNames[NumFields];
6255
6256 // long __gpr;
6257 FieldTypes[0] = Context->LongTy;
6258 FieldNames[0] = "__gpr";
6259
6260 // long __fpr;
6261 FieldTypes[1] = Context->LongTy;
6262 FieldNames[1] = "__fpr";
6263
6264 // void *__overflow_arg_area;
6265 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6266 FieldNames[2] = "__overflow_arg_area";
6267
6268 // void *__reg_save_area;
6269 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6270 FieldNames[3] = "__reg_save_area";
6271
6272 // Create fields
6273 for (unsigned i = 0; i < NumFields; ++i) {
6274 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6275 VaListTagDecl,
6276 SourceLocation(),
6277 SourceLocation(),
6278 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006279 FieldTypes[i], /*TInfo=*/nullptr,
6280 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006281 /*Mutable=*/false,
6282 ICIS_NoInit);
6283 Field->setAccess(AS_public);
6284 VaListTagDecl->addDecl(Field);
6285 }
6286 VaListTagDecl->completeDefinition();
6287 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6288 Context->VaListTagTy = VaListTagType;
6289
6290 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006291 TypedefDecl *VaListTagTypedefDecl =
6292 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006293 QualType VaListTagTypedefType =
6294 Context->getTypedefType(VaListTagTypedefDecl);
6295
6296 // typedef __va_list_tag __builtin_va_list[1];
6297 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6298 QualType VaListTagArrayType
6299 = Context->getConstantArrayType(VaListTagTypedefType,
6300 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006301
Alp Toker56b5cc92013-12-15 10:36:26 +00006302 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006303}
6304
Meador Inge5d3fb222012-06-16 03:34:49 +00006305static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6306 TargetInfo::BuiltinVaListKind Kind) {
6307 switch (Kind) {
6308 case TargetInfo::CharPtrBuiltinVaList:
6309 return CreateCharPtrBuiltinVaListDecl(Context);
6310 case TargetInfo::VoidPtrBuiltinVaList:
6311 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006312 case TargetInfo::AArch64ABIBuiltinVaList:
6313 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006314 case TargetInfo::PowerABIBuiltinVaList:
6315 return CreatePowerABIBuiltinVaListDecl(Context);
6316 case TargetInfo::X86_64ABIBuiltinVaList:
6317 return CreateX86_64ABIBuiltinVaListDecl(Context);
6318 case TargetInfo::PNaClABIBuiltinVaList:
6319 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006320 case TargetInfo::AAPCSABIBuiltinVaList:
6321 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006322 case TargetInfo::SystemZBuiltinVaList:
6323 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006324 }
6325
6326 llvm_unreachable("Unhandled __builtin_va_list type kind");
6327}
6328
6329TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006330 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006331 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006332 assert(BuiltinVaListDecl->isImplicit());
6333 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006334
6335 return BuiltinVaListDecl;
6336}
6337
Meador Ingecfb60902012-07-01 15:57:25 +00006338QualType ASTContext::getVaListTagType() const {
6339 // Force the creation of VaListTagTy by building the __builtin_va_list
6340 // declaration.
6341 if (VaListTagTy.isNull())
6342 (void) getBuiltinVaListDecl();
6343
6344 return VaListTagTy;
6345}
6346
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006347void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006348 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006349 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006350
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006351 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006352}
6353
John McCalld28ae272009-12-02 08:04:21 +00006354/// \brief Retrieve the template name that corresponds to a non-empty
6355/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006356TemplateName
6357ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6358 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006359 unsigned size = End - Begin;
6360 assert(size > 1 && "set is not overloaded!");
6361
6362 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6363 size * sizeof(FunctionTemplateDecl*));
6364 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6365
6366 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006367 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006368 NamedDecl *D = *I;
6369 assert(isa<FunctionTemplateDecl>(D) ||
6370 (isa<UsingShadowDecl>(D) &&
6371 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6372 *Storage++ = D;
6373 }
6374
6375 return TemplateName(OT);
6376}
6377
Douglas Gregordc572a32009-03-30 22:58:21 +00006378/// \brief Retrieve the template name that represents a qualified
6379/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006380TemplateName
6381ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6382 bool TemplateKeyword,
6383 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006384 assert(NNS && "Missing nested-name-specifier in qualified template name");
6385
Douglas Gregorc42075a2010-02-04 18:10:26 +00006386 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006387 llvm::FoldingSetNodeID ID;
6388 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6389
Craig Topper36250ad2014-05-12 05:36:57 +00006390 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006391 QualifiedTemplateName *QTN =
6392 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6393 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006394 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6395 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006396 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6397 }
6398
6399 return TemplateName(QTN);
6400}
6401
6402/// \brief Retrieve the template name that represents a dependent
6403/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006404TemplateName
6405ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6406 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006407 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006408 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006409
6410 llvm::FoldingSetNodeID ID;
6411 DependentTemplateName::Profile(ID, NNS, Name);
6412
Craig Topper36250ad2014-05-12 05:36:57 +00006413 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006414 DependentTemplateName *QTN =
6415 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6416
6417 if (QTN)
6418 return TemplateName(QTN);
6419
6420 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6421 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006422 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6423 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006424 } else {
6425 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006426 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6427 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006428 DependentTemplateName *CheckQTN =
6429 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6430 assert(!CheckQTN && "Dependent type name canonicalization broken");
6431 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006432 }
6433
6434 DependentTemplateNames.InsertNode(QTN, InsertPos);
6435 return TemplateName(QTN);
6436}
6437
Douglas Gregor71395fa2009-11-04 00:56:37 +00006438/// \brief Retrieve the template name that represents a dependent
6439/// template name such as \c MetaFun::template operator+.
6440TemplateName
6441ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006442 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006443 assert((!NNS || NNS->isDependent()) &&
6444 "Nested name specifier must be dependent");
6445
6446 llvm::FoldingSetNodeID ID;
6447 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006448
6449 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006450 DependentTemplateName *QTN
6451 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006452
6453 if (QTN)
6454 return TemplateName(QTN);
6455
6456 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6457 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006458 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6459 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006460 } else {
6461 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006462 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6463 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006464
6465 DependentTemplateName *CheckQTN
6466 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6467 assert(!CheckQTN && "Dependent template name canonicalization broken");
6468 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006469 }
6470
6471 DependentTemplateNames.InsertNode(QTN, InsertPos);
6472 return TemplateName(QTN);
6473}
6474
Douglas Gregor5590be02011-01-15 06:45:20 +00006475TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006476ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6477 TemplateName replacement) const {
6478 llvm::FoldingSetNodeID ID;
6479 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006480
6481 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006482 SubstTemplateTemplateParmStorage *subst
6483 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6484
6485 if (!subst) {
6486 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6487 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6488 }
6489
6490 return TemplateName(subst);
6491}
6492
6493TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006494ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6495 const TemplateArgument &ArgPack) const {
6496 ASTContext &Self = const_cast<ASTContext &>(*this);
6497 llvm::FoldingSetNodeID ID;
6498 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006499
6500 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006501 SubstTemplateTemplateParmPackStorage *Subst
6502 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6503
6504 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006505 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006506 ArgPack.pack_size(),
6507 ArgPack.pack_begin());
6508 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6509 }
6510
6511 return TemplateName(Subst);
6512}
6513
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006514/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006515/// TargetInfo, produce the corresponding type. The unsigned @p Type
6516/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006517CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006518 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006519 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006520 case TargetInfo::SignedChar: return SignedCharTy;
6521 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006522 case TargetInfo::SignedShort: return ShortTy;
6523 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6524 case TargetInfo::SignedInt: return IntTy;
6525 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6526 case TargetInfo::SignedLong: return LongTy;
6527 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6528 case TargetInfo::SignedLongLong: return LongLongTy;
6529 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6530 }
6531
David Blaikie83d382b2011-09-23 05:06:16 +00006532 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006533}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006534
6535//===----------------------------------------------------------------------===//
6536// Type Predicates.
6537//===----------------------------------------------------------------------===//
6538
Fariborz Jahanian96207692009-02-18 21:49:28 +00006539/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6540/// garbage collection attribute.
6541///
John McCall553d45a2011-01-12 00:34:59 +00006542Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006543 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006544 return Qualifiers::GCNone;
6545
David Blaikiebbafb8a2012-03-11 07:00:24 +00006546 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006547 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6548
6549 // Default behaviour under objective-C's gc is for ObjC pointers
6550 // (or pointers to them) be treated as though they were declared
6551 // as __strong.
6552 if (GCAttrs == Qualifiers::GCNone) {
6553 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6554 return Qualifiers::Strong;
6555 else if (Ty->isPointerType())
6556 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6557 } else {
6558 // It's not valid to set GC attributes on anything that isn't a
6559 // pointer.
6560#ifndef NDEBUG
6561 QualType CT = Ty->getCanonicalTypeInternal();
6562 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6563 CT = AT->getElementType();
6564 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6565#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006566 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006567 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006568}
6569
Chris Lattner49af6a42008-04-07 06:51:04 +00006570//===----------------------------------------------------------------------===//
6571// Type Compatibility Testing
6572//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006573
Mike Stump11289f42009-09-09 15:08:12 +00006574/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006575/// compatible.
6576static bool areCompatVectorTypes(const VectorType *LHS,
6577 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006578 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006579 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006580 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006581}
6582
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006583bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6584 QualType SecondVec) {
6585 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6586 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6587
6588 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6589 return true;
6590
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006591 // Treat Neon vector types and most AltiVec vector types as if they are the
6592 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006593 const VectorType *First = FirstVec->getAs<VectorType>();
6594 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006595 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006596 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006597 First->getVectorKind() != VectorType::AltiVecPixel &&
6598 First->getVectorKind() != VectorType::AltiVecBool &&
6599 Second->getVectorKind() != VectorType::AltiVecPixel &&
6600 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006601 return true;
6602
6603 return false;
6604}
6605
Steve Naroff8e6aee52009-07-23 01:01:38 +00006606//===----------------------------------------------------------------------===//
6607// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6608//===----------------------------------------------------------------------===//
6609
6610/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6611/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006612bool
6613ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6614 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006615 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006616 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006617 for (auto *PI : rProto->protocols())
6618 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006619 return true;
6620 return false;
6621}
6622
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006623/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6624/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006625bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6626 QualType rhs) {
6627 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6628 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6629 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6630
Aaron Ballman83731462014-03-17 16:14:00 +00006631 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006632 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006633 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006634 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6635 match = true;
6636 break;
6637 }
6638 }
6639 if (!match)
6640 return false;
6641 }
6642 return true;
6643}
6644
Steve Naroff8e6aee52009-07-23 01:01:38 +00006645/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6646/// ObjCQualifiedIDType.
6647bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6648 bool compare) {
6649 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006650 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006651 lhs->isObjCIdType() || lhs->isObjCClassType())
6652 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006653 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006654 rhs->isObjCIdType() || rhs->isObjCClassType())
6655 return true;
6656
6657 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006658 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006659
Steve Naroff8e6aee52009-07-23 01:01:38 +00006660 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006661
Steve Naroff8e6aee52009-07-23 01:01:38 +00006662 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006663 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006664 // make sure we check the class hierarchy.
6665 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006666 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006667 // when comparing an id<P> on lhs with a static type on rhs,
6668 // see if static class implements all of id's protocols, directly or
6669 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006670 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006671 return false;
6672 }
6673 }
6674 // If there are no qualifiers and no interface, we have an 'id'.
6675 return true;
6676 }
Mike Stump11289f42009-09-09 15:08:12 +00006677 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006678 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006679 bool match = false;
6680
6681 // when comparing an id<P> on lhs with a static type on rhs,
6682 // see if static class implements all of id's protocols, directly or
6683 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006684 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006685 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6686 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6687 match = true;
6688 break;
6689 }
6690 }
Mike Stump11289f42009-09-09 15:08:12 +00006691 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006692 // make sure we check the class hierarchy.
6693 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006694 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006695 // when comparing an id<P> on lhs with a static type on rhs,
6696 // see if static class implements all of id's protocols, directly or
6697 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006698 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006699 match = true;
6700 break;
6701 }
6702 }
6703 }
6704 if (!match)
6705 return false;
6706 }
Mike Stump11289f42009-09-09 15:08:12 +00006707
Steve Naroff8e6aee52009-07-23 01:01:38 +00006708 return true;
6709 }
Mike Stump11289f42009-09-09 15:08:12 +00006710
Steve Naroff8e6aee52009-07-23 01:01:38 +00006711 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6712 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6713
Mike Stump11289f42009-09-09 15:08:12 +00006714 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006715 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006716 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006717 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006718 bool match = false;
6719
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006720 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006721 // see if static class implements all of id's protocols, directly or
6722 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006723 // First, lhs protocols in the qualifier list must be found, direct
6724 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006725 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006726 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6727 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6728 match = true;
6729 break;
6730 }
6731 }
6732 if (!match)
6733 return false;
6734 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006735
6736 // Static class's protocols, or its super class or category protocols
6737 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6738 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6739 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6740 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6741 // This is rather dubious but matches gcc's behavior. If lhs has
6742 // no type qualifier and its class has no static protocol(s)
6743 // assume that it is mismatch.
6744 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6745 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006746 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006747 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006748 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006749 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6750 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6751 match = true;
6752 break;
6753 }
6754 }
6755 if (!match)
6756 return false;
6757 }
6758 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006759 return true;
6760 }
6761 return false;
6762}
6763
Eli Friedman47f77112008-08-22 00:56:42 +00006764/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006765/// compatible for assignment from RHS to LHS. This handles validation of any
6766/// protocol qualifiers on the LHS or RHS.
6767///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006768bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6769 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006770 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6771 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6772
Steve Naroff1329fa02009-07-15 18:40:39 +00006773 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006774 if (LHS->isObjCUnqualifiedIdOrClass() ||
6775 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006776 return true;
6777
John McCall8b07ec22010-05-15 11:32:37 +00006778 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006779 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6780 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006781 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006782
6783 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6784 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6785 QualType(RHSOPT,0));
6786
John McCall8b07ec22010-05-15 11:32:37 +00006787 // If we have 2 user-defined types, fall into that path.
6788 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006789 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006790
Steve Naroff8e6aee52009-07-23 01:01:38 +00006791 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006792}
6793
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006794/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006795/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006796/// arguments in block literals. When passed as arguments, passing 'A*' where
6797/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6798/// not OK. For the return type, the opposite is not OK.
6799bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6800 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006801 const ObjCObjectPointerType *RHSOPT,
6802 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006803 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006804 return true;
6805
6806 if (LHSOPT->isObjCBuiltinType()) {
6807 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6808 }
6809
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006810 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006811 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6812 QualType(RHSOPT,0),
6813 false);
6814
6815 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6816 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6817 if (LHS && RHS) { // We have 2 user-defined types.
6818 if (LHS != RHS) {
6819 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006820 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006821 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006822 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006823 }
6824 else
6825 return true;
6826 }
6827 return false;
6828}
6829
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006830/// Comparison routine for Objective-C protocols to be used with
6831/// llvm::array_pod_sort.
6832static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6833 ObjCProtocolDecl * const *rhs) {
6834 return (*lhs)->getName().compare((*rhs)->getName());
6835
6836}
6837
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006838/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006839/// of protocols inherited from two distinct objective-c pointer objects with
6840/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006841/// It is used to build composite qualifier list of the composite type of
6842/// the conditional expression involving two objective-c pointer objects.
6843static
6844void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006845 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006846 const ObjCObjectPointerType *LHSOPT,
6847 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006848 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006849
John McCall8b07ec22010-05-15 11:32:37 +00006850 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6851 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6852 assert(LHS->getInterface() && "LHS must have an interface base");
6853 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006854
6855 // Add all of the protocols for the LHS.
6856 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6857
6858 // Start with the protocol qualifiers.
6859 for (auto proto : LHS->quals()) {
6860 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006861 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006862
6863 // Also add the protocols associated with the LHS interface.
6864 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6865
6866 // Add all of the protocls for the RHS.
6867 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6868
6869 // Start with the protocol qualifiers.
6870 for (auto proto : RHS->quals()) {
6871 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006872 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006873
6874 // Also add the protocols associated with the RHS interface.
6875 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
6876
6877 // Compute the intersection of the collected protocol sets.
6878 for (auto proto : LHSProtocolSet) {
6879 if (RHSProtocolSet.count(proto))
6880 IntersectionSet.push_back(proto);
6881 }
6882
6883 // Compute the set of protocols that is implied by either the common type or
6884 // the protocols within the intersection.
6885 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
6886 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
6887
6888 // Remove any implied protocols from the list of inherited protocols.
6889 if (!ImpliedProtocols.empty()) {
6890 IntersectionSet.erase(
6891 std::remove_if(IntersectionSet.begin(),
6892 IntersectionSet.end(),
6893 [&](ObjCProtocolDecl *proto) -> bool {
6894 return ImpliedProtocols.count(proto) > 0;
6895 }),
6896 IntersectionSet.end());
6897 }
6898
6899 // Sort the remaining protocols by name.
6900 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
6901 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006902}
6903
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006904// Check that the given Objective-C type argument lists are equivalent.
6905static bool sameObjCTypeArgs(const ASTContext &ctx, ArrayRef<QualType> lhsArgs,
6906 ArrayRef<QualType> rhsArgs) {
6907 if (lhsArgs.size() != rhsArgs.size())
6908 return false;
6909
6910 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
6911 if (!ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
6912 return false;
6913 }
6914
6915 return true;
6916}
6917
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006918QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006919 const ObjCObjectPointerType *Lptr,
6920 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00006921 const ObjCObjectType *LHS = Lptr->getObjectType();
6922 const ObjCObjectType *RHS = Rptr->getObjectType();
6923 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6924 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006925
6926 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006927 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00006928
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006929 // Follow the left-hand side up the class hierarchy until we either hit a
6930 // root or find the RHS. Record the ancestors in case we don't find it.
6931 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
6932 LHSAncestors;
6933 while (true) {
6934 // Record this ancestor. We'll need this if the common type isn't in the
6935 // path from the LHS to the root.
6936 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00006937
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006938 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
6939 // Get the type arguments.
6940 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
6941 bool anyChanges = false;
6942 if (LHS->isSpecialized() && RHS->isSpecialized()) {
6943 // Both have type arguments, compare them.
6944 if (!sameObjCTypeArgs(*this, LHS->getTypeArgs(), RHS->getTypeArgs()))
6945 return QualType();
6946 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
6947 // If only one has type arguments, the result will not have type
6948 // arguments.
6949 LHSTypeArgs = { };
6950 anyChanges = true;
6951 }
6952
6953 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006954 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006955 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
6956 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00006957 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006958 anyChanges = true;
6959
6960 // If anything in the LHS will have changed, build a new result type.
6961 if (anyChanges) {
6962 QualType Result = getObjCInterfaceType(LHS->getInterface());
6963 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols);
6964 return getObjCObjectPointerType(Result);
6965 }
6966
6967 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006968 }
Douglas Gregore83b9562015-07-07 03:57:53 +00006969
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006970 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00006971 QualType LHSSuperType = LHS->getSuperClassType();
6972 if (LHSSuperType.isNull())
6973 break;
6974
6975 LHS = LHSSuperType->castAs<ObjCObjectType>();
6976 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006977
6978 // We didn't find anything by following the LHS to its root; now check
6979 // the RHS against the cached set of ancestors.
6980 while (true) {
6981 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
6982 if (KnownLHS != LHSAncestors.end()) {
6983 LHS = KnownLHS->second;
6984
6985 // Get the type arguments.
6986 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
6987 bool anyChanges = false;
6988 if (LHS->isSpecialized() && RHS->isSpecialized()) {
6989 // Both have type arguments, compare them.
6990 if (!sameObjCTypeArgs(*this, LHS->getTypeArgs(), RHS->getTypeArgs()))
6991 return QualType();
6992 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
6993 // If only one has type arguments, the result will not have type
6994 // arguments.
6995 RHSTypeArgs = { };
6996 anyChanges = true;
6997 }
6998
6999 // Compute the intersection of protocols.
7000 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7001 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7002 Protocols);
7003 if (!Protocols.empty())
7004 anyChanges = true;
7005
7006 if (anyChanges) {
7007 QualType Result = getObjCInterfaceType(RHS->getInterface());
7008 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols);
7009 return getObjCObjectPointerType(Result);
7010 }
7011
7012 return getObjCObjectPointerType(QualType(RHS, 0));
7013 }
7014
7015 // Find the superclass of the RHS.
7016 QualType RHSSuperType = RHS->getSuperClassType();
7017 if (RHSSuperType.isNull())
7018 break;
7019
7020 RHS = RHSSuperType->castAs<ObjCObjectType>();
7021 }
7022
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007023 return QualType();
7024}
7025
John McCall8b07ec22010-05-15 11:32:37 +00007026bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7027 const ObjCObjectType *RHS) {
7028 assert(LHS->getInterface() && "LHS is not an interface type");
7029 assert(RHS->getInterface() && "RHS is not an interface type");
7030
Chris Lattner49af6a42008-04-07 06:51:04 +00007031 // Verify that the base decls are compatible: the RHS must be a subclass of
7032 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007033 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7034 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7035 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007036 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007037
Douglas Gregore83b9562015-07-07 03:57:53 +00007038 // If the LHS has protocol qualifiers, determine whether all of them are
7039 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7040 // LHS).
7041 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007042 // OK if conversion of LHS to SuperClass results in narrowing of types
7043 // ; i.e., SuperClass may implement at least one of the protocols
7044 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7045 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7046 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7047 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7048 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7049 // qualifiers.
7050 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007051 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007052 // If there is no protocols associated with RHS, it is not a match.
7053 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007054 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007055
7056 for (const auto *LHSProto : LHS->quals()) {
7057 bool SuperImplementsProtocol = false;
7058 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7059 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7060 SuperImplementsProtocol = true;
7061 break;
7062 }
7063 if (!SuperImplementsProtocol)
7064 return false;
7065 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007066 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007067
7068 // If the LHS is specialized, we may need to check type arguments.
7069 if (LHS->isSpecialized()) {
7070 // Follow the superclass chain until we've matched the LHS class in the
7071 // hierarchy. This substitutes type arguments through.
7072 const ObjCObjectType *RHSSuper = RHS;
7073 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7074 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7075
7076 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007077 if (RHSSuper->isSpecialized() &&
7078 !sameObjCTypeArgs(*this, LHS->getTypeArgs(), RHSSuper->getTypeArgs())) {
7079 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007080 }
7081 }
7082
7083 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007084}
7085
Steve Naroffb7605152009-02-12 17:52:19 +00007086bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7087 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007088 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7089 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007090
Steve Naroff7cae42b2009-07-10 23:34:53 +00007091 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007092 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007093
7094 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7095 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007096}
7097
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007098bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7099 return canAssignObjCInterfaces(
7100 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7101 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7102}
7103
Mike Stump11289f42009-09-09 15:08:12 +00007104/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007105/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007106/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007107/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007108bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7109 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007110 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007111 return hasSameType(LHS, RHS);
7112
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007113 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007114}
7115
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007116bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007117 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007118}
7119
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007120bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7121 return !mergeTypes(LHS, RHS, true).isNull();
7122}
7123
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007124/// mergeTransparentUnionType - if T is a transparent union type and a member
7125/// of T is compatible with SubType, return the merged type, else return
7126/// QualType()
7127QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7128 bool OfBlockPointer,
7129 bool Unqualified) {
7130 if (const RecordType *UT = T->getAsUnionType()) {
7131 RecordDecl *UD = UT->getDecl();
7132 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007133 for (const auto *I : UD->fields()) {
7134 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007135 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7136 if (!MT.isNull())
7137 return MT;
7138 }
7139 }
7140 }
7141
7142 return QualType();
7143}
7144
Alp Toker9cacbab2014-01-20 20:26:09 +00007145/// mergeFunctionParameterTypes - merge two types which appear as function
7146/// parameter types
7147QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7148 bool OfBlockPointer,
7149 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007150 // GNU extension: two types are compatible if they appear as a function
7151 // argument, one of the types is a transparent union type and the other
7152 // type is compatible with a union member
7153 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7154 Unqualified);
7155 if (!lmerge.isNull())
7156 return lmerge;
7157
7158 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7159 Unqualified);
7160 if (!rmerge.isNull())
7161 return rmerge;
7162
7163 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7164}
7165
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007166QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007167 bool OfBlockPointer,
7168 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007169 const FunctionType *lbase = lhs->getAs<FunctionType>();
7170 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007171 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7172 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007173 bool allLTypes = true;
7174 bool allRTypes = true;
7175
7176 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007177 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007178 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007179 QualType RHS = rbase->getReturnType();
7180 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007181 bool UnqualifiedResult = Unqualified;
7182 if (!UnqualifiedResult)
7183 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007184 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007185 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007186 else
Alp Toker314cc812014-01-25 16:55:45 +00007187 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007188 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007189 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007190
7191 if (Unqualified)
7192 retType = retType.getUnqualifiedType();
7193
Alp Toker314cc812014-01-25 16:55:45 +00007194 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7195 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007196 if (Unqualified) {
7197 LRetType = LRetType.getUnqualifiedType();
7198 RRetType = RRetType.getUnqualifiedType();
7199 }
7200
7201 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007202 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007203 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007204 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007205
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007206 // FIXME: double check this
7207 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7208 // rbase->getRegParmAttr() != 0 &&
7209 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007210 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7211 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007212
Douglas Gregor8c940862010-01-18 17:14:39 +00007213 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007214 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007215 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007216
John McCall8c6b56f2010-12-15 01:06:38 +00007217 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007218 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7219 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007220 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7221 return QualType();
7222
John McCall31168b02011-06-15 23:02:42 +00007223 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7224 return QualType();
7225
John McCall8c6b56f2010-12-15 01:06:38 +00007226 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7227 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007228
Rafael Espindola8778c282012-11-29 16:09:03 +00007229 if (lbaseInfo.getNoReturn() != NoReturn)
7230 allLTypes = false;
7231 if (rbaseInfo.getNoReturn() != NoReturn)
7232 allRTypes = false;
7233
John McCall31168b02011-06-15 23:02:42 +00007234 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007235
Eli Friedman47f77112008-08-22 00:56:42 +00007236 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007237 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7238 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007239 // Compatible functions must have the same number of parameters
7240 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007241 return QualType();
7242
7243 // Variadic and non-variadic functions aren't compatible
7244 if (lproto->isVariadic() != rproto->isVariadic())
7245 return QualType();
7246
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007247 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7248 return QualType();
7249
Fariborz Jahanian97676972011-09-28 21:52:05 +00007250 if (LangOpts.ObjCAutoRefCount &&
7251 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7252 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007253
7254 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007255 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007256 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7257 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7258 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7259 QualType paramType = mergeFunctionParameterTypes(
7260 lParamType, rParamType, OfBlockPointer, Unqualified);
7261 if (paramType.isNull())
7262 return QualType();
7263
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007264 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007265 paramType = paramType.getUnqualifiedType();
7266
7267 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007268 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007269 lParamType = lParamType.getUnqualifiedType();
7270 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007271 }
Alp Toker601b22c2014-01-21 23:35:24 +00007272
7273 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007274 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007275 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007276 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007277 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007278
Eli Friedman47f77112008-08-22 00:56:42 +00007279 if (allLTypes) return lhs;
7280 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007281
7282 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7283 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007284 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007285 }
7286
7287 if (lproto) allRTypes = false;
7288 if (rproto) allLTypes = false;
7289
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007290 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007291 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007292 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007293 if (proto->isVariadic()) return QualType();
7294 // Check that the types are compatible with the types that
7295 // would result from default argument promotions (C99 6.7.5.3p15).
7296 // The only types actually affected are promotable integer
7297 // types and floats, which would be passed as a different
7298 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007299 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7300 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007301
Eli Friedman448ce402012-08-30 00:44:15 +00007302 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007303 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007304 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7305 paramTy = Enum->getDecl()->getIntegerType();
7306 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007307 return QualType();
7308 }
Alp Toker601b22c2014-01-21 23:35:24 +00007309
7310 if (paramTy->isPromotableIntegerType() ||
7311 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007312 return QualType();
7313 }
7314
7315 if (allLTypes) return lhs;
7316 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007317
7318 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7319 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007320 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007321 }
7322
7323 if (allLTypes) return lhs;
7324 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007325 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007326}
7327
John McCall433c2e62013-03-21 00:10:07 +00007328/// Given that we have an enum type and a non-enum type, try to merge them.
7329static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7330 QualType other, bool isBlockReturnType) {
7331 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7332 // a signed integer type, or an unsigned integer type.
7333 // Compatibility is based on the underlying type, not the promotion
7334 // type.
7335 QualType underlyingType = ET->getDecl()->getIntegerType();
7336 if (underlyingType.isNull()) return QualType();
7337 if (Context.hasSameType(underlyingType, other))
7338 return other;
7339
7340 // In block return types, we're more permissive and accept any
7341 // integral type of the same size.
7342 if (isBlockReturnType && other->isIntegerType() &&
7343 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7344 return other;
7345
7346 return QualType();
7347}
7348
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007349QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007350 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007351 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007352 // C++ [expr]: If an expression initially has the type "reference to T", the
7353 // type is adjusted to "T" prior to any further analysis, the expression
7354 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007355 // expression is an lvalue unless the reference is an rvalue reference and
7356 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007357 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7358 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007359
7360 if (Unqualified) {
7361 LHS = LHS.getUnqualifiedType();
7362 RHS = RHS.getUnqualifiedType();
7363 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007364
Eli Friedman47f77112008-08-22 00:56:42 +00007365 QualType LHSCan = getCanonicalType(LHS),
7366 RHSCan = getCanonicalType(RHS);
7367
7368 // If two types are identical, they are compatible.
7369 if (LHSCan == RHSCan)
7370 return LHS;
7371
John McCall8ccfcb52009-09-24 19:53:00 +00007372 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007373 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7374 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007375 if (LQuals != RQuals) {
7376 // If any of these qualifiers are different, we have a type
7377 // mismatch.
7378 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007379 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7380 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007381 return QualType();
7382
7383 // Exactly one GC qualifier difference is allowed: __strong is
7384 // okay if the other type has no GC qualifier but is an Objective
7385 // C object pointer (i.e. implicitly strong by default). We fix
7386 // this by pretending that the unqualified type was actually
7387 // qualified __strong.
7388 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7389 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7390 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7391
7392 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7393 return QualType();
7394
7395 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7396 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7397 }
7398 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7399 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7400 }
Eli Friedman47f77112008-08-22 00:56:42 +00007401 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007402 }
7403
7404 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007405
Eli Friedmandcca6332009-06-01 01:22:52 +00007406 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7407 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007408
Chris Lattnerfd652912008-01-14 05:45:46 +00007409 // We want to consider the two function types to be the same for these
7410 // comparisons, just force one to the other.
7411 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7412 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007413
7414 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007415 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7416 LHSClass = Type::ConstantArray;
7417 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7418 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007419
John McCall8b07ec22010-05-15 11:32:37 +00007420 // ObjCInterfaces are just specialized ObjCObjects.
7421 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7422 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7423
Nate Begemance4d7fc2008-04-18 23:10:10 +00007424 // Canonicalize ExtVector -> Vector.
7425 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7426 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007427
Chris Lattner95554662008-04-07 05:43:21 +00007428 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007429 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007430 // Note that we only have special rules for turning block enum
7431 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007432 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007433 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007434 }
John McCall9dd450b2009-09-21 23:43:11 +00007435 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007436 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007437 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007438 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007439 if (OfBlockPointer && !BlockReturnType) {
7440 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7441 return LHS;
7442 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7443 return RHS;
7444 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007445
Eli Friedman47f77112008-08-22 00:56:42 +00007446 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007447 }
Eli Friedman47f77112008-08-22 00:56:42 +00007448
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007449 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007450 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007451#define TYPE(Class, Base)
7452#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007453#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007454#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7455#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7456#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007457 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007458
Richard Smith27d807c2013-04-30 13:56:41 +00007459 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007460 case Type::LValueReference:
7461 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007462 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007463 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007464
John McCall8b07ec22010-05-15 11:32:37 +00007465 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007466 case Type::IncompleteArray:
7467 case Type::VariableArray:
7468 case Type::FunctionProto:
7469 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007470 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007471
Chris Lattnerfd652912008-01-14 05:45:46 +00007472 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007473 {
7474 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007475 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7476 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007477 if (Unqualified) {
7478 LHSPointee = LHSPointee.getUnqualifiedType();
7479 RHSPointee = RHSPointee.getUnqualifiedType();
7480 }
7481 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7482 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007483 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007484 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007485 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007486 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007487 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007488 return getPointerType(ResultType);
7489 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007490 case Type::BlockPointer:
7491 {
7492 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007493 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7494 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007495 if (Unqualified) {
7496 LHSPointee = LHSPointee.getUnqualifiedType();
7497 RHSPointee = RHSPointee.getUnqualifiedType();
7498 }
7499 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7500 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007501 if (ResultType.isNull()) return QualType();
7502 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7503 return LHS;
7504 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7505 return RHS;
7506 return getBlockPointerType(ResultType);
7507 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007508 case Type::Atomic:
7509 {
7510 // Merge two pointer types, while trying to preserve typedef info
7511 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7512 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7513 if (Unqualified) {
7514 LHSValue = LHSValue.getUnqualifiedType();
7515 RHSValue = RHSValue.getUnqualifiedType();
7516 }
7517 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7518 Unqualified);
7519 if (ResultType.isNull()) return QualType();
7520 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7521 return LHS;
7522 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7523 return RHS;
7524 return getAtomicType(ResultType);
7525 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007526 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007527 {
7528 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7529 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7530 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7531 return QualType();
7532
7533 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7534 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007535 if (Unqualified) {
7536 LHSElem = LHSElem.getUnqualifiedType();
7537 RHSElem = RHSElem.getUnqualifiedType();
7538 }
7539
7540 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007541 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007542 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7543 return LHS;
7544 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7545 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007546 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7547 ArrayType::ArraySizeModifier(), 0);
7548 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7549 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007550 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7551 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007552 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7553 return LHS;
7554 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7555 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007556 if (LVAT) {
7557 // FIXME: This isn't correct! But tricky to implement because
7558 // the array's size has to be the size of LHS, but the type
7559 // has to be different.
7560 return LHS;
7561 }
7562 if (RVAT) {
7563 // FIXME: This isn't correct! But tricky to implement because
7564 // the array's size has to be the size of RHS, but the type
7565 // has to be different.
7566 return RHS;
7567 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007568 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7569 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007570 return getIncompleteArrayType(ResultType,
7571 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007572 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007573 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007574 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007575 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007576 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007577 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007578 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007579 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007580 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007581 case Type::Complex:
7582 // Distinct complex types are incompatible.
7583 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007584 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007585 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007586 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7587 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007588 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007589 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007590 case Type::ObjCObject: {
7591 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007592 // FIXME: This should be type compatibility, e.g. whether
7593 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007594 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7595 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7596 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007597 return LHS;
7598
Eli Friedman47f77112008-08-22 00:56:42 +00007599 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007600 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007601 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007602 if (OfBlockPointer) {
7603 if (canAssignObjCInterfacesInBlockPointer(
7604 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007605 RHS->getAs<ObjCObjectPointerType>(),
7606 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007607 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007608 return QualType();
7609 }
John McCall9dd450b2009-09-21 23:43:11 +00007610 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7611 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007612 return LHS;
7613
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007614 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007615 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007616 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007617
David Blaikie8a40f702012-01-17 06:56:22 +00007618 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007619}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007620
Fariborz Jahanian97676972011-09-28 21:52:05 +00007621bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7622 const FunctionProtoType *FromFunctionType,
7623 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007624 if (FromFunctionType->hasAnyConsumedParams() !=
7625 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007626 return false;
7627 FunctionProtoType::ExtProtoInfo FromEPI =
7628 FromFunctionType->getExtProtoInfo();
7629 FunctionProtoType::ExtProtoInfo ToEPI =
7630 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007631 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007632 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7633 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007634 return false;
7635 }
7636 return true;
7637}
7638
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007639/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7640/// 'RHS' attributes and returns the merged version; including for function
7641/// return types.
7642QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7643 QualType LHSCan = getCanonicalType(LHS),
7644 RHSCan = getCanonicalType(RHS);
7645 // If two types are identical, they are compatible.
7646 if (LHSCan == RHSCan)
7647 return LHS;
7648 if (RHSCan->isFunctionType()) {
7649 if (!LHSCan->isFunctionType())
7650 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007651 QualType OldReturnType =
7652 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007653 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007654 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007655 QualType ResReturnType =
7656 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7657 if (ResReturnType.isNull())
7658 return QualType();
7659 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7660 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7661 // In either case, use OldReturnType to build the new function type.
7662 const FunctionType *F = LHS->getAs<FunctionType>();
7663 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007664 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7665 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007666 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007667 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007668 return ResultType;
7669 }
7670 }
7671 return QualType();
7672 }
7673
7674 // If the qualifiers are different, the types can still be merged.
7675 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7676 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7677 if (LQuals != RQuals) {
7678 // If any of these qualifiers are different, we have a type mismatch.
7679 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7680 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7681 return QualType();
7682
7683 // Exactly one GC qualifier difference is allowed: __strong is
7684 // okay if the other type has no GC qualifier but is an Objective
7685 // C object pointer (i.e. implicitly strong by default). We fix
7686 // this by pretending that the unqualified type was actually
7687 // qualified __strong.
7688 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7689 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7690 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7691
7692 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7693 return QualType();
7694
7695 if (GC_L == Qualifiers::Strong)
7696 return LHS;
7697 if (GC_R == Qualifiers::Strong)
7698 return RHS;
7699 return QualType();
7700 }
7701
7702 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7703 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7704 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7705 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7706 if (ResQT == LHSBaseQT)
7707 return LHS;
7708 if (ResQT == RHSBaseQT)
7709 return RHS;
7710 }
7711 return QualType();
7712}
7713
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007714//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007715// Integer Predicates
7716//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007717
Jay Foad39c79802011-01-12 09:06:06 +00007718unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007719 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007720 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007721 if (T->isBooleanType())
7722 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007723 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007724 return (unsigned)getTypeSize(T);
7725}
7726
Abramo Bagnara13640492012-09-09 10:21:24 +00007727QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007728 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007729
7730 // Turn <4 x signed int> -> <4 x unsigned int>
7731 if (const VectorType *VTy = T->getAs<VectorType>())
7732 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007733 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007734
7735 // For enums, we return the unsigned version of the base type.
7736 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007737 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007738
7739 const BuiltinType *BTy = T->getAs<BuiltinType>();
7740 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007741 switch (BTy->getKind()) {
7742 case BuiltinType::Char_S:
7743 case BuiltinType::SChar:
7744 return UnsignedCharTy;
7745 case BuiltinType::Short:
7746 return UnsignedShortTy;
7747 case BuiltinType::Int:
7748 return UnsignedIntTy;
7749 case BuiltinType::Long:
7750 return UnsignedLongTy;
7751 case BuiltinType::LongLong:
7752 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007753 case BuiltinType::Int128:
7754 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007755 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007756 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007757 }
7758}
7759
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007760ASTMutationListener::~ASTMutationListener() { }
7761
Richard Smith1fa5d642013-05-11 05:45:24 +00007762void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7763 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007764
7765//===----------------------------------------------------------------------===//
7766// Builtin Type Computation
7767//===----------------------------------------------------------------------===//
7768
7769/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007770/// pointer over the consumed characters. This returns the resultant type. If
7771/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7772/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7773/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007774///
7775/// RequiresICE is filled in on return to indicate whether the value is required
7776/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007777static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007778 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007779 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007780 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007781 // Modifiers.
7782 int HowLong = 0;
7783 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007784 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007785
Chris Lattnerdc226c22010-10-01 22:42:38 +00007786 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007787 bool Done = false;
7788 while (!Done) {
7789 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007790 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007791 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007792 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007793 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007794 case 'S':
7795 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7796 assert(!Signed && "Can't use 'S' modifier multiple times!");
7797 Signed = true;
7798 break;
7799 case 'U':
7800 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007801 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007802 Unsigned = true;
7803 break;
7804 case 'L':
7805 assert(HowLong <= 2 && "Can't have LLLL modifier");
7806 ++HowLong;
7807 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007808 case 'W':
7809 // This modifier represents int64 type.
7810 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7811 switch (Context.getTargetInfo().getInt64Type()) {
7812 default:
7813 llvm_unreachable("Unexpected integer type");
7814 case TargetInfo::SignedLong:
7815 HowLong = 1;
7816 break;
7817 case TargetInfo::SignedLongLong:
7818 HowLong = 2;
7819 break;
7820 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007821 }
7822 }
7823
7824 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007825
Chris Lattnerecd79c62009-06-14 00:45:47 +00007826 // Read the base type.
7827 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007828 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007829 case 'v':
7830 assert(HowLong == 0 && !Signed && !Unsigned &&
7831 "Bad modifiers used with 'v'!");
7832 Type = Context.VoidTy;
7833 break;
Jack Carter24bef982013-08-15 15:16:57 +00007834 case 'h':
7835 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00007836 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00007837 Type = Context.HalfTy;
7838 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007839 case 'f':
7840 assert(HowLong == 0 && !Signed && !Unsigned &&
7841 "Bad modifiers used with 'f'!");
7842 Type = Context.FloatTy;
7843 break;
7844 case 'd':
7845 assert(HowLong < 2 && !Signed && !Unsigned &&
7846 "Bad modifiers used with 'd'!");
7847 if (HowLong)
7848 Type = Context.LongDoubleTy;
7849 else
7850 Type = Context.DoubleTy;
7851 break;
7852 case 's':
7853 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7854 if (Unsigned)
7855 Type = Context.UnsignedShortTy;
7856 else
7857 Type = Context.ShortTy;
7858 break;
7859 case 'i':
7860 if (HowLong == 3)
7861 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7862 else if (HowLong == 2)
7863 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7864 else if (HowLong == 1)
7865 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7866 else
7867 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7868 break;
7869 case 'c':
7870 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7871 if (Signed)
7872 Type = Context.SignedCharTy;
7873 else if (Unsigned)
7874 Type = Context.UnsignedCharTy;
7875 else
7876 Type = Context.CharTy;
7877 break;
7878 case 'b': // boolean
7879 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7880 Type = Context.BoolTy;
7881 break;
7882 case 'z': // size_t.
7883 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7884 Type = Context.getSizeType();
7885 break;
7886 case 'F':
7887 Type = Context.getCFConstantStringType();
7888 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007889 case 'G':
7890 Type = Context.getObjCIdType();
7891 break;
7892 case 'H':
7893 Type = Context.getObjCSelType();
7894 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007895 case 'M':
7896 Type = Context.getObjCSuperType();
7897 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007898 case 'a':
7899 Type = Context.getBuiltinVaListType();
7900 assert(!Type.isNull() && "builtin va list type not initialized!");
7901 break;
7902 case 'A':
7903 // This is a "reference" to a va_list; however, what exactly
7904 // this means depends on how va_list is defined. There are two
7905 // different kinds of va_list: ones passed by value, and ones
7906 // passed by reference. An example of a by-value va_list is
7907 // x86, where va_list is a char*. An example of by-ref va_list
7908 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7909 // we want this argument to be a char*&; for x86-64, we want
7910 // it to be a __va_list_tag*.
7911 Type = Context.getBuiltinVaListType();
7912 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007913 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007914 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007915 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007916 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007917 break;
7918 case 'V': {
7919 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007920 unsigned NumElements = strtoul(Str, &End, 10);
7921 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007922 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007923
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007924 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7925 RequiresICE, false);
7926 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007927
7928 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007929 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007930 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007931 break;
7932 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007933 case 'E': {
7934 char *End;
7935
7936 unsigned NumElements = strtoul(Str, &End, 10);
7937 assert(End != Str && "Missing vector size");
7938
7939 Str = End;
7940
7941 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7942 false);
7943 Type = Context.getExtVectorType(ElementType, NumElements);
7944 break;
7945 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007946 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007947 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7948 false);
7949 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007950 Type = Context.getComplexType(ElementType);
7951 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007952 }
7953 case 'Y' : {
7954 Type = Context.getPointerDiffType();
7955 break;
7956 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007957 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007958 Type = Context.getFILEType();
7959 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007960 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007961 return QualType();
7962 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007963 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007964 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007965 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007966 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007967 else
7968 Type = Context.getjmp_bufType();
7969
Mike Stump2adb4da2009-07-28 23:47:15 +00007970 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007971 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007972 return QualType();
7973 }
7974 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007975 case 'K':
7976 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7977 Type = Context.getucontext_tType();
7978
7979 if (Type.isNull()) {
7980 Error = ASTContext::GE_Missing_ucontext;
7981 return QualType();
7982 }
7983 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007984 case 'p':
7985 Type = Context.getProcessIDType();
7986 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007987 }
Mike Stump11289f42009-09-09 15:08:12 +00007988
Chris Lattnerdc226c22010-10-01 22:42:38 +00007989 // If there are modifiers and if we're allowed to parse them, go for it.
7990 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007991 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007992 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007993 default: Done = true; --Str; break;
7994 case '*':
7995 case '&': {
7996 // Both pointers and references can have their pointee types
7997 // qualified with an address space.
7998 char *End;
7999 unsigned AddrSpace = strtoul(Str, &End, 10);
8000 if (End != Str && AddrSpace != 0) {
8001 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8002 Str = End;
8003 }
8004 if (c == '*')
8005 Type = Context.getPointerType(Type);
8006 else
8007 Type = Context.getLValueReferenceType(Type);
8008 break;
8009 }
8010 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8011 case 'C':
8012 Type = Type.withConst();
8013 break;
8014 case 'D':
8015 Type = Context.getVolatileType(Type);
8016 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008017 case 'R':
8018 Type = Type.withRestrict();
8019 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008020 }
8021 }
Chris Lattner84733392010-10-01 07:13:18 +00008022
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008023 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008024 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008025
Chris Lattnerecd79c62009-06-14 00:45:47 +00008026 return Type;
8027}
8028
8029/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008030QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008031 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008032 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008033 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008034
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008035 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008036
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008037 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008038 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008039 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8040 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008041 if (Error != GE_None)
8042 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008043
8044 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8045
Chris Lattnerecd79c62009-06-14 00:45:47 +00008046 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008047 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008048 if (Error != GE_None)
8049 return QualType();
8050
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008051 // If this argument is required to be an IntegerConstantExpression and the
8052 // caller cares, fill in the bitmask we return.
8053 if (RequiresICE && IntegerConstantArgs)
8054 *IntegerConstantArgs |= 1 << ArgTypes.size();
8055
Chris Lattnerecd79c62009-06-14 00:45:47 +00008056 // Do array -> pointer decay. The builtin should use the decayed type.
8057 if (Ty->isArrayType())
8058 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008059
Chris Lattnerecd79c62009-06-14 00:45:47 +00008060 ArgTypes.push_back(Ty);
8061 }
8062
David Majnemerba3e5ec2015-03-13 18:26:17 +00008063 if (Id == Builtin::BI__GetExceptionInfo)
8064 return QualType();
8065
Chris Lattnerecd79c62009-06-14 00:45:47 +00008066 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8067 "'.' should only occur at end of builtin type list!");
8068
Reid Kleckner78af0702013-08-27 23:08:25 +00008069 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008070 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8071
8072 bool Variadic = (TypeStr[0] == '.');
8073
8074 // We really shouldn't be making a no-proto type here, especially in C++.
8075 if (ArgTypes.empty() && Variadic)
8076 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008077
John McCalldb40c7f2010-12-14 08:05:40 +00008078 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008079 EPI.ExtInfo = EI;
8080 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008081
Jordan Rose5c382722013-03-08 21:51:21 +00008082 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008083}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008084
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008085static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8086 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008087 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008088 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008089
Rafael Espindola3ae00052013-05-13 00:12:11 +00008090 GVALinkage External = GVA_StrongExternal;
8091 switch (FD->getTemplateSpecializationKind()) {
8092 case TSK_Undeclared:
8093 case TSK_ExplicitSpecialization:
8094 External = GVA_StrongExternal;
8095 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008096
Rafael Espindola3ae00052013-05-13 00:12:11 +00008097 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008098 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008099
David Majnemerc3d07332014-05-15 06:25:57 +00008100 // C++11 [temp.explicit]p10:
8101 // [ Note: The intent is that an inline function that is the subject of
8102 // an explicit instantiation declaration will still be implicitly
8103 // instantiated when used so that the body can be considered for
8104 // inlining, but that no out-of-line copy of the inline function would be
8105 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008106 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008107 return GVA_AvailableExternally;
8108
Rafael Espindola3ae00052013-05-13 00:12:11 +00008109 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008110 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008111 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008112 }
8113
8114 if (!FD->isInlined())
8115 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008116
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008117 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
8118 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008119 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008120 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8121
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008122 // GNU or C99 inline semantics. Determine whether this symbol should be
8123 // externally visible.
8124 if (FD->isInlineDefinitionExternallyVisible())
8125 return External;
8126
8127 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008128 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008129 }
8130
David Majnemer54e3ba52014-04-02 23:17:29 +00008131 // Functions specified with extern and inline in -fms-compatibility mode
8132 // forcibly get emitted. While the body of the function cannot be later
8133 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008134 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008135 return GVA_StrongODR;
8136
David Majnemer27d69db2014-04-28 22:17:59 +00008137 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008138}
8139
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008140static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
8141 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8142 // dllexport/dllimport on inline functions.
8143 if (D->hasAttr<DLLImportAttr>()) {
8144 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8145 return GVA_AvailableExternally;
8146 } else if (D->hasAttr<DLLExportAttr>()) {
8147 if (L == GVA_DiscardableODR)
8148 return GVA_StrongODR;
8149 }
8150 return L;
8151}
8152
8153GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8154 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
8155 FD);
8156}
8157
8158static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8159 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008160 if (!VD->isExternallyVisible())
8161 return GVA_Internal;
8162
David Majnemer27d69db2014-04-28 22:17:59 +00008163 if (VD->isStaticLocal()) {
8164 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8165 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8166 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8167 LexicalContext = LexicalContext->getLexicalParent();
8168
Richard Smith9e2341d2015-03-23 03:25:59 +00008169 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008170 // enclosing function.
8171 if (LexicalContext)
8172 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008173 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008174
8175 // GVA_StrongODR function linkage is stronger than what we need,
8176 // downgrade to GVA_DiscardableODR.
8177 // This allows us to discard the variable if we never end up needing it.
8178 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8179 : StaticLocalLinkage;
8180 }
8181
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008182 // MSVC treats in-class initialized static data members as definitions.
8183 // By giving them non-strong linkage, out-of-line definitions won't
8184 // cause link errors.
8185 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8186 return GVA_DiscardableODR;
8187
Richard Smith8809a0c2013-09-27 20:14:12 +00008188 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008189 case TSK_Undeclared:
8190 case TSK_ExplicitSpecialization:
8191 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008192
Rafael Espindola3ae00052013-05-13 00:12:11 +00008193 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008194 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008195
David Majnemer27d69db2014-04-28 22:17:59 +00008196 case TSK_ExplicitInstantiationDeclaration:
8197 return GVA_AvailableExternally;
8198
Rafael Espindola3ae00052013-05-13 00:12:11 +00008199 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008200 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008201 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008202
8203 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008204}
8205
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008206GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8207 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
8208 VD);
8209}
8210
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008211bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008212 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8213 if (!VD->isFileVarDecl())
8214 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008215 // Global named register variables (GNU extension) are never emitted.
8216 if (VD->getStorageClass() == SC_Register)
8217 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008218 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8219 // We never need to emit an uninstantiated function template.
8220 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8221 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008222 } else if (isa<OMPThreadPrivateDecl>(D))
8223 return true;
8224 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008225 return false;
8226
8227 // If this is a member of a class template, we do not need to emit it.
8228 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008229 return false;
8230
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008231 // Weak references don't produce any output by themselves.
8232 if (D->hasAttr<WeakRefAttr>())
8233 return false;
8234
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008235 // Aliases and used decls are required.
8236 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8237 return true;
8238
8239 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8240 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008241 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008242 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008243
8244 // Constructors and destructors are required.
8245 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8246 return true;
8247
John McCall6bd2a892013-01-25 22:31:03 +00008248 // The key function for a class is required. This rule only comes
8249 // into play when inline functions can be key functions, though.
8250 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8251 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8252 const CXXRecordDecl *RD = MD->getParent();
8253 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8254 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8255 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8256 return true;
8257 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008258 }
8259 }
8260
8261 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8262
8263 // static, static inline, always_inline, and extern inline functions can
8264 // always be deferred. Normal inline functions can be deferred in C99/C++.
8265 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008266 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8267 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008268 return false;
8269 return true;
8270 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008271
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008272 const VarDecl *VD = cast<VarDecl>(D);
8273 assert(VD->isFileVarDecl() && "Expected file scoped var");
8274
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008275 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8276 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008277 return false;
8278
Richard Smitha0e5e542012-11-12 21:38:00 +00008279 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008280 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008281 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8282 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008283 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008284
Richard Smitha0e5e542012-11-12 21:38:00 +00008285 // Variables that have destruction with side-effects are required.
8286 if (VD->getType().isDestructedType())
8287 return true;
8288
8289 // Variables that have initialization with side-effects are required.
8290 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
8291 return true;
8292
8293 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008294}
Charles Davis53c59df2010-08-16 03:33:14 +00008295
Reid Kleckner78af0702013-08-27 23:08:25 +00008296CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8297 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008298 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008299 if (IsCXXMethod)
8300 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008301
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008302 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8303
8304 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008305}
8306
Jay Foad39c79802011-01-12 09:06:06 +00008307bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008308 // Pass through to the C++ ABI object
8309 return ABI->isNearlyEmpty(RD);
8310}
8311
Reid Kleckner96f8f932014-02-05 17:27:08 +00008312VTableContextBase *ASTContext::getVTableContext() {
8313 if (!VTContext.get()) {
8314 if (Target->getCXXABI().isMicrosoft())
8315 VTContext.reset(new MicrosoftVTableContext(*this));
8316 else
8317 VTContext.reset(new ItaniumVTableContext(*this));
8318 }
8319 return VTContext.get();
8320}
8321
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008322MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008323 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008324 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008325 case TargetCXXABI::GenericItanium:
8326 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008327 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008328 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008329 case TargetCXXABI::iOS64:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008330 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008331 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008332 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008333 }
David Blaikie83d382b2011-09-23 05:06:16 +00008334 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008335}
8336
Charles Davis53c59df2010-08-16 03:33:14 +00008337CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008338
8339size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008340 return ASTRecordLayouts.getMemorySize() +
8341 llvm::capacity_in_bytes(ObjCLayouts) +
8342 llvm::capacity_in_bytes(KeyFunctions) +
8343 llvm::capacity_in_bytes(ObjCImpls) +
8344 llvm::capacity_in_bytes(BlockVarCopyInits) +
8345 llvm::capacity_in_bytes(DeclAttrs) +
8346 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8347 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8348 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8349 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8350 llvm::capacity_in_bytes(OverriddenMethods) +
8351 llvm::capacity_in_bytes(Types) +
8352 llvm::capacity_in_bytes(VariableArrayTypes) +
8353 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008354}
Ted Kremenek540017e2011-10-06 05:00:56 +00008355
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008356/// getIntTypeForBitwidth -
8357/// sets integer QualTy according to specified details:
8358/// bitwidth, signed/unsigned.
8359/// Returns empty type if there is no appropriate target types.
8360QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8361 unsigned Signed) const {
8362 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8363 CanQualType QualTy = getFromTargetType(Ty);
8364 if (!QualTy && DestWidth == 128)
8365 return Signed ? Int128Ty : UnsignedInt128Ty;
8366 return QualTy;
8367}
8368
8369/// getRealTypeForBitwidth -
8370/// sets floating point QualTy according to specified bitwidth.
8371/// Returns empty type if there is no appropriate target types.
8372QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8373 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8374 switch (Ty) {
8375 case TargetInfo::Float:
8376 return FloatTy;
8377 case TargetInfo::Double:
8378 return DoubleTy;
8379 case TargetInfo::LongDouble:
8380 return LongDoubleTy;
8381 case TargetInfo::NoFloat:
8382 return QualType();
8383 }
8384
8385 llvm_unreachable("Unhandled TargetInfo::RealType value");
8386}
8387
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008388void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8389 if (Number > 1)
8390 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008391}
8392
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008393unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8394 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8395 MangleNumbers.find(ND);
8396 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008397}
8398
David Majnemer2206bf52014-03-05 08:57:59 +00008399void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8400 if (Number > 1)
8401 StaticLocalNumbers[VD] = Number;
8402}
8403
8404unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8405 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8406 StaticLocalNumbers.find(VD);
8407 return I != StaticLocalNumbers.end() ? I->second : 1;
8408}
8409
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008410MangleNumberingContext &
8411ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008412 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8413 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8414 if (!MCtx)
8415 MCtx = createMangleNumberingContext();
8416 return *MCtx;
8417}
8418
8419MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8420 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008421}
8422
David Majnemere7a818f2015-03-06 18:53:55 +00008423const CXXConstructorDecl *
8424ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8425 return ABI->getCopyConstructorForExceptionObject(
8426 cast<CXXRecordDecl>(RD->getFirstDecl()));
8427}
8428
8429void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8430 CXXConstructorDecl *CD) {
8431 return ABI->addCopyConstructorForExceptionObject(
8432 cast<CXXRecordDecl>(RD->getFirstDecl()),
8433 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8434}
8435
David Majnemerdfa6d202015-03-11 18:36:39 +00008436void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8437 unsigned ParmIdx, Expr *DAE) {
8438 ABI->addDefaultArgExprForConstructor(
8439 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8440}
8441
8442Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8443 unsigned ParmIdx) {
8444 return ABI->getDefaultArgExprForConstructor(
8445 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8446}
8447
Ted Kremenek540017e2011-10-06 05:00:56 +00008448void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8449 ParamIndices[D] = index;
8450}
8451
8452unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8453 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8454 assert(I != ParamIndices.end() &&
8455 "ParmIndices lacks entry set by ParmVarDecl");
8456 return I->second;
8457}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008458
Richard Smithe6c01442013-06-05 00:46:14 +00008459APValue *
8460ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8461 bool MayCreate) {
8462 assert(E && E->getStorageDuration() == SD_Static &&
8463 "don't need to cache the computed value for this temporary");
8464 if (MayCreate)
8465 return &MaterializedTemporaryValues[E];
8466
8467 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8468 MaterializedTemporaryValues.find(E);
Craig Topper36250ad2014-05-12 05:36:57 +00008469 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
Richard Smithe6c01442013-06-05 00:46:14 +00008470}
8471
Fariborz Jahanian615de762013-05-28 17:37:39 +00008472bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8473 const llvm::Triple &T = getTargetInfo().getTriple();
8474 if (!T.isOSDarwin())
8475 return false;
8476
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008477 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8478 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8479 return false;
8480
Fariborz Jahanian615de762013-05-28 17:37:39 +00008481 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8482 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8483 uint64_t Size = sizeChars.getQuantity();
8484 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8485 unsigned Align = alignChars.getQuantity();
8486 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8487 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8488}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008489
8490namespace {
8491
8492 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8493 /// parents as defined by the \c RecursiveASTVisitor.
8494 ///
8495 /// Note that the relationship described here is purely in terms of AST
8496 /// traversal - there are other relationships (for example declaration context)
8497 /// in the AST that are better modeled by special matchers.
8498 ///
8499 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8500 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8501
8502 public:
8503 /// \brief Builds and returns the translation unit's parent map.
8504 ///
8505 /// The caller takes ownership of the returned \c ParentMap.
8506 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8507 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8508 Visitor.TraverseDecl(&TU);
8509 return Visitor.Parents;
8510 }
8511
8512 private:
8513 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8514
8515 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8516 }
8517
8518 bool shouldVisitTemplateInstantiations() const {
8519 return true;
8520 }
8521 bool shouldVisitImplicitCode() const {
8522 return true;
8523 }
8524 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8525 // are not triggered during data recursion.
8526 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8527 return false;
8528 }
8529
8530 template <typename T>
8531 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008532 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008533 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008534 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008535 // FIXME: Currently we add the same parent multiple times, but only
8536 // when no memoization data is available for the type.
8537 // For example when we visit all subexpressions of template
8538 // instantiations; this is suboptimal, but benign: the only way to
8539 // visit those is with hasAncestor / hasParent, and those do not create
8540 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008541 // The plan is to enable DynTypedNode to be storable in a map or hash
8542 // map. The main problem there is to implement hash functions /
8543 // comparison operators for all types that DynTypedNode supports that
8544 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008545 auto &NodeOrVector = (*Parents)[Node];
8546 if (NodeOrVector.isNull()) {
8547 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008548 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008549 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8550 auto *Node =
8551 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8552 auto *Vector = new ASTContext::ParentVector(1, *Node);
8553 NodeOrVector = Vector;
8554 delete Node;
8555 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008556 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008557
8558 auto *Vector =
8559 NodeOrVector.template get<ASTContext::ParentVector *>();
8560 // Skip duplicates for types that have memoization data.
8561 // We must check that the type has memoization data before calling
8562 // std::find() because DynTypedNode::operator== can't compare all
8563 // types.
8564 bool Found = ParentStack.back().getMemoizationData() &&
8565 std::find(Vector->begin(), Vector->end(),
8566 ParentStack.back()) != Vector->end();
8567 if (!Found)
8568 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008569 }
8570 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008571 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8572 bool Result = (this ->* traverse) (Node);
8573 ParentStack.pop_back();
8574 return Result;
8575 }
8576
8577 bool TraverseDecl(Decl *DeclNode) {
8578 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8579 }
8580
8581 bool TraverseStmt(Stmt *StmtNode) {
8582 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8583 }
8584
8585 ASTContext::ParentMap *Parents;
8586 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8587
8588 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8589 };
8590
8591} // end namespace
8592
Benjamin Kramer07935292014-10-04 17:01:26 +00008593ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008594ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8595 assert(Node.getMemoizationData() &&
8596 "Invariant broken: only nodes that support memoization may be "
8597 "used in the parent map.");
8598 if (!AllParents) {
8599 // We always need to run over the whole translation unit, as
8600 // hasAncestor can escape any subtree.
8601 AllParents.reset(
8602 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8603 }
8604 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8605 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008606 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008607 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008608 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8609 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008610 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008611 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008612}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008613
8614bool
8615ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8616 const ObjCMethodDecl *MethodImpl) {
8617 // No point trying to match an unavailable/deprecated mothod.
8618 if (MethodDecl->hasAttr<UnavailableAttr>()
8619 || MethodDecl->hasAttr<DeprecatedAttr>())
8620 return false;
8621 if (MethodDecl->getObjCDeclQualifier() !=
8622 MethodImpl->getObjCDeclQualifier())
8623 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008624 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008625 return false;
8626
8627 if (MethodDecl->param_size() != MethodImpl->param_size())
8628 return false;
8629
8630 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8631 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8632 EF = MethodDecl->param_end();
8633 IM != EM && IF != EF; ++IM, ++IF) {
8634 const ParmVarDecl *DeclVar = (*IF);
8635 const ParmVarDecl *ImplVar = (*IM);
8636 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8637 return false;
8638 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8639 return false;
8640 }
8641 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8642
8643}
Richard Smith053f6c62014-05-16 23:01:30 +00008644
8645// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8646// doesn't include ASTContext.h
8647template
8648clang::LazyGenerationalUpdatePtr<
8649 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8650clang::LazyGenerationalUpdatePtr<
8651 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8652 const clang::ASTContext &Ctx, Decl *Value);