blob: 47d0107a66de8ffa3571139e4553c57415de848b [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:
Dan Gohmanc2853072015-09-03 22:51:53 +0000687 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000688 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000689 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000690 return CreateMicrosoftCXXABI(*this);
691 }
David Blaikie8a40f702012-01-17 06:56:22 +0000692 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000693}
694
Douglas Gregore8bbc122011-09-02 00:18:52 +0000695static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000696 const LangOptions &LOpts) {
697 if (LOpts.FakeAddressSpaceMap) {
698 // The fake address space map must have a distinct entry for each
699 // language-specific address space.
700 static const unsigned FakeAddrSpaceMap[] = {
701 1, // opencl_global
702 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000703 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000704 4, // opencl_generic
705 5, // cuda_device
706 6, // cuda_constant
707 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000708 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000709 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000710 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000711 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000712 }
713}
714
David Tweed31d09b02013-09-13 12:04:22 +0000715static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
716 const LangOptions &LangOpts) {
717 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000718 case LangOptions::ASMM_Target:
719 return TI.useAddressSpaceMapMangling();
720 case LangOptions::ASMM_On:
721 return true;
722 case LangOptions::ASMM_Off:
723 return false;
724 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000725 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000726}
727
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000728ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000729 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000730 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000731 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
732 DependentTemplateSpecializationTypes(this_()),
733 SubstTemplateTemplateParmPacks(this_()),
734 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
735 UInt128Decl(nullptr), Float128StubDecl(nullptr),
Charles Davisc7d5c942015-09-17 20:55:33 +0000736 BuiltinVaListDecl(nullptr), BuiltinMSVaListDecl(nullptr),
737 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
738 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000739 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
740 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
741 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
742 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Richard Smithf19e1272015-03-07 00:04:49 +0000743 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
744 SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000745 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000746 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
747 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
748 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
749 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000750 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000751 TUDecl = TranslationUnitDecl::Create(*this);
752}
753
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000754ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000755 ReleaseParentMapEntries();
756
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000757 // Release the DenseMaps associated with DeclContext objects.
758 // FIXME: Is this the ideal solution?
759 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000760
Manuel Klimeka7328992013-06-03 13:51:33 +0000761 // Call all of the deallocation functions on all of their targets.
762 for (DeallocationMap::const_iterator I = Deallocations.begin(),
763 E = Deallocations.end(); I != E; ++I)
764 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
765 (I->first)((I->second)[J]);
766
Ted Kremenek076baeb2010-06-08 23:00:58 +0000767 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000768 // because they can contain DenseMaps.
769 for (llvm::DenseMap<const ObjCContainerDecl*,
770 const ASTRecordLayout*>::iterator
771 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
772 // Increment in loop to prevent using deallocated memory.
773 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
774 R->Destroy(*this);
775
Ted Kremenek076baeb2010-06-08 23:00:58 +0000776 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
777 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
778 // Increment in loop to prevent using deallocated memory.
779 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
780 R->Destroy(*this);
781 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000782
783 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
784 AEnd = DeclAttrs.end();
785 A != AEnd; ++A)
786 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000787
David Majnemere694f3e2015-08-14 14:43:50 +0000788 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
789 MaterializedTemporaryValues)
790 MTVPair.second->~APValue();
791
Reid Kleckner588c9372014-02-19 23:44:52 +0000792 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000793}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000794
Manuel Klimek95403e62014-05-21 13:28:59 +0000795void ASTContext::ReleaseParentMapEntries() {
796 if (!AllParents) return;
797 for (const auto &Entry : *AllParents) {
798 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
799 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
800 } else {
801 assert(Entry.second.is<ParentVector *>());
802 delete Entry.second.get<ParentVector *>();
803 }
804 }
805}
806
Douglas Gregor1a809332010-05-23 18:26:36 +0000807void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000808 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000809}
810
Mike Stump11289f42009-09-09 15:08:12 +0000811void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000812ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
813 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000814}
815
Chris Lattner4eb445d2007-01-26 01:27:23 +0000816void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000817 llvm::errs() << "\n*** AST Context Stats:\n";
818 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000819
Douglas Gregora30d0462009-05-26 14:40:08 +0000820 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000821#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000822#define ABSTRACT_TYPE(Name, Parent)
823#include "clang/AST/TypeNodes.def"
824 0 // Extra
825 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000826
Chris Lattner4eb445d2007-01-26 01:27:23 +0000827 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
828 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000829 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000830 }
831
Douglas Gregora30d0462009-05-26 14:40:08 +0000832 unsigned Idx = 0;
833 unsigned TotalBytes = 0;
834#define TYPE(Name, Parent) \
835 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000836 llvm::errs() << " " << counts[Idx] << " " << #Name \
837 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000838 TotalBytes += counts[Idx] * sizeof(Name##Type); \
839 ++Idx;
840#define ABSTRACT_TYPE(Name, Parent)
841#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000842
Chandler Carruth3c147a72011-07-04 05:32:14 +0000843 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
844
Douglas Gregor7454c562010-07-02 20:37:36 +0000845 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000846 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
847 << NumImplicitDefaultConstructors
848 << " implicit default constructors created\n";
849 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
850 << NumImplicitCopyConstructors
851 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000852 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
854 << NumImplicitMoveConstructors
855 << " implicit move constructors created\n";
856 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
857 << NumImplicitCopyAssignmentOperators
858 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000859 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000860 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
861 << NumImplicitMoveAssignmentOperators
862 << " implicit move assignment operators created\n";
863 llvm::errs() << NumImplicitDestructorsDeclared << "/"
864 << NumImplicitDestructors
865 << " implicit destructors created\n";
866
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000867 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000868 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000869 ExternalSource->PrintStats();
870 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000871
Douglas Gregor5b11d492010-07-25 17:53:33 +0000872 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000873}
874
Richard Smith42413142015-05-15 20:05:43 +0000875void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
876 bool NotifyListeners) {
877 if (NotifyListeners)
878 if (auto *Listener = getASTMutationListener())
879 Listener->RedefinedHiddenDefinition(ND, M);
880
881 if (getLangOpts().ModulesLocalVisibility)
882 MergedDefModules[ND].push_back(M);
883 else
884 ND->setHidden(false);
885}
886
887void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
888 auto It = MergedDefModules.find(ND);
889 if (It == MergedDefModules.end())
890 return;
891
892 auto &Merged = It->second;
893 llvm::DenseSet<Module*> Found;
894 for (Module *&M : Merged)
895 if (!Found.insert(M).second)
896 M = nullptr;
897 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
898}
899
Richard Smithf19e1272015-03-07 00:04:49 +0000900ExternCContextDecl *ASTContext::getExternCContextDecl() const {
901 if (!ExternCContext)
902 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
903
904 return ExternCContext;
905}
906
Alp Toker2dea15b2013-12-17 01:22:38 +0000907RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
908 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000909 SourceLocation Loc;
910 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000911 if (getLangOpts().CPlusPlus)
912 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
913 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000914 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000915 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
916 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000917 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000918 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
919 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000920 return NewDecl;
921}
922
923TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
924 StringRef Name) const {
925 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
926 TypedefDecl *NewDecl = TypedefDecl::Create(
927 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
928 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
929 NewDecl->setImplicit();
930 return NewDecl;
931}
932
Douglas Gregor801c99d2011-08-12 06:49:56 +0000933TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000934 if (!Int128Decl)
935 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000936 return Int128Decl;
937}
938
939TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000940 if (!UInt128Decl)
941 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000942 return UInt128Decl;
943}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000944
Nico Webere1687c52013-06-20 21:44:55 +0000945TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000946 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000947 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000948 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000949
Nico Webere1687c52013-06-20 21:44:55 +0000950 return Float128StubDecl;
951}
952
John McCall48f2d582009-10-23 23:03:21 +0000953void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000954 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000955 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000956 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000957}
958
Artem Belevichb5bc9232015-09-22 17:23:22 +0000959void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
960 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000961 assert((!this->Target || this->Target == &Target) &&
962 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000963 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000964
Douglas Gregore8bbc122011-09-02 00:18:52 +0000965 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000966 this->AuxTarget = AuxTarget;
967
Douglas Gregore8bbc122011-09-02 00:18:52 +0000968 ABI.reset(createCXXABI(Target));
969 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000970 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000971
Chris Lattner970e54e2006-11-12 00:37:36 +0000972 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000973 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000974
Chris Lattner970e54e2006-11-12 00:37:36 +0000975 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000976 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000977 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000978 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000979 InitBuiltinType(CharTy, BuiltinType::Char_S);
980 else
981 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000982 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000983 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
984 InitBuiltinType(ShortTy, BuiltinType::Short);
985 InitBuiltinType(IntTy, BuiltinType::Int);
986 InitBuiltinType(LongTy, BuiltinType::Long);
987 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000988
Chris Lattner970e54e2006-11-12 00:37:36 +0000989 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000990 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
991 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
992 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
993 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
994 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000995
Chris Lattner970e54e2006-11-12 00:37:36 +0000996 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000997 InitBuiltinType(FloatTy, BuiltinType::Float);
998 InitBuiltinType(DoubleTy, BuiltinType::Double);
999 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001000
Chris Lattnerf122cef2009-04-30 02:43:43 +00001001 // GNU extension, 128-bit integers.
1002 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1003 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1004
Hans Wennborg0d81e012013-05-10 10:08:40 +00001005 // C++ 3.9.1p5
1006 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1007 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1008 else // -fshort-wchar makes wchar_t be unsigned.
1009 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1010 if (LangOpts.CPlusPlus && LangOpts.WChar)
1011 WideCharTy = WCharTy;
1012 else {
1013 // C99 (or C++ using -fno-wchar).
1014 WideCharTy = getFromTargetType(Target.getWCharType());
1015 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001016
James Molloy36365542012-05-04 10:55:22 +00001017 WIntTy = getFromTargetType(Target.getWIntType());
1018
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001019 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1020 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1021 else // C99
1022 Char16Ty = getFromTargetType(Target.getChar16Type());
1023
1024 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1025 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1026 else // C99
1027 Char32Ty = getFromTargetType(Target.getChar32Type());
1028
Douglas Gregor4619e432008-12-05 23:32:09 +00001029 // Placeholder type for type-dependent expressions whose type is
1030 // completely unknown. No code should ever check a type against
1031 // DependentTy and users should never see it; however, it is here to
1032 // help diagnose failures to properly check for type-dependent
1033 // expressions.
1034 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001035
John McCall36e7fe32010-10-12 00:20:44 +00001036 // Placeholder type for functions.
1037 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1038
John McCall0009fcc2011-04-26 20:42:42 +00001039 // Placeholder type for bound members.
1040 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1041
John McCall526ab472011-10-25 17:37:35 +00001042 // Placeholder type for pseudo-objects.
1043 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1044
John McCall31996342011-04-07 08:22:57 +00001045 // "any" type; useful for debugger-like clients.
1046 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1047
John McCall8a6b59a2011-10-17 18:09:15 +00001048 // Placeholder type for unbridged ARC casts.
1049 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1050
Eli Friedman34866c72012-08-31 00:14:07 +00001051 // Placeholder type for builtin functions.
1052 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1053
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001054 // Placeholder type for OMP array sections.
1055 if (LangOpts.OpenMP)
1056 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1057
Chris Lattner970e54e2006-11-12 00:37:36 +00001058 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001059 FloatComplexTy = getComplexType(FloatTy);
1060 DoubleComplexTy = getComplexType(DoubleTy);
1061 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001063 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001064 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1065 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001066 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001067
1068 if (LangOpts.OpenCL) {
1069 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1070 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1071 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1072 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1073 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001074 InitBuiltinType(OCLImage2dDepthTy, BuiltinType::OCLImage2dDepth);
1075 InitBuiltinType(OCLImage2dArrayDepthTy, BuiltinType::OCLImage2dArrayDepth);
1076 InitBuiltinType(OCLImage2dMSAATy, BuiltinType::OCLImage2dMSAA);
1077 InitBuiltinType(OCLImage2dArrayMSAATy, BuiltinType::OCLImage2dArrayMSAA);
1078 InitBuiltinType(OCLImage2dMSAADepthTy, BuiltinType::OCLImage2dMSAADepth);
1079 InitBuiltinType(OCLImage2dArrayMSAADepthTy,
1080 BuiltinType::OCLImage2dArrayMSAADepth);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001081 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001082
Guy Benyei61054192013-02-07 10:55:47 +00001083 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001084 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001085 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1086 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1087 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1088 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001089 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001090
1091 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001092 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1093 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001094
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001095 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001096
1097 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001098
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001099 // void * type
1100 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001101
1102 // nullptr type (C++0x 2.14.7)
1103 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001104
1105 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1106 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001107
1108 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001109 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001110}
1111
David Blaikie9c902b52011-09-25 23:23:43 +00001112DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001113 return SourceMgr.getDiagnostics();
1114}
1115
Douglas Gregor561eceb2010-08-30 16:49:28 +00001116AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1117 AttrVec *&Result = DeclAttrs[D];
1118 if (!Result) {
1119 void *Mem = Allocate(sizeof(AttrVec));
1120 Result = new (Mem) AttrVec;
1121 }
1122
1123 return *Result;
1124}
1125
1126/// \brief Erase the attributes corresponding to the given declaration.
1127void ASTContext::eraseDeclAttrs(const Decl *D) {
1128 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1129 if (Pos != DeclAttrs.end()) {
1130 Pos->second->~AttrVec();
1131 DeclAttrs.erase(Pos);
1132 }
1133}
1134
Larisse Voufo39a1e502013-08-06 01:03:05 +00001135// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001136MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001137ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001138 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001139 return getTemplateOrSpecializationInfo(Var)
1140 .dyn_cast<MemberSpecializationInfo *>();
1141}
1142
1143ASTContext::TemplateOrSpecializationInfo
1144ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1145 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1146 TemplateOrInstantiation.find(Var);
1147 if (Pos == TemplateOrInstantiation.end())
1148 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001149
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001150 return Pos->second;
1151}
1152
Mike Stump11289f42009-09-09 15:08:12 +00001153void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001154ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001155 TemplateSpecializationKind TSK,
1156 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001157 assert(Inst->isStaticDataMember() && "Not a static data member");
1158 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001159 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1160 Tmpl, TSK, PointOfInstantiation));
1161}
1162
1163void
1164ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1165 TemplateOrSpecializationInfo TSI) {
1166 assert(!TemplateOrInstantiation[Inst] &&
1167 "Already noted what the variable was instantiated from");
1168 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001169}
1170
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001171FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1172 const FunctionDecl *FD){
1173 assert(FD && "Specialization is 0");
1174 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001175 = ClassScopeSpecializationPattern.find(FD);
1176 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001177 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001178
1179 return Pos->second;
1180}
1181
1182void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1183 FunctionDecl *Pattern) {
1184 assert(FD && "Specialization is 0");
1185 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001186 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001187}
1188
John McCalle61f2ba2009-11-18 02:36:19 +00001189NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001190ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001191 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001192 = InstantiatedFromUsingDecl.find(UUD);
1193 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001194 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001195
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001196 return Pos->second;
1197}
1198
1199void
John McCallb96ec562009-12-04 22:46:56 +00001200ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1201 assert((isa<UsingDecl>(Pattern) ||
1202 isa<UnresolvedUsingValueDecl>(Pattern) ||
1203 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1204 "pattern decl is not a using decl");
1205 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1206 InstantiatedFromUsingDecl[Inst] = Pattern;
1207}
1208
1209UsingShadowDecl *
1210ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1211 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1212 = InstantiatedFromUsingShadowDecl.find(Inst);
1213 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001214 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001215
1216 return Pos->second;
1217}
1218
1219void
1220ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1221 UsingShadowDecl *Pattern) {
1222 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1223 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001224}
1225
Anders Carlsson5da84842009-09-01 04:26:58 +00001226FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1227 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1228 = InstantiatedFromUnnamedFieldDecl.find(Field);
1229 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001230 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001231
Anders Carlsson5da84842009-09-01 04:26:58 +00001232 return Pos->second;
1233}
1234
1235void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1236 FieldDecl *Tmpl) {
1237 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1238 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1239 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1240 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001241
Anders Carlsson5da84842009-09-01 04:26:58 +00001242 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1243}
1244
Douglas Gregor832940b2010-03-02 23:58:15 +00001245ASTContext::overridden_cxx_method_iterator
1246ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1247 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001248 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001249 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001250 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001251
1252 return Pos->second.begin();
1253}
1254
1255ASTContext::overridden_cxx_method_iterator
1256ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1257 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001258 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001259 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001260 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001261
1262 return Pos->second.end();
1263}
1264
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001265unsigned
1266ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1267 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001268 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001269 if (Pos == OverriddenMethods.end())
1270 return 0;
1271
1272 return Pos->second.size();
1273}
1274
Douglas Gregor832940b2010-03-02 23:58:15 +00001275void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1276 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001277 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001278 OverriddenMethods[Method].push_back(Overridden);
1279}
1280
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001281void ASTContext::getOverriddenMethods(
1282 const NamedDecl *D,
1283 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001284 assert(D);
1285
1286 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001287 Overridden.append(overridden_methods_begin(CXXMethod),
1288 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001289 return;
1290 }
1291
1292 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1293 if (!Method)
1294 return;
1295
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001296 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1297 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001298 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001299}
1300
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001301void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1302 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1303 assert(!Import->isFromASTFile() && "Non-local import declaration");
1304 if (!FirstLocalImport) {
1305 FirstLocalImport = Import;
1306 LastLocalImport = Import;
1307 return;
1308 }
1309
1310 LastLocalImport->NextLocalImport = Import;
1311 LastLocalImport = Import;
1312}
1313
Chris Lattner53cfe802007-07-18 17:52:12 +00001314//===----------------------------------------------------------------------===//
1315// Type Sizing and Analysis
1316//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001317
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001318/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1319/// scalar floating point type.
1320const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001321 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001322 assert(BT && "Not a floating point type!");
1323 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001324 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001325 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001326 case BuiltinType::Float: return Target->getFloatFormat();
1327 case BuiltinType::Double: return Target->getDoubleFormat();
1328 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001329 }
1330}
1331
Rafael Espindola71eccb32013-08-08 19:53:46 +00001332CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001333 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001334
John McCall94268702010-10-08 18:24:19 +00001335 bool UseAlignAttrOnly = false;
1336 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1337 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001338
John McCall94268702010-10-08 18:24:19 +00001339 // __attribute__((aligned)) can increase or decrease alignment
1340 // *except* on a struct or struct member, where it only increases
1341 // alignment unless 'packed' is also specified.
1342 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001343 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001344 // ignore that possibility; Sema should diagnose it.
1345 if (isa<FieldDecl>(D)) {
1346 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1347 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1348 } else {
1349 UseAlignAttrOnly = true;
1350 }
1351 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001352 else if (isa<FieldDecl>(D))
1353 UseAlignAttrOnly =
1354 D->hasAttr<PackedAttr>() ||
1355 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001356
John McCall4e819612011-01-20 07:57:12 +00001357 // If we're using the align attribute only, just ignore everything
1358 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001359 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001360 // do nothing
1361
John McCall94268702010-10-08 18:24:19 +00001362 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001363 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001364 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001365 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001366 T = RT->getPointeeType();
1367 else
1368 T = getPointerType(RT->getPointeeType());
1369 }
Richard Smithf6d70302014-06-10 23:34:28 +00001370 QualType BaseT = getBaseElementType(T);
1371 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001372 // Adjust alignments of declarations with array type by the
1373 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001374 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001375 unsigned MinWidth = Target->getLargeArrayMinWidth();
1376 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001377 if (isa<VariableArrayType>(arrayType))
1378 Align = std::max(Align, Target->getLargeArrayAlign());
1379 else if (isa<ConstantArrayType>(arrayType) &&
1380 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1381 Align = std::max(Align, Target->getLargeArrayAlign());
1382 }
John McCall33ddac02011-01-19 10:06:00 +00001383 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001384 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001385 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001386 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001387 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1388 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001389 }
John McCall4e819612011-01-20 07:57:12 +00001390
1391 // Fields can be subject to extra alignment constraints, like if
1392 // the field is packed, the struct is packed, or the struct has a
1393 // a max-field-alignment constraint (#pragma pack). So calculate
1394 // the actual alignment of the field within the struct, and then
1395 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001396 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1397 const RecordDecl *Parent = Field->getParent();
1398 // We can only produce a sensible answer if the record is valid.
1399 if (!Parent->isInvalidDecl()) {
1400 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001401
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001402 // Start with the record's overall alignment.
1403 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001404
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001405 // Use the GCD of that and the offset within the record.
1406 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1407 if (Offset > 0) {
1408 // Alignment is always a power of 2, so the GCD will be a power of 2,
1409 // which means we get to do this crazy thing instead of Euclid's.
1410 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1411 if (LowBitOfOffset < FieldAlign)
1412 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1413 }
1414
1415 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001416 }
Charles Davis3fc51072010-02-23 04:52:00 +00001417 }
Chris Lattner68061312009-01-24 21:53:27 +00001418 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001419
Ken Dyckcc56c542011-01-15 18:38:59 +00001420 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001421}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001422
John McCallf1249922012-08-21 04:10:00 +00001423// getTypeInfoDataSizeInChars - Return the size of a type, in
1424// chars. If the type is a record, its data size is returned. This is
1425// the size of the memcpy that's performed when assigning this type
1426// using a trivial copy/move assignment operator.
1427std::pair<CharUnits, CharUnits>
1428ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1429 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1430
1431 // In C++, objects can sometimes be allocated into the tail padding
1432 // of a base-class subobject. We decide whether that's possible
1433 // during class layout, so here we can just trust the layout results.
1434 if (getLangOpts().CPlusPlus) {
1435 if (const RecordType *RT = T->getAs<RecordType>()) {
1436 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1437 sizeAndAlign.first = layout.getDataSize();
1438 }
1439 }
1440
1441 return sizeAndAlign;
1442}
1443
Richard Trieu04d2d942013-05-14 21:59:17 +00001444/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1445/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1446std::pair<CharUnits, CharUnits>
1447static getConstantArrayInfoInChars(const ASTContext &Context,
1448 const ConstantArrayType *CAT) {
1449 std::pair<CharUnits, CharUnits> EltInfo =
1450 Context.getTypeInfoInChars(CAT->getElementType());
1451 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001452 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1453 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001454 "Overflow in array type char size evaluation");
1455 uint64_t Width = EltInfo.first.getQuantity() * Size;
1456 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001457 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1458 Context.getTargetInfo().getPointerWidth(0) == 64)
1459 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001460 return std::make_pair(CharUnits::fromQuantity(Width),
1461 CharUnits::fromQuantity(Align));
1462}
1463
John McCall87fe5d52010-05-20 01:18:31 +00001464std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001465ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001466 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1467 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001468 TypeInfo Info = getTypeInfo(T);
1469 return std::make_pair(toCharUnitsFromBits(Info.Width),
1470 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001471}
1472
1473std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001474ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001475 return getTypeInfoInChars(T.getTypePtr());
1476}
1477
David Majnemer34b57492014-07-30 01:30:47 +00001478bool ASTContext::isAlignmentRequired(const Type *T) const {
1479 return getTypeInfo(T).AlignIsRequired;
1480}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001481
David Majnemer34b57492014-07-30 01:30:47 +00001482bool ASTContext::isAlignmentRequired(QualType T) const {
1483 return isAlignmentRequired(T.getTypePtr());
1484}
1485
1486TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001487 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1488 if (I != MemoizedTypeInfo.end())
1489 return I->second;
1490
1491 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1492 TypeInfo TI = getTypeInfoImpl(T);
1493 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001494 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001495}
1496
1497/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1498/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001499///
1500/// FIXME: Pointers into different addr spaces could have different sizes and
1501/// alignment requirements: getPointerInfo should take an AddrSpace, this
1502/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001503TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1504 uint64_t Width = 0;
1505 unsigned Align = 8;
1506 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001507 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001508#define TYPE(Class, Base)
1509#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001510#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001511#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001512#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1513 case Type::Class: \
1514 assert(!T->isDependentType() && "should not see dependent types here"); \
1515 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001516#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001517 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001518
Chris Lattner355332d2007-07-13 22:27:08 +00001519 case Type::FunctionNoProto:
1520 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001521 // GCC extension: alignof(function) = 32 bits
1522 Width = 0;
1523 Align = 32;
1524 break;
1525
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001526 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001527 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001528 Width = 0;
1529 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1530 break;
1531
Steve Naroff5c131802007-08-30 01:06:46 +00001532 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001533 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001534
David Majnemer34b57492014-07-30 01:30:47 +00001535 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001536 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001537 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001538 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001539 Width = EltInfo.Width * Size;
1540 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001541 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1542 getTargetInfo().getPointerWidth(0) == 64)
1543 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001544 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001545 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001546 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001547 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001548 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001549 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1550 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001551 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001552 // If the alignment is not a power of 2, round up to the next power of 2.
1553 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001554 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001555 Align = llvm::NextPowerOf2(Align);
1556 Width = llvm::RoundUpToAlignment(Width, Align);
1557 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001558 // Adjust the alignment based on the target max.
1559 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1560 if (TargetVectorAlign && TargetVectorAlign < Align)
1561 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001562 break;
1563 }
Chris Lattner647fb222007-07-18 18:26:58 +00001564
Chris Lattner7570e9c2008-03-08 08:52:55 +00001565 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001566 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001567 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001568 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001569 // GCC extension: alignof(void) = 8 bits.
1570 Width = 0;
1571 Align = 8;
1572 break;
1573
Chris Lattner6a4f7452007-12-19 19:23:28 +00001574 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001575 Width = Target->getBoolWidth();
1576 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001577 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001578 case BuiltinType::Char_S:
1579 case BuiltinType::Char_U:
1580 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001581 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001582 Width = Target->getCharWidth();
1583 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001584 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001585 case BuiltinType::WChar_S:
1586 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001587 Width = Target->getWCharWidth();
1588 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001589 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001590 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001591 Width = Target->getChar16Width();
1592 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001593 break;
1594 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001595 Width = Target->getChar32Width();
1596 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001597 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001598 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001599 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001600 Width = Target->getShortWidth();
1601 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001602 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001603 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001604 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001605 Width = Target->getIntWidth();
1606 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001607 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001608 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001609 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001610 Width = Target->getLongWidth();
1611 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001612 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001613 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001614 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001615 Width = Target->getLongLongWidth();
1616 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001617 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001618 case BuiltinType::Int128:
1619 case BuiltinType::UInt128:
1620 Width = 128;
1621 Align = 128; // int128_t is 128-bit aligned on all targets.
1622 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001623 case BuiltinType::Half:
1624 Width = Target->getHalfWidth();
1625 Align = Target->getHalfAlign();
1626 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001627 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001628 Width = Target->getFloatWidth();
1629 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001630 break;
1631 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001632 Width = Target->getDoubleWidth();
1633 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001634 break;
1635 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001636 Width = Target->getLongDoubleWidth();
1637 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001638 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001639 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001640 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1641 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001642 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001643 case BuiltinType::ObjCId:
1644 case BuiltinType::ObjCClass:
1645 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001646 Width = Target->getPointerWidth(0);
1647 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001648 break;
Guy Benyei61054192013-02-07 10:55:47 +00001649 case BuiltinType::OCLSampler:
1650 // Samplers are modeled as integers.
1651 Width = Target->getIntWidth();
1652 Align = Target->getIntAlign();
1653 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001654 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001655 case BuiltinType::OCLClkEvent:
1656 case BuiltinType::OCLQueue:
1657 case BuiltinType::OCLNDRange:
1658 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001659 case BuiltinType::OCLImage1d:
1660 case BuiltinType::OCLImage1dArray:
1661 case BuiltinType::OCLImage1dBuffer:
1662 case BuiltinType::OCLImage2d:
1663 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001664 case BuiltinType::OCLImage2dDepth:
1665 case BuiltinType::OCLImage2dArrayDepth:
1666 case BuiltinType::OCLImage2dMSAA:
1667 case BuiltinType::OCLImage2dArrayMSAA:
1668 case BuiltinType::OCLImage2dMSAADepth:
1669 case BuiltinType::OCLImage2dArrayMSAADepth:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001670 case BuiltinType::OCLImage3d:
1671 // Currently these types are pointers to opaque types.
1672 Width = Target->getPointerWidth(0);
1673 Align = Target->getPointerAlign(0);
1674 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001675 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001676 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001677 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001678 Width = Target->getPointerWidth(0);
1679 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001680 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001681 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001682 unsigned AS = getTargetAddressSpace(
1683 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001684 Width = Target->getPointerWidth(AS);
1685 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001686 break;
1687 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001688 case Type::LValueReference:
1689 case Type::RValueReference: {
1690 // alignof and sizeof should never enter this code path here, so we go
1691 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001692 unsigned AS = getTargetAddressSpace(
1693 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001694 Width = Target->getPointerWidth(AS);
1695 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001696 break;
1697 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001698 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001699 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001700 Width = Target->getPointerWidth(AS);
1701 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001702 break;
1703 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001704 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001705 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001706 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001707 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001708 }
Chris Lattner647fb222007-07-18 18:26:58 +00001709 case Type::Complex: {
1710 // Complex types have the same alignment as their elements, but twice the
1711 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001712 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1713 Width = EltInfo.Width * 2;
1714 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001715 break;
1716 }
John McCall8b07ec22010-05-15 11:32:37 +00001717 case Type::ObjCObject:
1718 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001719 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001720 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001721 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001722 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001723 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001724 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001725 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001726 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001727 break;
1728 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001729 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001730 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001731 const TagType *TT = cast<TagType>(T);
1732
1733 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001734 Width = 8;
1735 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001736 break;
1737 }
Mike Stump11289f42009-09-09 15:08:12 +00001738
David Majnemer475b25e2015-01-21 10:54:38 +00001739 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1740 const EnumDecl *ED = ET->getDecl();
1741 TypeInfo Info =
1742 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1743 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1744 Info.Align = AttrAlign;
1745 Info.AlignIsRequired = true;
1746 }
1747 return Info;
1748 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001749
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001750 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001751 const RecordDecl *RD = RT->getDecl();
1752 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001753 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001754 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001755 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001756 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001757 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001758
Chris Lattner63d2b362009-10-22 05:17:15 +00001759 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001760 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1761 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001762
Richard Smith30482bc2011-02-20 03:19:35 +00001763 case Type::Auto: {
1764 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001765 assert(!A->getDeducedType().isNull() &&
1766 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001767 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001768 }
1769
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001770 case Type::Paren:
1771 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1772
Douglas Gregoref462e62009-04-30 17:32:17 +00001773 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001774 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001775 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001776 // If the typedef has an aligned attribute on it, it overrides any computed
1777 // alignment we have. This violates the GCC documentation (which says that
1778 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001779 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001780 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001781 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001782 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001783 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001784 AlignIsRequired = Info.AlignIsRequired;
1785 }
David Majnemer34b57492014-07-30 01:30:47 +00001786 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001787 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001788 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001789
Abramo Bagnara6150c882010-05-11 21:36:43 +00001790 case Type::Elaborated:
1791 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001792
John McCall81904512011-01-06 01:58:22 +00001793 case Type::Attributed:
1794 return getTypeInfo(
1795 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1796
Eli Friedman0dfb8892011-10-06 23:00:33 +00001797 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001798 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001799 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1800 Width = Info.Width;
1801 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001802
1803 // If the size of the type doesn't exceed the platform's max
1804 // atomic promotion width, make the size and alignment more
1805 // favorable to atomic operations:
1806 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1807 // Round the size up to a power of 2.
1808 if (!llvm::isPowerOf2_64(Width))
1809 Width = llvm::NextPowerOf2(Width);
1810
1811 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001812 Align = static_cast<unsigned>(Width);
1813 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001814 }
1815
Douglas Gregoref462e62009-04-30 17:32:17 +00001816 }
Mike Stump11289f42009-09-09 15:08:12 +00001817
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001818 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001819 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001820}
1821
Alexey Bataev00396512015-07-02 03:40:19 +00001822unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1823 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1824 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1825 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1826 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1827 getTargetInfo().getABI() == "elfv1-qpx" &&
1828 T->isSpecificBuiltinType(BuiltinType::Double))
1829 SimdAlign = 256;
1830 return SimdAlign;
1831}
1832
Ken Dyckcc56c542011-01-15 18:38:59 +00001833/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1834CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1835 return CharUnits::fromQuantity(BitSize / getCharWidth());
1836}
1837
Ken Dyckb0fcc592011-02-11 01:54:29 +00001838/// toBits - Convert a size in characters to a size in characters.
1839int64_t ASTContext::toBits(CharUnits CharSize) const {
1840 return CharSize.getQuantity() * getCharWidth();
1841}
1842
Ken Dyck8c89d592009-12-22 14:23:30 +00001843/// getTypeSizeInChars - Return the size of the specified type, in characters.
1844/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001845CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001846 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001847}
Jay Foad39c79802011-01-12 09:06:06 +00001848CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001849 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001850}
1851
Ken Dycka6046ab2010-01-26 17:25:18 +00001852/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001853/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001854CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001855 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001856}
Jay Foad39c79802011-01-12 09:06:06 +00001857CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001858 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001859}
1860
Chris Lattnera3402cd2009-01-27 18:08:34 +00001861/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1862/// type for the current target in bits. This can be different than the ABI
1863/// alignment in cases where it is beneficial for performance to overalign
1864/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001865unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001866 TypeInfo TI = getTypeInfo(T);
1867 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001868
David Majnemere1544562015-04-24 01:25:05 +00001869 T = T->getBaseElementTypeUnsafe();
1870
1871 // The preferred alignment of member pointers is that of a pointer.
1872 if (T->isMemberPointerType())
1873 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1874
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001875 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1876 return ABIAlign; // Never overalign on XCore.
1877
Eli Friedman7ab09572009-05-25 21:27:19 +00001878 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001879 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001880 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001881 if (const EnumType *ET = T->getAs<EnumType>())
1882 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001883 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001884 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1885 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001886 // Don't increase the alignment if an alignment attribute was specified on a
1887 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001888 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001889 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001890
Chris Lattnera3402cd2009-01-27 18:08:34 +00001891 return ABIAlign;
1892}
1893
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001894/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1895/// for __attribute__((aligned)) on this target, to be used if no alignment
1896/// value is specified.
1897unsigned ASTContext::getTargetDefaultAlignForAttributeAligned(void) const {
1898 return getTargetInfo().getDefaultAlignForAttributeAligned();
1899}
1900
Ulrich Weigandfa806422013-05-06 16:23:57 +00001901/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1902/// to a global variable of the specified type.
1903unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1904 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1905}
1906
1907/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1908/// should be given to a global variable of the specified type.
1909CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1910 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1911}
1912
David Majnemer08ef2ba2015-06-23 20:34:18 +00001913CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1914 CharUnits Offset = CharUnits::Zero();
1915 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1916 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1917 Offset += Layout->getBaseClassOffset(Base);
1918 Layout = &getASTRecordLayout(Base);
1919 }
1920 return Offset;
1921}
1922
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001923/// DeepCollectObjCIvars -
1924/// This routine first collects all declared, but not synthesized, ivars in
1925/// super class and then collects all ivars, including those synthesized for
1926/// current class. This routine is used for implementation of current class
1927/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001928///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001929void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1930 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001931 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001932 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1933 DeepCollectObjCIvars(SuperClass, false, Ivars);
1934 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001935 for (const auto *I : OI->ivars())
1936 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001937 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001938 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001939 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001940 Iv= Iv->getNextIvar())
1941 Ivars.push_back(Iv);
1942 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001943}
1944
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001945/// CollectInheritedProtocols - Collect all protocols in current class and
1946/// those inherited by it.
1947void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001948 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001949 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001950 // We can use protocol_iterator here instead of
1951 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001952 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001953 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001954 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001955
1956 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001957 for (const auto *Cat : OI->visible_categories())
1958 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001959
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001960 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1961 while (SD) {
1962 CollectInheritedProtocols(SD, Protocols);
1963 SD = SD->getSuperClass();
1964 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001965 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001966 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001967 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001968 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001969 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001970 // Insert the protocol.
1971 if (!Protocols.insert(
1972 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1973 return;
1974
1975 for (auto *Proto : OP->protocols())
1976 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001977 }
1978}
1979
Jay Foad39c79802011-01-12 09:06:06 +00001980unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001981 unsigned count = 0;
1982 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001983 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001984 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001985
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001986 // Count ivar defined in this class's implementation. This
1987 // includes synthesized ivars.
1988 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001989 count += ImplDecl->ivar_size();
1990
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001991 return count;
1992}
1993
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001994bool ASTContext::isSentinelNullExpr(const Expr *E) {
1995 if (!E)
1996 return false;
1997
1998 // nullptr_t is always treated as null.
1999 if (E->getType()->isNullPtrType()) return true;
2000
2001 if (E->getType()->isAnyPointerType() &&
2002 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2003 Expr::NPC_ValueDependentIsNull))
2004 return true;
2005
2006 // Unfortunately, __null has type 'int'.
2007 if (isa<GNUNullExpr>(E)) return true;
2008
2009 return false;
2010}
2011
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002012/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2013ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2014 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2015 I = ObjCImpls.find(D);
2016 if (I != ObjCImpls.end())
2017 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002018 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002019}
2020/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2021ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2022 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2023 I = ObjCImpls.find(D);
2024 if (I != ObjCImpls.end())
2025 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002026 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002027}
2028
2029/// \brief Set the implementation of ObjCInterfaceDecl.
2030void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2031 ObjCImplementationDecl *ImplD) {
2032 assert(IFaceD && ImplD && "Passed null params");
2033 ObjCImpls[IFaceD] = ImplD;
2034}
2035/// \brief Set the implementation of ObjCCategoryDecl.
2036void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2037 ObjCCategoryImplDecl *ImplD) {
2038 assert(CatD && ImplD && "Passed null params");
2039 ObjCImpls[CatD] = ImplD;
2040}
2041
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002042const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2043 const NamedDecl *ND) const {
2044 if (const ObjCInterfaceDecl *ID =
2045 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002046 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002047 if (const ObjCCategoryDecl *CD =
2048 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002049 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002050 if (const ObjCImplDecl *IMD =
2051 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002052 return IMD->getClassInterface();
2053
Craig Topper36250ad2014-05-12 05:36:57 +00002054 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002055}
2056
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002057/// \brief Get the copy initialization expression of VarDecl,or NULL if
2058/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002059Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002060 assert(VD && "Passed null params");
2061 assert(VD->hasAttr<BlocksAttr>() &&
2062 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002063 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002064 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002065 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002066}
2067
2068/// \brief Set the copy inialization expression of a block var decl.
2069void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2070 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002071 assert(VD->hasAttr<BlocksAttr>() &&
2072 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002073 BlockVarCopyInits[VD] = Init;
2074}
2075
John McCallbcd03502009-12-07 02:54:59 +00002076TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002077 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002078 if (!DataSize)
2079 DataSize = TypeLoc::getFullDataSizeForType(T);
2080 else
2081 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002082 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002083
John McCallbcd03502009-12-07 02:54:59 +00002084 TypeSourceInfo *TInfo =
2085 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2086 new (TInfo) TypeSourceInfo(T);
2087 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002088}
2089
John McCallbcd03502009-12-07 02:54:59 +00002090TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002091 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002092 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002093 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002094 return DI;
2095}
2096
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002097const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002098ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002099 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002100}
2101
2102const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002103ASTContext::getASTObjCImplementationLayout(
2104 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002105 return getObjCLayout(D->getClassInterface(), D);
2106}
2107
Chris Lattner983a8bb2007-07-13 22:13:22 +00002108//===----------------------------------------------------------------------===//
2109// Type creation/memoization methods
2110//===----------------------------------------------------------------------===//
2111
Jay Foad39c79802011-01-12 09:06:06 +00002112QualType
John McCall33ddac02011-01-19 10:06:00 +00002113ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2114 unsigned fastQuals = quals.getFastQualifiers();
2115 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002116
2117 // Check if we've already instantiated this type.
2118 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002119 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002120 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002121 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2122 assert(eq->getQualifiers() == quals);
2123 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002124 }
2125
John McCall33ddac02011-01-19 10:06:00 +00002126 // If the base type is not canonical, make the appropriate canonical type.
2127 QualType canon;
2128 if (!baseType->isCanonicalUnqualified()) {
2129 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002130 canonSplit.Quals.addConsistentQualifiers(quals);
2131 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002132
2133 // Re-find the insert position.
2134 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2135 }
2136
2137 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2138 ExtQualNodes.InsertNode(eq, insertPos);
2139 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002140}
2141
Jay Foad39c79802011-01-12 09:06:06 +00002142QualType
2143ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002144 QualType CanT = getCanonicalType(T);
2145 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002146 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002147
John McCall8ccfcb52009-09-24 19:53:00 +00002148 // If we are composing extended qualifiers together, merge together
2149 // into one ExtQuals node.
2150 QualifierCollector Quals;
2151 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002152
John McCall8ccfcb52009-09-24 19:53:00 +00002153 // If this type already has an address space specified, it cannot get
2154 // another one.
2155 assert(!Quals.hasAddressSpace() &&
2156 "Type cannot be in multiple addr spaces!");
2157 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002158
John McCall8ccfcb52009-09-24 19:53:00 +00002159 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002160}
2161
Chris Lattnerd60183d2009-02-18 22:53:11 +00002162QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002163 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002164 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002165 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002166 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002167
John McCall53fa7142010-12-24 02:08:15 +00002168 if (const PointerType *ptr = T->getAs<PointerType>()) {
2169 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002170 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002171 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2172 return getPointerType(ResultType);
2173 }
2174 }
Mike Stump11289f42009-09-09 15:08:12 +00002175
John McCall8ccfcb52009-09-24 19:53:00 +00002176 // If we are composing extended qualifiers together, merge together
2177 // into one ExtQuals node.
2178 QualifierCollector Quals;
2179 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002180
John McCall8ccfcb52009-09-24 19:53:00 +00002181 // If this type already has an ObjCGC specified, it cannot get
2182 // another one.
2183 assert(!Quals.hasObjCGCAttr() &&
2184 "Type cannot have multiple ObjCGCs!");
2185 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002186
John McCall8ccfcb52009-09-24 19:53:00 +00002187 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002188}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002189
John McCall4f5019e2010-12-19 02:44:49 +00002190const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2191 FunctionType::ExtInfo Info) {
2192 if (T->getExtInfo() == Info)
2193 return T;
2194
2195 QualType Result;
2196 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002197 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002198 } else {
2199 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2200 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2201 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002202 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002203 }
2204
2205 return cast<FunctionType>(Result.getTypePtr());
2206}
2207
Richard Smith2a7d4812013-05-04 07:00:32 +00002208void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2209 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002210 FD = FD->getMostRecentDecl();
2211 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002212 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2213 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002214 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002215 if (FunctionDecl *Next = FD->getPreviousDecl())
2216 FD = Next;
2217 else
2218 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002219 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002220 if (ASTMutationListener *L = getASTMutationListener())
2221 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002222}
2223
Richard Smith0b3a4622014-11-13 20:01:57 +00002224/// Get a function type and produce the equivalent function type with the
2225/// specified exception specification. Type sugar that can be present on a
2226/// declaration of a function with an exception specification is permitted
2227/// and preserved. Other type sugar (for instance, typedefs) is not.
2228static QualType getFunctionTypeWithExceptionSpec(
2229 ASTContext &Context, QualType Orig,
2230 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2231 // Might have some parens.
2232 if (auto *PT = dyn_cast<ParenType>(Orig))
2233 return Context.getParenType(
2234 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2235
2236 // Might have a calling-convention attribute.
2237 if (auto *AT = dyn_cast<AttributedType>(Orig))
2238 return Context.getAttributedType(
2239 AT->getAttrKind(),
2240 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2241 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2242 ESI));
2243
2244 // Anything else must be a function type. Rebuild it with the new exception
2245 // specification.
2246 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2247 return Context.getFunctionType(
2248 Proto->getReturnType(), Proto->getParamTypes(),
2249 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2250}
2251
2252void ASTContext::adjustExceptionSpec(
2253 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2254 bool AsWritten) {
2255 // Update the type.
2256 QualType Updated =
2257 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2258 FD->setType(Updated);
2259
2260 if (!AsWritten)
2261 return;
2262
2263 // Update the type in the type source information too.
2264 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2265 // If the type and the type-as-written differ, we may need to update
2266 // the type-as-written too.
2267 if (TSInfo->getType() != FD->getType())
2268 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2269
2270 // FIXME: When we get proper type location information for exceptions,
2271 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2272 // up the TypeSourceInfo;
2273 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2274 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2275 "TypeLoc size mismatch from updating exception specification");
2276 TSInfo->overrideType(Updated);
2277 }
2278}
2279
Chris Lattnerc6395932007-06-22 20:56:16 +00002280/// getComplexType - Return the uniqued reference to the type for a complex
2281/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002282QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002283 // Unique pointers, to guarantee there is only one pointer of a particular
2284 // structure.
2285 llvm::FoldingSetNodeID ID;
2286 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002287
Craig Topper36250ad2014-05-12 05:36:57 +00002288 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002289 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2290 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002291
Chris Lattnerc6395932007-06-22 20:56:16 +00002292 // If the pointee type isn't canonical, this won't be a canonical type either,
2293 // so fill in the canonical type field.
2294 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002295 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002296 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002297
Chris Lattnerc6395932007-06-22 20:56:16 +00002298 // Get the new insert position for the node we care about.
2299 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002300 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002301 }
John McCall90d1c2d2009-09-24 23:30:46 +00002302 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002303 Types.push_back(New);
2304 ComplexTypes.InsertNode(New, InsertPos);
2305 return QualType(New, 0);
2306}
2307
Chris Lattner970e54e2006-11-12 00:37:36 +00002308/// getPointerType - Return the uniqued reference to the type for a pointer to
2309/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002310QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002311 // Unique pointers, to guarantee there is only one pointer of a particular
2312 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002313 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002314 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002315
Craig Topper36250ad2014-05-12 05:36:57 +00002316 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002317 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002318 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002319
Chris Lattner7ccecb92006-11-12 08:50:50 +00002320 // If the pointee type isn't canonical, this won't be a canonical type either,
2321 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002322 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002323 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002324 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002325
Bob Wilsonc8541f22013-03-15 17:12:43 +00002326 // Get the new insert position for the node we care about.
2327 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002328 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002329 }
John McCall90d1c2d2009-09-24 23:30:46 +00002330 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002331 Types.push_back(New);
2332 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002333 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002334}
2335
Reid Kleckner0503a872013-12-05 01:23:43 +00002336QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2337 llvm::FoldingSetNodeID ID;
2338 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002339 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002340 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2341 if (AT)
2342 return QualType(AT, 0);
2343
2344 QualType Canonical = getCanonicalType(New);
2345
2346 // Get the new insert position for the node we care about.
2347 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002348 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002349
2350 AT = new (*this, TypeAlignment)
2351 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2352 Types.push_back(AT);
2353 AdjustedTypes.InsertNode(AT, InsertPos);
2354 return QualType(AT, 0);
2355}
2356
Reid Kleckner8a365022013-06-24 17:51:48 +00002357QualType ASTContext::getDecayedType(QualType T) const {
2358 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2359
Reid Kleckner8a365022013-06-24 17:51:48 +00002360 QualType Decayed;
2361
2362 // C99 6.7.5.3p7:
2363 // A declaration of a parameter as "array of type" shall be
2364 // adjusted to "qualified pointer to type", where the type
2365 // qualifiers (if any) are those specified within the [ and ] of
2366 // the array type derivation.
2367 if (T->isArrayType())
2368 Decayed = getArrayDecayedType(T);
2369
2370 // C99 6.7.5.3p8:
2371 // A declaration of a parameter as "function returning type"
2372 // shall be adjusted to "pointer to function returning type", as
2373 // in 6.3.2.1.
2374 if (T->isFunctionType())
2375 Decayed = getPointerType(T);
2376
Reid Kleckner0503a872013-12-05 01:23:43 +00002377 llvm::FoldingSetNodeID ID;
2378 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002379 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002380 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2381 if (AT)
2382 return QualType(AT, 0);
2383
Reid Kleckner8a365022013-06-24 17:51:48 +00002384 QualType Canonical = getCanonicalType(Decayed);
2385
2386 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002387 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002388 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002389
Reid Kleckner0503a872013-12-05 01:23:43 +00002390 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2391 Types.push_back(AT);
2392 AdjustedTypes.InsertNode(AT, InsertPos);
2393 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002394}
2395
Mike Stump11289f42009-09-09 15:08:12 +00002396/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002397/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002398QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002399 assert(T->isFunctionType() && "block of function types only");
2400 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002401 // structure.
2402 llvm::FoldingSetNodeID ID;
2403 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002404
Craig Topper36250ad2014-05-12 05:36:57 +00002405 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002406 if (BlockPointerType *PT =
2407 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2408 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002409
2410 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002411 // type either so fill in the canonical type field.
2412 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002413 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002414 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002415
Steve Naroffec33ed92008-08-27 16:04:49 +00002416 // Get the new insert position for the node we care about.
2417 BlockPointerType *NewIP =
2418 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002419 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002420 }
John McCall90d1c2d2009-09-24 23:30:46 +00002421 BlockPointerType *New
2422 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002423 Types.push_back(New);
2424 BlockPointerTypes.InsertNode(New, InsertPos);
2425 return QualType(New, 0);
2426}
2427
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002428/// getLValueReferenceType - Return the uniqued reference to the type for an
2429/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002430QualType
2431ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002432 assert(getCanonicalType(T) != OverloadTy &&
2433 "Unresolved overloaded function type");
2434
Bill Wendling3708c182007-05-27 10:15:43 +00002435 // Unique pointers, to guarantee there is only one pointer of a particular
2436 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002437 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002438 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002439
Craig Topper36250ad2014-05-12 05:36:57 +00002440 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002441 if (LValueReferenceType *RT =
2442 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002443 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002444
John McCallfc93cf92009-10-22 22:37:11 +00002445 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2446
Bill Wendling3708c182007-05-27 10:15:43 +00002447 // If the referencee type isn't canonical, this won't be a canonical type
2448 // either, so fill in the canonical type field.
2449 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002450 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2451 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2452 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002453
Bill Wendling3708c182007-05-27 10:15:43 +00002454 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002455 LValueReferenceType *NewIP =
2456 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002457 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002458 }
2459
John McCall90d1c2d2009-09-24 23:30:46 +00002460 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002461 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2462 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002463 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002464 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002465
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002466 return QualType(New, 0);
2467}
2468
2469/// getRValueReferenceType - Return the uniqued reference to the type for an
2470/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002471QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002472 // Unique pointers, to guarantee there is only one pointer of a particular
2473 // structure.
2474 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002475 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002476
Craig Topper36250ad2014-05-12 05:36:57 +00002477 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002478 if (RValueReferenceType *RT =
2479 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2480 return QualType(RT, 0);
2481
John McCallfc93cf92009-10-22 22:37:11 +00002482 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2483
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002484 // If the referencee type isn't canonical, this won't be a canonical type
2485 // either, so fill in the canonical type field.
2486 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002487 if (InnerRef || !T.isCanonical()) {
2488 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2489 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002490
2491 // Get the new insert position for the node we care about.
2492 RValueReferenceType *NewIP =
2493 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002494 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002495 }
2496
John McCall90d1c2d2009-09-24 23:30:46 +00002497 RValueReferenceType *New
2498 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002499 Types.push_back(New);
2500 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002501 return QualType(New, 0);
2502}
2503
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002504/// getMemberPointerType - Return the uniqued reference to the type for a
2505/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002506QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002507 // Unique pointers, to guarantee there is only one pointer of a particular
2508 // structure.
2509 llvm::FoldingSetNodeID ID;
2510 MemberPointerType::Profile(ID, T, Cls);
2511
Craig Topper36250ad2014-05-12 05:36:57 +00002512 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002513 if (MemberPointerType *PT =
2514 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2515 return QualType(PT, 0);
2516
2517 // If the pointee or class type isn't canonical, this won't be a canonical
2518 // type either, so fill in the canonical type field.
2519 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002520 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002521 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2522
2523 // Get the new insert position for the node we care about.
2524 MemberPointerType *NewIP =
2525 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002526 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002527 }
John McCall90d1c2d2009-09-24 23:30:46 +00002528 MemberPointerType *New
2529 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002530 Types.push_back(New);
2531 MemberPointerTypes.InsertNode(New, InsertPos);
2532 return QualType(New, 0);
2533}
2534
Mike Stump11289f42009-09-09 15:08:12 +00002535/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002536/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002537QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002538 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002539 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002540 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002541 assert((EltTy->isDependentType() ||
2542 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002543 "Constant array of VLAs is illegal!");
2544
Chris Lattnere2df3f92009-05-13 04:12:56 +00002545 // Convert the array size into a canonical width matching the pointer size for
2546 // the target.
2547 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002548 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002549 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002550
Chris Lattner23b7eb62007-06-15 23:05:46 +00002551 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002552 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002553
Craig Topper36250ad2014-05-12 05:36:57 +00002554 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002555 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002556 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002557 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002558
John McCall33ddac02011-01-19 10:06:00 +00002559 // If the element type isn't canonical or has qualifiers, this won't
2560 // be a canonical type either, so fill in the canonical type field.
2561 QualType Canon;
2562 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2563 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002564 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002565 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002566 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002567
Chris Lattner36f8e652007-01-27 08:31:04 +00002568 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002569 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002570 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002571 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002572 }
Mike Stump11289f42009-09-09 15:08:12 +00002573
John McCall90d1c2d2009-09-24 23:30:46 +00002574 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002575 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002576 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002577 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002578 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002579}
2580
John McCall06549462011-01-18 08:40:38 +00002581/// getVariableArrayDecayedType - Turns the given type, which may be
2582/// variably-modified, into the corresponding type with all the known
2583/// sizes replaced with [*].
2584QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2585 // Vastly most common case.
2586 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002587
John McCall06549462011-01-18 08:40:38 +00002588 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002589
John McCall06549462011-01-18 08:40:38 +00002590 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002591 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002592 switch (ty->getTypeClass()) {
2593#define TYPE(Class, Base)
2594#define ABSTRACT_TYPE(Class, Base)
2595#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2596#include "clang/AST/TypeNodes.def"
2597 llvm_unreachable("didn't desugar past all non-canonical types?");
2598
2599 // These types should never be variably-modified.
2600 case Type::Builtin:
2601 case Type::Complex:
2602 case Type::Vector:
2603 case Type::ExtVector:
2604 case Type::DependentSizedExtVector:
2605 case Type::ObjCObject:
2606 case Type::ObjCInterface:
2607 case Type::ObjCObjectPointer:
2608 case Type::Record:
2609 case Type::Enum:
2610 case Type::UnresolvedUsing:
2611 case Type::TypeOfExpr:
2612 case Type::TypeOf:
2613 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002614 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002615 case Type::DependentName:
2616 case Type::InjectedClassName:
2617 case Type::TemplateSpecialization:
2618 case Type::DependentTemplateSpecialization:
2619 case Type::TemplateTypeParm:
2620 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002621 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002622 case Type::PackExpansion:
2623 llvm_unreachable("type should never be variably-modified");
2624
2625 // These types can be variably-modified but should never need to
2626 // further decay.
2627 case Type::FunctionNoProto:
2628 case Type::FunctionProto:
2629 case Type::BlockPointer:
2630 case Type::MemberPointer:
2631 return type;
2632
2633 // These types can be variably-modified. All these modifications
2634 // preserve structure except as noted by comments.
2635 // TODO: if we ever care about optimizing VLAs, there are no-op
2636 // optimizations available here.
2637 case Type::Pointer:
2638 result = getPointerType(getVariableArrayDecayedType(
2639 cast<PointerType>(ty)->getPointeeType()));
2640 break;
2641
2642 case Type::LValueReference: {
2643 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2644 result = getLValueReferenceType(
2645 getVariableArrayDecayedType(lv->getPointeeType()),
2646 lv->isSpelledAsLValue());
2647 break;
2648 }
2649
2650 case Type::RValueReference: {
2651 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2652 result = getRValueReferenceType(
2653 getVariableArrayDecayedType(lv->getPointeeType()));
2654 break;
2655 }
2656
Eli Friedman0dfb8892011-10-06 23:00:33 +00002657 case Type::Atomic: {
2658 const AtomicType *at = cast<AtomicType>(ty);
2659 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2660 break;
2661 }
2662
John McCall06549462011-01-18 08:40:38 +00002663 case Type::ConstantArray: {
2664 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2665 result = getConstantArrayType(
2666 getVariableArrayDecayedType(cat->getElementType()),
2667 cat->getSize(),
2668 cat->getSizeModifier(),
2669 cat->getIndexTypeCVRQualifiers());
2670 break;
2671 }
2672
2673 case Type::DependentSizedArray: {
2674 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2675 result = getDependentSizedArrayType(
2676 getVariableArrayDecayedType(dat->getElementType()),
2677 dat->getSizeExpr(),
2678 dat->getSizeModifier(),
2679 dat->getIndexTypeCVRQualifiers(),
2680 dat->getBracketsRange());
2681 break;
2682 }
2683
2684 // Turn incomplete types into [*] types.
2685 case Type::IncompleteArray: {
2686 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2687 result = getVariableArrayType(
2688 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002689 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002690 ArrayType::Normal,
2691 iat->getIndexTypeCVRQualifiers(),
2692 SourceRange());
2693 break;
2694 }
2695
2696 // Turn VLA types into [*] types.
2697 case Type::VariableArray: {
2698 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2699 result = getVariableArrayType(
2700 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002701 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002702 ArrayType::Star,
2703 vat->getIndexTypeCVRQualifiers(),
2704 vat->getBracketsRange());
2705 break;
2706 }
2707 }
2708
2709 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002710 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002711}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002712
Steve Naroffcadebd02007-08-30 18:14:25 +00002713/// getVariableArrayType - Returns a non-unique reference to the type for a
2714/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002715QualType ASTContext::getVariableArrayType(QualType EltTy,
2716 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002717 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002718 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002719 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002720 // Since we don't unique expressions, it isn't possible to unique VLA's
2721 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002722 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002723
John McCall33ddac02011-01-19 10:06:00 +00002724 // Be sure to pull qualifiers off the element type.
2725 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2726 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002727 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002728 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002729 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002730 }
2731
John McCall90d1c2d2009-09-24 23:30:46 +00002732 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002733 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002734
2735 VariableArrayTypes.push_back(New);
2736 Types.push_back(New);
2737 return QualType(New, 0);
2738}
2739
Douglas Gregor4619e432008-12-05 23:32:09 +00002740/// getDependentSizedArrayType - Returns a non-unique reference to
2741/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002742/// type.
John McCall33ddac02011-01-19 10:06:00 +00002743QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2744 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002745 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002746 unsigned elementTypeQuals,
2747 SourceRange brackets) const {
2748 assert((!numElements || numElements->isTypeDependent() ||
2749 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002750 "Size must be type- or value-dependent!");
2751
John McCall33ddac02011-01-19 10:06:00 +00002752 // Dependently-sized array types that do not have a specified number
2753 // of elements will have their sizes deduced from a dependent
2754 // initializer. We do no canonicalization here at all, which is okay
2755 // because they can't be used in most locations.
2756 if (!numElements) {
2757 DependentSizedArrayType *newType
2758 = new (*this, TypeAlignment)
2759 DependentSizedArrayType(*this, elementType, QualType(),
2760 numElements, ASM, elementTypeQuals,
2761 brackets);
2762 Types.push_back(newType);
2763 return QualType(newType, 0);
2764 }
2765
2766 // Otherwise, we actually build a new type every time, but we
2767 // also build a canonical type.
2768
2769 SplitQualType canonElementType = getCanonicalType(elementType).split();
2770
Craig Topper36250ad2014-05-12 05:36:57 +00002771 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002772 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002773 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002774 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002775 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002776
John McCall33ddac02011-01-19 10:06:00 +00002777 // Look for an existing type with these properties.
2778 DependentSizedArrayType *canonTy =
2779 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002780
John McCall33ddac02011-01-19 10:06:00 +00002781 // If we don't have one, build one.
2782 if (!canonTy) {
2783 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002784 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002785 QualType(), numElements, ASM, elementTypeQuals,
2786 brackets);
2787 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2788 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002789 }
2790
John McCall33ddac02011-01-19 10:06:00 +00002791 // Apply qualifiers from the element type to the array.
2792 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002793 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002794
David Majnemer16a74702015-07-24 05:54:19 +00002795 // If we didn't need extra canonicalization for the element type or the size
2796 // expression, then just use that as our result.
2797 if (QualType(canonElementType.Ty, 0) == elementType &&
2798 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002799 return canon;
2800
2801 // Otherwise, we need to build a type which follows the spelling
2802 // of the element type.
2803 DependentSizedArrayType *sugaredType
2804 = new (*this, TypeAlignment)
2805 DependentSizedArrayType(*this, elementType, canon, numElements,
2806 ASM, elementTypeQuals, brackets);
2807 Types.push_back(sugaredType);
2808 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002809}
2810
John McCall33ddac02011-01-19 10:06:00 +00002811QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002812 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002813 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002814 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002815 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002816
Craig Topper36250ad2014-05-12 05:36:57 +00002817 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002818 if (IncompleteArrayType *iat =
2819 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2820 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002821
2822 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002823 // either, so fill in the canonical type field. We also have to pull
2824 // qualifiers off the element type.
2825 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002826
John McCall33ddac02011-01-19 10:06:00 +00002827 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2828 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002829 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002830 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002831 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002832
2833 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002834 IncompleteArrayType *existing =
2835 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2836 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002837 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002838
John McCall33ddac02011-01-19 10:06:00 +00002839 IncompleteArrayType *newType = new (*this, TypeAlignment)
2840 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002841
John McCall33ddac02011-01-19 10:06:00 +00002842 IncompleteArrayTypes.InsertNode(newType, insertPos);
2843 Types.push_back(newType);
2844 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002845}
2846
Steve Naroff91fcddb2007-07-18 18:00:27 +00002847/// getVectorType - Return the unique reference to a vector type of
2848/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002849QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002850 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002851 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002852
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002853 // Check if we've already instantiated a vector of this type.
2854 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002855 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002856
Craig Topper36250ad2014-05-12 05:36:57 +00002857 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002858 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2859 return QualType(VTP, 0);
2860
2861 // If the element type isn't canonical, this won't be a canonical type either,
2862 // so fill in the canonical type field.
2863 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002864 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002865 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002866
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002867 // Get the new insert position for the node we care about.
2868 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002869 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002870 }
John McCall90d1c2d2009-09-24 23:30:46 +00002871 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002872 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002873 VectorTypes.InsertNode(New, InsertPos);
2874 Types.push_back(New);
2875 return QualType(New, 0);
2876}
2877
Nate Begemance4d7fc2008-04-18 23:10:10 +00002878/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002879/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002880QualType
2881ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002882 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002883
Steve Naroff91fcddb2007-07-18 18:00:27 +00002884 // Check if we've already instantiated a vector of this type.
2885 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002886 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002887 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002888 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002889 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2890 return QualType(VTP, 0);
2891
2892 // If the element type isn't canonical, this won't be a canonical type either,
2893 // so fill in the canonical type field.
2894 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002895 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002896 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002897
Steve Naroff91fcddb2007-07-18 18:00:27 +00002898 // Get the new insert position for the node we care about.
2899 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002900 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002901 }
John McCall90d1c2d2009-09-24 23:30:46 +00002902 ExtVectorType *New = new (*this, TypeAlignment)
2903 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002904 VectorTypes.InsertNode(New, InsertPos);
2905 Types.push_back(New);
2906 return QualType(New, 0);
2907}
2908
Jay Foad39c79802011-01-12 09:06:06 +00002909QualType
2910ASTContext::getDependentSizedExtVectorType(QualType vecType,
2911 Expr *SizeExpr,
2912 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002913 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002914 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002915 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002916
Craig Topper36250ad2014-05-12 05:36:57 +00002917 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002918 DependentSizedExtVectorType *Canon
2919 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2920 DependentSizedExtVectorType *New;
2921 if (Canon) {
2922 // We already have a canonical version of this array type; use it as
2923 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002924 New = new (*this, TypeAlignment)
2925 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2926 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002927 } else {
2928 QualType CanonVecTy = getCanonicalType(vecType);
2929 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002930 New = new (*this, TypeAlignment)
2931 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2932 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002933
2934 DependentSizedExtVectorType *CanonCheck
2935 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2936 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2937 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002938 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2939 } else {
2940 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2941 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002942 New = new (*this, TypeAlignment)
2943 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002944 }
2945 }
Mike Stump11289f42009-09-09 15:08:12 +00002946
Douglas Gregor758a8692009-06-17 21:51:59 +00002947 Types.push_back(New);
2948 return QualType(New, 0);
2949}
2950
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002951/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002952///
Jay Foad39c79802011-01-12 09:06:06 +00002953QualType
2954ASTContext::getFunctionNoProtoType(QualType ResultTy,
2955 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002956 const CallingConv CallConv = Info.getCC();
2957
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002958 // Unique functions, to guarantee there is only one function of a particular
2959 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002960 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002961 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002962
Craig Topper36250ad2014-05-12 05:36:57 +00002963 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002964 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002965 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002966 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002967
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002968 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002969 if (!ResultTy.isCanonical()) {
2970 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002971
Chris Lattner47955de2007-01-27 08:37:20 +00002972 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002973 FunctionNoProtoType *NewIP =
2974 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002975 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002976 }
Mike Stump11289f42009-09-09 15:08:12 +00002977
Roman Divacky65b88cd2011-03-01 17:40:53 +00002978 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002979 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002980 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002981 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002982 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002983 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002984}
2985
Douglas Gregorcd780372013-01-17 23:36:45 +00002986/// \brief Determine whether \p T is canonical as the result type of a function.
2987static bool isCanonicalResultType(QualType T) {
2988 return T.isCanonical() &&
2989 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2990 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2991}
2992
Douglas Gregora602a152015-10-01 20:20:47 +00002993CanQualType
2994ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
2995 CanQualType CanResultType = getCanonicalType(ResultType);
2996
2997 // Canonical result types do not have ARC lifetime qualifiers.
2998 if (CanResultType.getQualifiers().hasObjCLifetime()) {
2999 Qualifiers Qs = CanResultType.getQualifiers();
3000 Qs.removeObjCLifetime();
3001 return CanQualType::CreateUnsafe(
3002 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3003 }
3004
3005 return CanResultType;
3006}
3007
Jay Foad39c79802011-01-12 09:06:06 +00003008QualType
Jordan Rose5c382722013-03-08 21:51:21 +00003009ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00003010 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003011 size_t NumArgs = ArgArray.size();
3012
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003013 // Unique functions, to guarantee there is only one function of a particular
3014 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003015 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003016 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3017 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003018
Craig Topper36250ad2014-05-12 05:36:57 +00003019 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003020 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003021 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003022 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003023
3024 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003025 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003026 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003027 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003028 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003029 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003030 isCanonical = false;
3031
3032 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003033 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003034 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003035 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003036 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003037 CanonicalArgs.reserve(NumArgs);
3038 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003039 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003040
John McCalldb40c7f2010-12-14 08:05:40 +00003041 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003042 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003043 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003044
Douglas Gregora602a152015-10-01 20:20:47 +00003045 // Adjust the canonical function result type.
3046 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Jordan Rose5c382722013-03-08 21:51:21 +00003047 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003048
Chris Lattnerfd4de792007-01-27 01:15:32 +00003049 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003050 FunctionProtoType *NewIP =
3051 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003052 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003053 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003054
John McCall31168b02011-06-15 23:02:42 +00003055 // FunctionProtoType objects are allocated with extra bytes after
3056 // them for three variable size arrays at the end:
3057 // - parameter types
3058 // - exception types
3059 // - consumed-arguments flags
3060 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003061 // expression, or information used to resolve the exception
3062 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003063 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003064 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00003065 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3066 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3067 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003068 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003069 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003070 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003071 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003072 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003073 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003074 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00003075 Size += NumArgs * sizeof(bool);
3076
John McCalldb40c7f2010-12-14 08:05:40 +00003077 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003078 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003079 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003080 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003081 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003082 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003083}
Chris Lattneref51c202006-11-10 07:17:23 +00003084
John McCalle78aac42010-03-10 03:28:59 +00003085#ifndef NDEBUG
3086static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3087 if (!isa<CXXRecordDecl>(D)) return false;
3088 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3089 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3090 return true;
3091 if (RD->getDescribedClassTemplate() &&
3092 !isa<ClassTemplateSpecializationDecl>(RD))
3093 return true;
3094 return false;
3095}
3096#endif
3097
3098/// getInjectedClassNameType - Return the unique reference to the
3099/// injected class name type for the specified templated declaration.
3100QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003101 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003102 assert(NeedsInjectedClassNameType(Decl));
3103 if (Decl->TypeForDecl) {
3104 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003105 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003106 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3107 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3108 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3109 } else {
John McCall424cec92011-01-19 06:33:43 +00003110 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003111 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003112 Decl->TypeForDecl = newType;
3113 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003114 }
3115 return QualType(Decl->TypeForDecl, 0);
3116}
3117
Douglas Gregor83a586e2008-04-13 21:07:44 +00003118/// getTypeDeclType - Return the unique reference to the type for the
3119/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003120QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003121 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003122 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003123
Richard Smithdda56e42011-04-15 14:24:37 +00003124 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003125 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003126
John McCall96f0b5f2010-03-10 06:48:02 +00003127 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3128 "Template type parameter types are always available.");
3129
John McCall81e38502010-02-16 03:57:14 +00003130 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003131 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003132 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003133 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003134 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003135 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003136 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003137 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003138 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003139 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3140 Decl->TypeForDecl = newType;
3141 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003142 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003143 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003144
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003145 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003146}
3147
Chris Lattner32d920b2007-01-26 02:01:53 +00003148/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003149/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003150QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003151ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3152 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003153 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003154
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003155 if (Canonical.isNull())
3156 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003157 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003158 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003159 Decl->TypeForDecl = newType;
3160 Types.push_back(newType);
3161 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003162}
3163
Jay Foad39c79802011-01-12 09:06:06 +00003164QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003165 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3166
Douglas Gregorec9fd132012-01-14 16:38:05 +00003167 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003168 if (PrevDecl->TypeForDecl)
3169 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3170
John McCall424cec92011-01-19 06:33:43 +00003171 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3172 Decl->TypeForDecl = newType;
3173 Types.push_back(newType);
3174 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003175}
3176
Jay Foad39c79802011-01-12 09:06:06 +00003177QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003178 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3179
Douglas Gregorec9fd132012-01-14 16:38:05 +00003180 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003181 if (PrevDecl->TypeForDecl)
3182 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3183
John McCall424cec92011-01-19 06:33:43 +00003184 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3185 Decl->TypeForDecl = newType;
3186 Types.push_back(newType);
3187 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003188}
3189
John McCall81904512011-01-06 01:58:22 +00003190QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3191 QualType modifiedType,
3192 QualType equivalentType) {
3193 llvm::FoldingSetNodeID id;
3194 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3195
Craig Topper36250ad2014-05-12 05:36:57 +00003196 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003197 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3198 if (type) return QualType(type, 0);
3199
3200 QualType canon = getCanonicalType(equivalentType);
3201 type = new (*this, TypeAlignment)
3202 AttributedType(canon, attrKind, modifiedType, equivalentType);
3203
3204 Types.push_back(type);
3205 AttributedTypes.InsertNode(type, insertPos);
3206
3207 return QualType(type, 0);
3208}
3209
3210
John McCallcebee162009-10-18 09:09:24 +00003211/// \brief Retrieve a substitution-result type.
3212QualType
3213ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003214 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003215 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003216 && "replacement types must always be canonical");
3217
3218 llvm::FoldingSetNodeID ID;
3219 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003220 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003221 SubstTemplateTypeParmType *SubstParm
3222 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3223
3224 if (!SubstParm) {
3225 SubstParm = new (*this, TypeAlignment)
3226 SubstTemplateTypeParmType(Parm, Replacement);
3227 Types.push_back(SubstParm);
3228 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3229 }
3230
3231 return QualType(SubstParm, 0);
3232}
3233
Douglas Gregorada4b792011-01-14 02:55:32 +00003234/// \brief Retrieve a
3235QualType ASTContext::getSubstTemplateTypeParmPackType(
3236 const TemplateTypeParmType *Parm,
3237 const TemplateArgument &ArgPack) {
3238#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003239 for (const auto &P : ArgPack.pack_elements()) {
3240 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3241 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003242 }
3243#endif
3244
3245 llvm::FoldingSetNodeID ID;
3246 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003247 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003248 if (SubstTemplateTypeParmPackType *SubstParm
3249 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3250 return QualType(SubstParm, 0);
3251
3252 QualType Canon;
3253 if (!Parm->isCanonicalUnqualified()) {
3254 Canon = getCanonicalType(QualType(Parm, 0));
3255 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3256 ArgPack);
3257 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3258 }
3259
3260 SubstTemplateTypeParmPackType *SubstParm
3261 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3262 ArgPack);
3263 Types.push_back(SubstParm);
3264 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3265 return QualType(SubstParm, 0);
3266}
3267
Douglas Gregoreff93e02009-02-05 23:33:38 +00003268/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003269/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003270/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003271QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003272 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003273 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003274 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003275 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003276 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003277 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003278 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3279
3280 if (TypeParm)
3281 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003282
Chandler Carruth08836322011-05-01 00:51:33 +00003283 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003284 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003285 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003286
3287 TemplateTypeParmType *TypeCheck
3288 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3289 assert(!TypeCheck && "Template type parameter canonical type broken");
3290 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003291 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003292 TypeParm = new (*this, TypeAlignment)
3293 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003294
3295 Types.push_back(TypeParm);
3296 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3297
3298 return QualType(TypeParm, 0);
3299}
3300
John McCalle78aac42010-03-10 03:28:59 +00003301TypeSourceInfo *
3302ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3303 SourceLocation NameLoc,
3304 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003305 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003306 assert(!Name.getAsDependentTemplateName() &&
3307 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003308 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003309
3310 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003311 TemplateSpecializationTypeLoc TL =
3312 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003313 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003314 TL.setTemplateNameLoc(NameLoc);
3315 TL.setLAngleLoc(Args.getLAngleLoc());
3316 TL.setRAngleLoc(Args.getRAngleLoc());
3317 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3318 TL.setArgLocInfo(i, Args[i].getLocInfo());
3319 return DI;
3320}
3321
Mike Stump11289f42009-09-09 15:08:12 +00003322QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003323ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003324 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003325 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003326 assert(!Template.getAsDependentTemplateName() &&
3327 "No dependent template names here!");
3328
John McCall6b51f282009-11-23 01:53:49 +00003329 unsigned NumArgs = Args.size();
3330
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003331 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003332 ArgVec.reserve(NumArgs);
3333 for (unsigned i = 0; i != NumArgs; ++i)
3334 ArgVec.push_back(Args[i].getArgument());
3335
John McCall2408e322010-04-27 00:57:59 +00003336 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003337 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003338}
3339
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003340#ifndef NDEBUG
3341static bool hasAnyPackExpansions(const TemplateArgument *Args,
3342 unsigned NumArgs) {
3343 for (unsigned I = 0; I != NumArgs; ++I)
3344 if (Args[I].isPackExpansion())
3345 return true;
3346
3347 return true;
3348}
3349#endif
3350
John McCall0ad16662009-10-29 08:12:44 +00003351QualType
3352ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003353 const TemplateArgument *Args,
3354 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003355 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003356 assert(!Template.getAsDependentTemplateName() &&
3357 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003358 // Look through qualified template names.
3359 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3360 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003361
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003362 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003363 Template.getAsTemplateDecl() &&
3364 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003365 QualType CanonType;
3366 if (!Underlying.isNull())
3367 CanonType = getCanonicalType(Underlying);
3368 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003369 // We can get here with an alias template when the specialization contains
3370 // a pack expansion that does not match up with a parameter pack.
3371 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3372 "Caller must compute aliased type");
3373 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003374 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3375 NumArgs);
3376 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003377
Douglas Gregora8e02e72009-07-28 23:00:59 +00003378 // Allocate the (non-canonical) template specialization type, but don't
3379 // try to unique it: these types typically have location information that
3380 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003381 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3382 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003383 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003384 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003385 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003386 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3387 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003388
Douglas Gregor8bf42052009-02-09 18:46:07 +00003389 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003390 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003391}
3392
Mike Stump11289f42009-09-09 15:08:12 +00003393QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003394ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3395 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003396 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003397 assert(!Template.getAsDependentTemplateName() &&
3398 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003399
Douglas Gregore29139c2011-03-03 17:04:51 +00003400 // Look through qualified template names.
3401 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3402 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003403
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003404 // Build the canonical template specialization type.
3405 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003406 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003407 CanonArgs.reserve(NumArgs);
3408 for (unsigned I = 0; I != NumArgs; ++I)
3409 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3410
3411 // Determine whether this canonical template specialization type already
3412 // exists.
3413 llvm::FoldingSetNodeID ID;
3414 TemplateSpecializationType::Profile(ID, CanonTemplate,
3415 CanonArgs.data(), NumArgs, *this);
3416
Craig Topper36250ad2014-05-12 05:36:57 +00003417 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003418 TemplateSpecializationType *Spec
3419 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3420
3421 if (!Spec) {
3422 // Allocate a new canonical template specialization type.
3423 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3424 sizeof(TemplateArgument) * NumArgs),
3425 TypeAlignment);
3426 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3427 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003428 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003429 Types.push_back(Spec);
3430 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3431 }
3432
3433 assert(Spec->isDependentType() &&
3434 "Non-dependent template-id type must have a canonical type");
3435 return QualType(Spec, 0);
3436}
3437
3438QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003439ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3440 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003441 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003442 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003443 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003444
Craig Topper36250ad2014-05-12 05:36:57 +00003445 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003446 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003447 if (T)
3448 return QualType(T, 0);
3449
Douglas Gregorc42075a2010-02-04 18:10:26 +00003450 QualType Canon = NamedType;
3451 if (!Canon.isCanonical()) {
3452 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003453 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3454 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003455 (void)CheckT;
3456 }
3457
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003458 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003459 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003460 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003461 return QualType(T, 0);
3462}
3463
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003464QualType
Jay Foad39c79802011-01-12 09:06:06 +00003465ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003466 llvm::FoldingSetNodeID ID;
3467 ParenType::Profile(ID, InnerType);
3468
Craig Topper36250ad2014-05-12 05:36:57 +00003469 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003470 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3471 if (T)
3472 return QualType(T, 0);
3473
3474 QualType Canon = InnerType;
3475 if (!Canon.isCanonical()) {
3476 Canon = getCanonicalType(InnerType);
3477 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3478 assert(!CheckT && "Paren canonical type broken");
3479 (void)CheckT;
3480 }
3481
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003482 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003483 Types.push_back(T);
3484 ParenTypes.InsertNode(T, InsertPos);
3485 return QualType(T, 0);
3486}
3487
Douglas Gregor02085352010-03-31 20:19:30 +00003488QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3489 NestedNameSpecifier *NNS,
3490 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003491 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003492 if (Canon.isNull()) {
3493 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003494 ElaboratedTypeKeyword CanonKeyword = Keyword;
3495 if (Keyword == ETK_None)
3496 CanonKeyword = ETK_Typename;
3497
3498 if (CanonNNS != NNS || CanonKeyword != Keyword)
3499 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003500 }
3501
3502 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003503 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003504
Craig Topper36250ad2014-05-12 05:36:57 +00003505 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003506 DependentNameType *T
3507 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003508 if (T)
3509 return QualType(T, 0);
3510
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003511 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003512 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003513 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003514 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003515}
3516
Mike Stump11289f42009-09-09 15:08:12 +00003517QualType
John McCallc392f372010-06-11 00:33:02 +00003518ASTContext::getDependentTemplateSpecializationType(
3519 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003520 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003521 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003522 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003523 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003524 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003525 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3526 ArgCopy.push_back(Args[I].getArgument());
3527 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3528 ArgCopy.size(),
3529 ArgCopy.data());
3530}
3531
3532QualType
3533ASTContext::getDependentTemplateSpecializationType(
3534 ElaboratedTypeKeyword Keyword,
3535 NestedNameSpecifier *NNS,
3536 const IdentifierInfo *Name,
3537 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003538 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003539 assert((!NNS || NNS->isDependent()) &&
3540 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003541
Douglas Gregorc42075a2010-02-04 18:10:26 +00003542 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003543 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3544 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003545
Craig Topper36250ad2014-05-12 05:36:57 +00003546 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003547 DependentTemplateSpecializationType *T
3548 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003549 if (T)
3550 return QualType(T, 0);
3551
John McCallc392f372010-06-11 00:33:02 +00003552 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003553
John McCallc392f372010-06-11 00:33:02 +00003554 ElaboratedTypeKeyword CanonKeyword = Keyword;
3555 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3556
3557 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003558 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003559 for (unsigned I = 0; I != NumArgs; ++I) {
3560 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3561 if (!CanonArgs[I].structurallyEquals(Args[I]))
3562 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003563 }
3564
John McCallc392f372010-06-11 00:33:02 +00003565 QualType Canon;
3566 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3567 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3568 Name, NumArgs,
3569 CanonArgs.data());
3570
3571 // Find the insert position again.
3572 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3573 }
3574
3575 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3576 sizeof(TemplateArgument) * NumArgs),
3577 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003578 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003579 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003580 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003581 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003582 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003583}
3584
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003585QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003586 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003587 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003588 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003589
3590 assert(Pattern->containsUnexpandedParameterPack() &&
3591 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003592 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003593 PackExpansionType *T
3594 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3595 if (T)
3596 return QualType(T, 0);
3597
3598 QualType Canon;
3599 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003600 Canon = getCanonicalType(Pattern);
3601 // The canonical type might not contain an unexpanded parameter pack, if it
3602 // contains an alias template specialization which ignores one of its
3603 // parameters.
3604 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003605 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003606
Richard Smith68eea502012-07-16 00:20:35 +00003607 // Find the insert position again, in case we inserted an element into
3608 // PackExpansionTypes and invalidated our insert position.
3609 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3610 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003611 }
3612
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003613 T = new (*this, TypeAlignment)
3614 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003615 Types.push_back(T);
3616 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003617 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003618}
3619
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003620/// CmpProtocolNames - Comparison predicate for sorting protocols
3621/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003622static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3623 ObjCProtocolDecl *const *RHS) {
3624 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003625}
3626
John McCall8b07ec22010-05-15 11:32:37 +00003627static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003628 unsigned NumProtocols) {
3629 if (NumProtocols == 0) return true;
3630
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003631 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3632 return false;
3633
John McCallfc93cf92009-10-22 22:37:11 +00003634 for (unsigned i = 1; i != NumProtocols; ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003635 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003636 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003637 return false;
3638 return true;
3639}
3640
3641static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003642 unsigned &NumProtocols) {
3643 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003644
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003645 // Sort protocols, keyed by name.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003646 llvm::array_pod_sort(Protocols, ProtocolsEnd, CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003647
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003648 // Canonicalize.
3649 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3650 Protocols[I] = Protocols[I]->getCanonicalDecl();
3651
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003652 // Remove duplicates.
3653 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3654 NumProtocols = ProtocolsEnd-Protocols;
3655}
3656
John McCall8b07ec22010-05-15 11:32:37 +00003657QualType ASTContext::getObjCObjectType(QualType BaseType,
3658 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003659 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003660 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003661 llvm::makeArrayRef(Protocols, NumProtocols),
3662 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003663}
3664
3665QualType ASTContext::getObjCObjectType(
3666 QualType baseType,
3667 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003668 ArrayRef<ObjCProtocolDecl *> protocols,
3669 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003670 // If the base type is an interface and there aren't any protocols or
3671 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003672 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3673 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003674 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003675
3676 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003677 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003678 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003679 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003680 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3681 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003682
Douglas Gregore9d95f12015-07-07 03:57:35 +00003683 // Determine the type arguments to be used for canonicalization,
3684 // which may be explicitly specified here or written on the base
3685 // type.
3686 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3687 if (effectiveTypeArgs.empty()) {
3688 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3689 effectiveTypeArgs = baseObject->getTypeArgs();
3690 }
John McCallfc93cf92009-10-22 22:37:11 +00003691
Douglas Gregore9d95f12015-07-07 03:57:35 +00003692 // Build the canonical type, which has the canonical base type and a
3693 // sorted-and-uniqued list of protocols and the type arguments
3694 // canonicalized.
3695 QualType canonical;
3696 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3697 effectiveTypeArgs.end(),
3698 [&](QualType type) {
3699 return type.isCanonical();
3700 });
3701 bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3702 protocols.size());
3703 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3704 // Determine the canonical type arguments.
3705 ArrayRef<QualType> canonTypeArgs;
3706 SmallVector<QualType, 4> canonTypeArgsVec;
3707 if (!typeArgsAreCanonical) {
3708 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3709 for (auto typeArg : effectiveTypeArgs)
3710 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3711 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003712 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003713 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003714 }
3715
Douglas Gregore9d95f12015-07-07 03:57:35 +00003716 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3717 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3718 if (!protocolsSorted) {
3719 canonProtocolsVec.insert(canonProtocolsVec.begin(),
3720 protocols.begin(),
3721 protocols.end());
3722 unsigned uniqueCount = protocols.size();
3723 SortAndUniqueProtocols(&canonProtocolsVec[0], uniqueCount);
3724 canonProtocols = llvm::makeArrayRef(&canonProtocolsVec[0], uniqueCount);
3725 } else {
3726 canonProtocols = protocols;
3727 }
3728
3729 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003730 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003731
John McCallfc93cf92009-10-22 22:37:11 +00003732 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003733 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3734 }
3735
Douglas Gregore9d95f12015-07-07 03:57:35 +00003736 unsigned size = sizeof(ObjCObjectTypeImpl);
3737 size += typeArgs.size() * sizeof(QualType);
3738 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3739 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003740 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003741 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3742 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003743
3744 Types.push_back(T);
3745 ObjCObjectTypes.InsertNode(T, InsertPos);
3746 return QualType(T, 0);
3747}
3748
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003749/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3750/// protocol list adopt all protocols in QT's qualified-id protocol
3751/// list.
3752bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3753 ObjCInterfaceDecl *IC) {
3754 if (!QT->isObjCQualifiedIdType())
3755 return false;
3756
3757 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3758 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003759 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003760 if (!IC->ClassImplementsProtocol(Proto, false))
3761 return false;
3762 }
3763 return true;
3764 }
3765 return false;
3766}
3767
3768/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3769/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3770/// of protocols.
3771bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3772 ObjCInterfaceDecl *IDecl) {
3773 if (!QT->isObjCQualifiedIdType())
3774 return false;
3775 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3776 if (!OPT)
3777 return false;
3778 if (!IDecl->hasDefinition())
3779 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003780 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3781 CollectInheritedProtocols(IDecl, InheritedProtocols);
3782 if (InheritedProtocols.empty())
3783 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003784 // Check that if every protocol in list of id<plist> conforms to a protcol
3785 // of IDecl's, then bridge casting is ok.
3786 bool Conforms = false;
3787 for (auto *Proto : OPT->quals()) {
3788 Conforms = false;
3789 for (auto *PI : InheritedProtocols) {
3790 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3791 Conforms = true;
3792 break;
3793 }
3794 }
3795 if (!Conforms)
3796 break;
3797 }
3798 if (Conforms)
3799 return true;
3800
Aaron Ballman83731462014-03-17 16:14:00 +00003801 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003802 // If both the right and left sides have qualifiers.
3803 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003804 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003805 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003806 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003807 break;
3808 }
3809 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003810 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003811 }
3812 return true;
3813}
3814
John McCall8b07ec22010-05-15 11:32:37 +00003815/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3816/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003817QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003818 llvm::FoldingSetNodeID ID;
3819 ObjCObjectPointerType::Profile(ID, ObjectT);
3820
Craig Topper36250ad2014-05-12 05:36:57 +00003821 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003822 if (ObjCObjectPointerType *QT =
3823 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3824 return QualType(QT, 0);
3825
3826 // Find the canonical object type.
3827 QualType Canonical;
3828 if (!ObjectT.isCanonical()) {
3829 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3830
3831 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003832 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3833 }
3834
Douglas Gregorf85bee62010-02-08 22:59:26 +00003835 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003836 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3837 ObjCObjectPointerType *QType =
3838 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003839
Steve Narofffb4330f2009-06-17 22:40:22 +00003840 Types.push_back(QType);
3841 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003842 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003843}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003844
Douglas Gregor1c283312010-08-11 12:19:30 +00003845/// getObjCInterfaceType - Return the unique reference to the type for the
3846/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003847QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3848 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003849 if (Decl->TypeForDecl)
3850 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003851
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003852 if (PrevDecl) {
3853 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3854 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3855 return QualType(PrevDecl->TypeForDecl, 0);
3856 }
3857
Douglas Gregor7671e532011-12-16 16:34:57 +00003858 // Prefer the definition, if there is one.
3859 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3860 Decl = Def;
3861
Douglas Gregor1c283312010-08-11 12:19:30 +00003862 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3863 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3864 Decl->TypeForDecl = T;
3865 Types.push_back(T);
3866 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003867}
3868
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003869/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3870/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003871/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003872/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003873/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003874QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003875 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003876 if (tofExpr->isTypeDependent()) {
3877 llvm::FoldingSetNodeID ID;
3878 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003879
Craig Topper36250ad2014-05-12 05:36:57 +00003880 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003881 DependentTypeOfExprType *Canon
3882 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3883 if (Canon) {
3884 // We already have a "canonical" version of an identical, dependent
3885 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003886 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003887 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003888 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003889 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003890 Canon
3891 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003892 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3893 toe = Canon;
3894 }
3895 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003896 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003897 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003898 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003899 Types.push_back(toe);
3900 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003901}
3902
Steve Naroffa773cd52007-08-01 18:02:17 +00003903/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003904/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003905/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003906/// an issue. This doesn't affect the type checker, since it operates
3907/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003908QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003909 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003910 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003911 Types.push_back(tot);
3912 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003913}
3914
Anders Carlssonad6bd352009-06-24 21:24:56 +00003915
Richard Smith8eb1d322014-06-05 20:13:13 +00003916/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3917/// nodes. This would never be helpful, since each such type has its own
3918/// expression, and would not give a significant memory saving, since there
3919/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003920QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003921 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003922
3923 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003924 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003925 // unique dependent type. Two such decltype-specifiers refer to the same
3926 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003927 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003928 llvm::FoldingSetNodeID ID;
3929 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003930
Craig Topper36250ad2014-05-12 05:36:57 +00003931 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003932 DependentDecltypeType *Canon
3933 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003934 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003935 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003936 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003937 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003938 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003939 dt = new (*this, TypeAlignment)
3940 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003941 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003942 dt = new (*this, TypeAlignment)
3943 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003944 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003945 Types.push_back(dt);
3946 return QualType(dt, 0);
3947}
3948
Alexis Hunte852b102011-05-24 22:41:36 +00003949/// getUnaryTransformationType - We don't unique these, since the memory
3950/// savings are minimal and these are rare.
3951QualType ASTContext::getUnaryTransformType(QualType BaseType,
3952 QualType UnderlyingType,
3953 UnaryTransformType::UTTKind Kind)
3954 const {
3955 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003956 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3957 Kind,
3958 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003959 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003960 Types.push_back(Ty);
3961 return QualType(Ty, 0);
3962}
3963
Richard Smith2a7d4812013-05-04 07:00:32 +00003964/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3965/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3966/// canonical deduced-but-dependent 'auto' type.
3967QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003968 bool IsDependent) const {
3969 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003970 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003971
Richard Smith2a7d4812013-05-04 07:00:32 +00003972 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003973 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003974 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003975 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003976 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3977 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003978
Richard Smith74aeef52013-04-26 16:15:35 +00003979 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003980 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003981 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003982 Types.push_back(AT);
3983 if (InsertPos)
3984 AutoTypes.InsertNode(AT, InsertPos);
3985 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003986}
3987
Eli Friedman0dfb8892011-10-06 23:00:33 +00003988/// getAtomicType - Return the uniqued reference to the atomic type for
3989/// the given value type.
3990QualType ASTContext::getAtomicType(QualType T) const {
3991 // Unique pointers, to guarantee there is only one pointer of a particular
3992 // structure.
3993 llvm::FoldingSetNodeID ID;
3994 AtomicType::Profile(ID, T);
3995
Craig Topper36250ad2014-05-12 05:36:57 +00003996 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003997 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3998 return QualType(AT, 0);
3999
4000 // If the atomic value type isn't canonical, this won't be a canonical type
4001 // either, so fill in the canonical type field.
4002 QualType Canonical;
4003 if (!T.isCanonical()) {
4004 Canonical = getAtomicType(getCanonicalType(T));
4005
4006 // Get the new insert position for the node we care about.
4007 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004008 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004009 }
4010 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4011 Types.push_back(New);
4012 AtomicTypes.InsertNode(New, InsertPos);
4013 return QualType(New, 0);
4014}
4015
Richard Smith02e85f32011-04-14 22:09:26 +00004016/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4017QualType ASTContext::getAutoDeductType() const {
4018 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004019 AutoDeductTy = QualType(
4020 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004021 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004022 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004023 return AutoDeductTy;
4024}
4025
4026/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4027QualType ASTContext::getAutoRRefDeductType() const {
4028 if (AutoRRefDeductTy.isNull())
4029 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4030 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4031 return AutoRRefDeductTy;
4032}
4033
Chris Lattnerfb072462007-01-23 05:45:31 +00004034/// getTagDeclType - Return the unique reference to the type for the
4035/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004036QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004037 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004038 // FIXME: What is the design on getTagDeclType when it requires casting
4039 // away const? mutable?
4040 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004041}
4042
Mike Stump11289f42009-09-09 15:08:12 +00004043/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4044/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4045/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004046CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004047 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004048}
Chris Lattnerfb072462007-01-23 05:45:31 +00004049
Hans Wennborg27541db2011-10-27 08:29:09 +00004050/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4051CanQualType ASTContext::getIntMaxType() const {
4052 return getFromTargetType(Target->getIntMaxType());
4053}
4054
4055/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4056CanQualType ASTContext::getUIntMaxType() const {
4057 return getFromTargetType(Target->getUIntMaxType());
4058}
4059
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004060/// getSignedWCharType - Return the type of "signed wchar_t".
4061/// Used when in C++, as a GCC extension.
4062QualType ASTContext::getSignedWCharType() const {
4063 // FIXME: derive from "Target" ?
4064 return WCharTy;
4065}
4066
4067/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4068/// Used when in C++, as a GCC extension.
4069QualType ASTContext::getUnsignedWCharType() const {
4070 // FIXME: derive from "Target" ?
4071 return UnsignedIntTy;
4072}
4073
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004074QualType ASTContext::getIntPtrType() const {
4075 return getFromTargetType(Target->getIntPtrType());
4076}
4077
4078QualType ASTContext::getUIntPtrType() const {
4079 return getCorrespondingUnsignedType(getIntPtrType());
4080}
4081
Hans Wennborg27541db2011-10-27 08:29:09 +00004082/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004083/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4084QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004085 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004086}
4087
Eli Friedman4e91899e2012-11-27 02:58:24 +00004088/// \brief Return the unique type for "pid_t" defined in
4089/// <sys/types.h>. We need this to compute the correct type for vfork().
4090QualType ASTContext::getProcessIDType() const {
4091 return getFromTargetType(Target->getProcessIDType());
4092}
4093
Chris Lattnera21ad802008-04-02 05:18:44 +00004094//===----------------------------------------------------------------------===//
4095// Type Operators
4096//===----------------------------------------------------------------------===//
4097
Jay Foad39c79802011-01-12 09:06:06 +00004098CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004099 // Push qualifiers into arrays, and then discard any remaining
4100 // qualifiers.
4101 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004102 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004103 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004104 QualType Result;
4105 if (isa<ArrayType>(Ty)) {
4106 Result = getArrayDecayedType(QualType(Ty,0));
4107 } else if (isa<FunctionType>(Ty)) {
4108 Result = getPointerType(QualType(Ty, 0));
4109 } else {
4110 Result = QualType(Ty, 0);
4111 }
4112
4113 return CanQualType::CreateUnsafe(Result);
4114}
4115
John McCall6c9dd522011-01-18 07:41:22 +00004116QualType ASTContext::getUnqualifiedArrayType(QualType type,
4117 Qualifiers &quals) {
4118 SplitQualType splitType = type.getSplitUnqualifiedType();
4119
4120 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4121 // the unqualified desugared type and then drops it on the floor.
4122 // We then have to strip that sugar back off with
4123 // getUnqualifiedDesugaredType(), which is silly.
4124 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004125 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004126
4127 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004128 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004129 quals = splitType.Quals;
4130 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004131 }
4132
John McCall6c9dd522011-01-18 07:41:22 +00004133 // Otherwise, recurse on the array's element type.
4134 QualType elementType = AT->getElementType();
4135 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4136
4137 // If that didn't change the element type, AT has no qualifiers, so we
4138 // can just use the results in splitType.
4139 if (elementType == unqualElementType) {
4140 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004141 quals = splitType.Quals;
4142 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004143 }
4144
4145 // Otherwise, add in the qualifiers from the outermost type, then
4146 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004147 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004148
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004149 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004150 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004151 CAT->getSizeModifier(), 0);
4152 }
4153
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004154 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004155 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004156 }
4157
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004158 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004159 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004160 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004161 VAT->getSizeModifier(),
4162 VAT->getIndexTypeCVRQualifiers(),
4163 VAT->getBracketsRange());
4164 }
4165
4166 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004167 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004168 DSAT->getSizeModifier(), 0,
4169 SourceRange());
4170}
4171
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004172/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4173/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4174/// they point to and return true. If T1 and T2 aren't pointer types
4175/// or pointer-to-member types, or if they are not similar at this
4176/// level, returns false and leaves T1 and T2 unchanged. Top-level
4177/// qualifiers on T1 and T2 are ignored. This function will typically
4178/// be called in a loop that successively "unwraps" pointer and
4179/// pointer-to-member types to compare them at each level.
4180bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4181 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4182 *T2PtrType = T2->getAs<PointerType>();
4183 if (T1PtrType && T2PtrType) {
4184 T1 = T1PtrType->getPointeeType();
4185 T2 = T2PtrType->getPointeeType();
4186 return true;
4187 }
4188
4189 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4190 *T2MPType = T2->getAs<MemberPointerType>();
4191 if (T1MPType && T2MPType &&
4192 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4193 QualType(T2MPType->getClass(), 0))) {
4194 T1 = T1MPType->getPointeeType();
4195 T2 = T2MPType->getPointeeType();
4196 return true;
4197 }
4198
David Blaikiebbafb8a2012-03-11 07:00:24 +00004199 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004200 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4201 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4202 if (T1OPType && T2OPType) {
4203 T1 = T1OPType->getPointeeType();
4204 T2 = T2OPType->getPointeeType();
4205 return true;
4206 }
4207 }
4208
4209 // FIXME: Block pointers, too?
4210
4211 return false;
4212}
4213
Jay Foad39c79802011-01-12 09:06:06 +00004214DeclarationNameInfo
4215ASTContext::getNameForTemplate(TemplateName Name,
4216 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004217 switch (Name.getKind()) {
4218 case TemplateName::QualifiedTemplate:
4219 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004220 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004221 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4222 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004223
John McCalld9dfe3a2011-06-30 08:33:18 +00004224 case TemplateName::OverloadedTemplate: {
4225 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4226 // DNInfo work in progress: CHECKME: what about DNLoc?
4227 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4228 }
4229
4230 case TemplateName::DependentTemplate: {
4231 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004232 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004233 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004234 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4235 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004236 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004237 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4238 // DNInfo work in progress: FIXME: source locations?
4239 DeclarationNameLoc DNLoc;
4240 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4241 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4242 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004243 }
4244 }
4245
John McCalld9dfe3a2011-06-30 08:33:18 +00004246 case TemplateName::SubstTemplateTemplateParm: {
4247 SubstTemplateTemplateParmStorage *subst
4248 = Name.getAsSubstTemplateTemplateParm();
4249 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4250 NameLoc);
4251 }
4252
4253 case TemplateName::SubstTemplateTemplateParmPack: {
4254 SubstTemplateTemplateParmPackStorage *subst
4255 = Name.getAsSubstTemplateTemplateParmPack();
4256 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4257 NameLoc);
4258 }
4259 }
4260
4261 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004262}
4263
Jay Foad39c79802011-01-12 09:06:06 +00004264TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004265 switch (Name.getKind()) {
4266 case TemplateName::QualifiedTemplate:
4267 case TemplateName::Template: {
4268 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004269 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004270 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004271 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4272
4273 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004274 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004275 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004276
John McCalld9dfe3a2011-06-30 08:33:18 +00004277 case TemplateName::OverloadedTemplate:
4278 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004279
John McCalld9dfe3a2011-06-30 08:33:18 +00004280 case TemplateName::DependentTemplate: {
4281 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4282 assert(DTN && "Non-dependent template names must refer to template decls.");
4283 return DTN->CanonicalTemplateName;
4284 }
4285
4286 case TemplateName::SubstTemplateTemplateParm: {
4287 SubstTemplateTemplateParmStorage *subst
4288 = Name.getAsSubstTemplateTemplateParm();
4289 return getCanonicalTemplateName(subst->getReplacement());
4290 }
4291
4292 case TemplateName::SubstTemplateTemplateParmPack: {
4293 SubstTemplateTemplateParmPackStorage *subst
4294 = Name.getAsSubstTemplateTemplateParmPack();
4295 TemplateTemplateParmDecl *canonParameter
4296 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4297 TemplateArgument canonArgPack
4298 = getCanonicalTemplateArgument(subst->getArgumentPack());
4299 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4300 }
4301 }
4302
4303 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004304}
4305
Douglas Gregoradee3e32009-11-11 23:06:43 +00004306bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4307 X = getCanonicalTemplateName(X);
4308 Y = getCanonicalTemplateName(Y);
4309 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4310}
4311
Mike Stump11289f42009-09-09 15:08:12 +00004312TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004313ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004314 switch (Arg.getKind()) {
4315 case TemplateArgument::Null:
4316 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004317
Douglas Gregora8e02e72009-07-28 23:00:59 +00004318 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004319 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004320
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004321 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004322 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004323 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004324 }
Mike Stump11289f42009-09-09 15:08:12 +00004325
Eli Friedmanb826a002012-09-26 02:36:12 +00004326 case TemplateArgument::NullPtr:
4327 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4328 /*isNullPtr*/true);
4329
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004330 case TemplateArgument::Template:
4331 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004332
4333 case TemplateArgument::TemplateExpansion:
4334 return TemplateArgument(getCanonicalTemplateName(
4335 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004336 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004337
Douglas Gregora8e02e72009-07-28 23:00:59 +00004338 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004339 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004340
Douglas Gregora8e02e72009-07-28 23:00:59 +00004341 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004342 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004343
Douglas Gregora8e02e72009-07-28 23:00:59 +00004344 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004345 if (Arg.pack_size() == 0)
4346 return Arg;
4347
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004348 TemplateArgument *CanonArgs
4349 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004350 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004351 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004352 AEnd = Arg.pack_end();
4353 A != AEnd; (void)++A, ++Idx)
4354 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004355
Benjamin Kramercce63472015-08-05 09:40:22 +00004356 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004357 }
4358 }
4359
4360 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004361 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004362}
4363
Douglas Gregor333489b2009-03-27 23:10:48 +00004364NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004365ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004366 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004367 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004368
4369 switch (NNS->getKind()) {
4370 case NestedNameSpecifier::Identifier:
4371 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004372 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004373 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4374 NNS->getAsIdentifier());
4375
4376 case NestedNameSpecifier::Namespace:
4377 // A namespace is canonical; build a nested-name-specifier with
4378 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004379 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004380 NNS->getAsNamespace()->getOriginalNamespace());
4381
4382 case NestedNameSpecifier::NamespaceAlias:
4383 // A namespace is canonical; build a nested-name-specifier with
4384 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004385 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004386 NNS->getAsNamespaceAlias()->getNamespace()
4387 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004388
4389 case NestedNameSpecifier::TypeSpec:
4390 case NestedNameSpecifier::TypeSpecWithTemplate: {
4391 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004392
4393 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4394 // break it apart into its prefix and identifier, then reconsititute those
4395 // as the canonical nested-name-specifier. This is required to canonicalize
4396 // a dependent nested-name-specifier involving typedefs of dependent-name
4397 // types, e.g.,
4398 // typedef typename T::type T1;
4399 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004400 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4401 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004402 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004403
Eli Friedman5358a0a2012-03-03 04:09:56 +00004404 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4405 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4406 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004407 return NestedNameSpecifier::Create(*this, nullptr, false,
4408 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004409 }
4410
4411 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004412 case NestedNameSpecifier::Super:
4413 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004414 return NNS;
4415 }
4416
David Blaikie8a40f702012-01-17 06:56:22 +00004417 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004418}
4419
Chris Lattner7adf0762008-08-04 07:31:14 +00004420
Jay Foad39c79802011-01-12 09:06:06 +00004421const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004422 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004423 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004424 // Handle the common positive case fast.
4425 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4426 return AT;
4427 }
Mike Stump11289f42009-09-09 15:08:12 +00004428
John McCall8ccfcb52009-09-24 19:53:00 +00004429 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004430 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004431 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004432
John McCall8ccfcb52009-09-24 19:53:00 +00004433 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004434 // implements C99 6.7.3p8: "If the specification of an array type includes
4435 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004436
Chris Lattner7adf0762008-08-04 07:31:14 +00004437 // If we get here, we either have type qualifiers on the type, or we have
4438 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004439 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004440
John McCall33ddac02011-01-19 10:06:00 +00004441 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004442 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004443
Chris Lattner7adf0762008-08-04 07:31:14 +00004444 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004445 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004446 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004447 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004448
Chris Lattner7adf0762008-08-04 07:31:14 +00004449 // Otherwise, we have an array and we have qualifiers on it. Push the
4450 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004451 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004452
Chris Lattner7adf0762008-08-04 07:31:14 +00004453 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4454 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4455 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004456 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004457 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4458 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4459 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004460 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004461
Mike Stump11289f42009-09-09 15:08:12 +00004462 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004463 = dyn_cast<DependentSizedArrayType>(ATy))
4464 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004465 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004466 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004467 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004468 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004469 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004470
Chris Lattner7adf0762008-08-04 07:31:14 +00004471 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004472 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004473 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004474 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004475 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004476 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004477}
4478
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004479QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004480 if (T->isArrayType() || T->isFunctionType())
4481 return getDecayedType(T);
4482 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004483}
4484
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004485QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004486 T = getVariableArrayDecayedType(T);
4487 T = getAdjustedParameterType(T);
4488 return T.getUnqualifiedType();
4489}
4490
David Majnemerd09a51c2015-03-03 01:50:05 +00004491QualType ASTContext::getExceptionObjectType(QualType T) const {
4492 // C++ [except.throw]p3:
4493 // A throw-expression initializes a temporary object, called the exception
4494 // object, the type of which is determined by removing any top-level
4495 // cv-qualifiers from the static type of the operand of throw and adjusting
4496 // the type from "array of T" or "function returning T" to "pointer to T"
4497 // or "pointer to function returning T", [...]
4498 T = getVariableArrayDecayedType(T);
4499 if (T->isArrayType() || T->isFunctionType())
4500 T = getDecayedType(T);
4501 return T.getUnqualifiedType();
4502}
4503
Chris Lattnera21ad802008-04-02 05:18:44 +00004504/// getArrayDecayedType - Return the properly qualified result of decaying the
4505/// specified array type to a pointer. This operation is non-trivial when
4506/// handling typedefs etc. The canonical type of "T" must be an array type,
4507/// this returns a pointer to a properly qualified element of the array.
4508///
4509/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004510QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004511 // Get the element type with 'getAsArrayType' so that we don't lose any
4512 // typedefs in the element type of the array. This also handles propagation
4513 // of type qualifiers from the array type into the element type if present
4514 // (C99 6.7.3p8).
4515 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4516 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004517
Chris Lattner7adf0762008-08-04 07:31:14 +00004518 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004519
4520 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004521 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004522}
4523
John McCall33ddac02011-01-19 10:06:00 +00004524QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4525 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004526}
4527
John McCall33ddac02011-01-19 10:06:00 +00004528QualType ASTContext::getBaseElementType(QualType type) const {
4529 Qualifiers qs;
4530 while (true) {
4531 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004532 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004533 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004534
John McCall33ddac02011-01-19 10:06:00 +00004535 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004536 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004537 }
Mike Stump11289f42009-09-09 15:08:12 +00004538
John McCall33ddac02011-01-19 10:06:00 +00004539 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004540}
4541
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004542/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004543uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004544ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4545 uint64_t ElementCount = 1;
4546 do {
4547 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004548 CA = dyn_cast_or_null<ConstantArrayType>(
4549 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004550 } while (CA);
4551 return ElementCount;
4552}
4553
Steve Naroff0af91202007-04-27 21:51:21 +00004554/// getFloatingRank - Return a relative rank for floating point types.
4555/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004556static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004557 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004558 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004559
John McCall9dd450b2009-09-21 23:43:11 +00004560 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4561 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004562 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004563 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004564 case BuiltinType::Float: return FloatRank;
4565 case BuiltinType::Double: return DoubleRank;
4566 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004567 }
4568}
4569
Mike Stump11289f42009-09-09 15:08:12 +00004570/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4571/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004572/// 'typeDomain' is a real floating point or complex type.
4573/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004574QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4575 QualType Domain) const {
4576 FloatingRank EltRank = getFloatingRank(Size);
4577 if (Domain->isComplexType()) {
4578 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004579 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004580 case FloatRank: return FloatComplexTy;
4581 case DoubleRank: return DoubleComplexTy;
4582 case LongDoubleRank: return LongDoubleComplexTy;
4583 }
Steve Naroff0af91202007-04-27 21:51:21 +00004584 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004585
4586 assert(Domain->isRealFloatingType() && "Unknown domain!");
4587 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004588 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004589 case FloatRank: return FloatTy;
4590 case DoubleRank: return DoubleTy;
4591 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004592 }
David Blaikief47fa302012-01-17 02:30:50 +00004593 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004594}
4595
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004596/// getFloatingTypeOrder - Compare the rank of the two specified floating
4597/// point types, ignoring the domain of the type (i.e. 'double' ==
4598/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004599/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004600int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004601 FloatingRank LHSR = getFloatingRank(LHS);
4602 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004603
Chris Lattnerb90739d2008-04-06 23:38:49 +00004604 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004605 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004606 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004607 return 1;
4608 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004609}
4610
Chris Lattner76a00cf2008-04-06 22:59:24 +00004611/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4612/// routine will assert if passed a built-in type that isn't an integer or enum,
4613/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004614unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004615 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004616
Chris Lattner76a00cf2008-04-06 22:59:24 +00004617 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004618 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004619 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004620 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004621 case BuiltinType::Char_S:
4622 case BuiltinType::Char_U:
4623 case BuiltinType::SChar:
4624 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004625 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004626 case BuiltinType::Short:
4627 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004628 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004629 case BuiltinType::Int:
4630 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004631 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004632 case BuiltinType::Long:
4633 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004634 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004635 case BuiltinType::LongLong:
4636 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004637 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004638 case BuiltinType::Int128:
4639 case BuiltinType::UInt128:
4640 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004641 }
4642}
4643
Eli Friedman629ffb92009-08-20 04:21:42 +00004644/// \brief Whether this is a promotable bitfield reference according
4645/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4646///
4647/// \returns the type this bit-field will promote to, or NULL if no
4648/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004649QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004650 if (E->isTypeDependent() || E->isValueDependent())
4651 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004652
4653 // FIXME: We should not do this unless E->refersToBitField() is true. This
4654 // matters in C where getSourceBitField() will find bit-fields for various
4655 // cases where the source expression is not a bit-field designator.
4656
John McCalld25db7e2013-05-06 21:39:12 +00004657 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004658 if (!Field)
4659 return QualType();
4660
4661 QualType FT = Field->getType();
4662
Richard Smithcaf33902011-10-10 18:28:20 +00004663 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004664 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004665 // C++ [conv.prom]p5:
4666 // A prvalue for an integral bit-field can be converted to a prvalue of type
4667 // int if int can represent all the values of the bit-field; otherwise, it
4668 // can be converted to unsigned int if unsigned int can represent all the
4669 // values of the bit-field. If the bit-field is larger yet, no integral
4670 // promotion applies to it.
4671 // C11 6.3.1.1/2:
4672 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4673 // If an int can represent all values of the original type (as restricted by
4674 // the width, for a bit-field), the value is converted to an int; otherwise,
4675 // it is converted to an unsigned int.
4676 //
4677 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4678 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004679 if (BitWidth < IntSize)
4680 return IntTy;
4681
4682 if (BitWidth == IntSize)
4683 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4684
4685 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004686 // like the base type. GCC has some weird bugs in this area that we
4687 // deliberately do not follow (GCC follows a pre-standard resolution to
4688 // C's DR315 which treats bit-width as being part of the type, and this leaks
4689 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004690 return QualType();
4691}
4692
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004693/// getPromotedIntegerType - Returns the type that Promotable will
4694/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4695/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004696QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004697 assert(!Promotable.isNull());
4698 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004699 if (const EnumType *ET = Promotable->getAs<EnumType>())
4700 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004701
4702 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4703 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4704 // (3.9.1) can be converted to a prvalue of the first of the following
4705 // types that can represent all the values of its underlying type:
4706 // int, unsigned int, long int, unsigned long int, long long int, or
4707 // unsigned long long int [...]
4708 // FIXME: Is there some better way to compute this?
4709 if (BT->getKind() == BuiltinType::WChar_S ||
4710 BT->getKind() == BuiltinType::WChar_U ||
4711 BT->getKind() == BuiltinType::Char16 ||
4712 BT->getKind() == BuiltinType::Char32) {
4713 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4714 uint64_t FromSize = getTypeSize(BT);
4715 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4716 LongLongTy, UnsignedLongLongTy };
4717 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4718 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4719 if (FromSize < ToSize ||
4720 (FromSize == ToSize &&
4721 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4722 return PromoteTypes[Idx];
4723 }
4724 llvm_unreachable("char type should fit into long long");
4725 }
4726 }
4727
4728 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004729 if (Promotable->isSignedIntegerType())
4730 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004731 uint64_t PromotableSize = getIntWidth(Promotable);
4732 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004733 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4734 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4735}
4736
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004737/// \brief Recurses in pointer/array types until it finds an objc retainable
4738/// type and returns its ownership.
4739Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4740 while (!T.isNull()) {
4741 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4742 return T.getObjCLifetime();
4743 if (T->isArrayType())
4744 T = getBaseElementType(T);
4745 else if (const PointerType *PT = T->getAs<PointerType>())
4746 T = PT->getPointeeType();
4747 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004748 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004749 else
4750 break;
4751 }
4752
4753 return Qualifiers::OCL_None;
4754}
4755
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004756static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4757 // Incomplete enum types are not treated as integer types.
4758 // FIXME: In C++, enum types are never integer types.
4759 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4760 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004761 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004762}
4763
Mike Stump11289f42009-09-09 15:08:12 +00004764/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004765/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004766/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004767int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004768 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4769 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004770
4771 // Unwrap enums to their underlying type.
4772 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4773 LHSC = getIntegerTypeForEnum(ET);
4774 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4775 RHSC = getIntegerTypeForEnum(ET);
4776
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004777 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004778
Chris Lattner76a00cf2008-04-06 22:59:24 +00004779 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4780 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004781
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004782 unsigned LHSRank = getIntegerRank(LHSC);
4783 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004784
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004785 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4786 if (LHSRank == RHSRank) return 0;
4787 return LHSRank > RHSRank ? 1 : -1;
4788 }
Mike Stump11289f42009-09-09 15:08:12 +00004789
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004790 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4791 if (LHSUnsigned) {
4792 // If the unsigned [LHS] type is larger, return it.
4793 if (LHSRank >= RHSRank)
4794 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004795
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004796 // If the signed type can represent all values of the unsigned type, it
4797 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004798 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004799 return -1;
4800 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004801
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004802 // If the unsigned [RHS] type is larger, return it.
4803 if (RHSRank >= LHSRank)
4804 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004805
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004806 // If the signed type can represent all values of the unsigned type, it
4807 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004808 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004809 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004810}
Anders Carlsson98f07902007-08-17 05:31:46 +00004811
Mike Stump11289f42009-09-09 15:08:12 +00004812// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004813QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004814 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004815 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004816 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004817
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004818 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004819
Anders Carlsson98f07902007-08-17 05:31:46 +00004820 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004821 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004822 // int flags;
4823 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004824 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004825 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004826 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004827 FieldTypes[3] = LongTy;
4828
Anders Carlsson98f07902007-08-17 05:31:46 +00004829 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004830 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004831 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004832 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004833 SourceLocation(), nullptr,
4834 FieldTypes[i], /*TInfo=*/nullptr,
4835 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004836 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004837 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004838 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004839 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004840 }
4841
Douglas Gregord5058122010-02-11 01:19:42 +00004842 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004843 }
Mike Stump11289f42009-09-09 15:08:12 +00004844
Anders Carlsson98f07902007-08-17 05:31:46 +00004845 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004846}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004847
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004848QualType ASTContext::getObjCSuperType() const {
4849 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004850 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004851 TUDecl->addDecl(ObjCSuperTypeDecl);
4852 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4853 }
4854 return ObjCSuperType;
4855}
4856
Douglas Gregor512b0772009-04-23 22:29:11 +00004857void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004858 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004859 assert(Rec && "Invalid CFConstantStringType");
4860 CFConstantStringTypeDecl = Rec->getDecl();
4861}
4862
Jay Foad39c79802011-01-12 09:06:06 +00004863QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004864 if (BlockDescriptorType)
4865 return getTagDeclType(BlockDescriptorType);
4866
Alp Toker2dea15b2013-12-17 01:22:38 +00004867 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004868 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004869 RD = buildImplicitRecord("__block_descriptor");
4870 RD->startDefinition();
4871
Mike Stumpd0153282009-10-20 02:12:22 +00004872 QualType FieldTypes[] = {
4873 UnsignedLongTy,
4874 UnsignedLongTy,
4875 };
4876
Craig Topperd6d31ac2013-07-15 08:24:27 +00004877 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004878 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004879 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004880 };
4881
4882 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004883 FieldDecl *Field = FieldDecl::Create(
4884 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004885 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4886 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004887 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004888 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004889 }
4890
Alp Toker2dea15b2013-12-17 01:22:38 +00004891 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004892
Alp Toker2dea15b2013-12-17 01:22:38 +00004893 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004894
4895 return getTagDeclType(BlockDescriptorType);
4896}
4897
Jay Foad39c79802011-01-12 09:06:06 +00004898QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004899 if (BlockDescriptorExtendedType)
4900 return getTagDeclType(BlockDescriptorExtendedType);
4901
Alp Toker2dea15b2013-12-17 01:22:38 +00004902 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004903 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004904 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4905 RD->startDefinition();
4906
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004907 QualType FieldTypes[] = {
4908 UnsignedLongTy,
4909 UnsignedLongTy,
4910 getPointerType(VoidPtrTy),
4911 getPointerType(VoidPtrTy)
4912 };
4913
Craig Topperd6d31ac2013-07-15 08:24:27 +00004914 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004915 "reserved",
4916 "Size",
4917 "CopyFuncPtr",
4918 "DestroyFuncPtr"
4919 };
4920
4921 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004922 FieldDecl *Field = FieldDecl::Create(
4923 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004924 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4925 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004926 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004927 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004928 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004929 }
4930
Alp Toker2dea15b2013-12-17 01:22:38 +00004931 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004932
Alp Toker2dea15b2013-12-17 01:22:38 +00004933 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004934 return getTagDeclType(BlockDescriptorExtendedType);
4935}
4936
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004937/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4938/// requires copy/dispose. Note that this must match the logic
4939/// in buildByrefHelpers.
4940bool ASTContext::BlockRequiresCopying(QualType Ty,
4941 const VarDecl *D) {
4942 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4943 const Expr *copyExpr = getBlockVarCopyInits(D);
4944 if (!copyExpr && record->hasTrivialDestructor()) return false;
4945
Mike Stump94967902009-10-21 18:16:27 +00004946 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004947 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004948
4949 if (!Ty->isObjCRetainableType()) return false;
4950
4951 Qualifiers qs = Ty.getQualifiers();
4952
4953 // If we have lifetime, that dominates.
4954 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4955 assert(getLangOpts().ObjCAutoRefCount);
4956
4957 switch (lifetime) {
4958 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4959
4960 // These are just bits as far as the runtime is concerned.
4961 case Qualifiers::OCL_ExplicitNone:
4962 case Qualifiers::OCL_Autoreleasing:
4963 return false;
4964
4965 // Tell the runtime that this is ARC __weak, called by the
4966 // byref routines.
4967 case Qualifiers::OCL_Weak:
4968 // ARC __strong __block variables need to be retained.
4969 case Qualifiers::OCL_Strong:
4970 return true;
4971 }
4972 llvm_unreachable("fell out of lifetime switch!");
4973 }
4974 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4975 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004976}
4977
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004978bool ASTContext::getByrefLifetime(QualType Ty,
4979 Qualifiers::ObjCLifetime &LifeTime,
4980 bool &HasByrefExtendedLayout) const {
4981
4982 if (!getLangOpts().ObjC1 ||
4983 getLangOpts().getGC() != LangOptions::NonGC)
4984 return false;
4985
4986 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004987 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004988 HasByrefExtendedLayout = true;
4989 LifeTime = Qualifiers::OCL_None;
4990 }
4991 else if (getLangOpts().ObjCAutoRefCount)
4992 LifeTime = Ty.getObjCLifetime();
4993 // MRR.
4994 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4995 LifeTime = Qualifiers::OCL_ExplicitNone;
4996 else
4997 LifeTime = Qualifiers::OCL_None;
4998 return true;
4999}
5000
Douglas Gregorbab8a962011-09-08 01:46:34 +00005001TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5002 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005003 ObjCInstanceTypeDecl =
5004 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005005 return ObjCInstanceTypeDecl;
5006}
5007
Anders Carlsson18acd442007-10-29 06:33:42 +00005008// This returns true if a type has been typedefed to BOOL:
5009// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005010static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005011 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005012 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5013 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005014
Anders Carlssond8499822007-10-29 05:01:08 +00005015 return false;
5016}
5017
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005018/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005019/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005020CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005021 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5022 return CharUnits::Zero();
5023
Ken Dyck40775002010-01-11 17:06:35 +00005024 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005025
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005026 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005027 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005028 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005029 // Treat arrays as pointers, since that's how they're passed in.
5030 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005031 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005032 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005033}
5034
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005035bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
5036 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
5037 VD->getType()->isIntegralOrEnumerationType() &&
Alexey Bataev15413ea2015-05-20 11:57:02 +00005038 VD->isFirstDecl() && !VD->isOutOfLine() && VD->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005039}
5040
Ken Dyck40775002010-01-11 17:06:35 +00005041static inline
5042std::string charUnitsToString(const CharUnits &CU) {
5043 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005044}
5045
John McCall351762c2011-02-07 10:33:21 +00005046/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005047/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005048std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5049 std::string S;
5050
David Chisnall950a9512009-11-17 19:33:30 +00005051 const BlockDecl *Decl = Expr->getBlockDecl();
5052 QualType BlockTy =
5053 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5054 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005055 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005056 getObjCEncodingForMethodParameter(
5057 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5058 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005059 else
Alp Toker314cc812014-01-25 16:55:45 +00005060 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005061 // Compute size of all parameters.
5062 // Start with computing size of a pointer in number of bytes.
5063 // FIXME: There might(should) be a better way of doing this computation!
5064 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005065 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5066 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005067 for (auto PI : Decl->params()) {
5068 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005069 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005070 if (sz.isZero())
5071 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005072 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005073 ParmOffset += sz;
5074 }
5075 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005076 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005077 // Block pointer and offset.
5078 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005079
5080 // Argument types.
5081 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005082 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00005083 QualType PType = PVDecl->getOriginalType();
5084 if (const ArrayType *AT =
5085 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5086 // Use array's original type only if it has known number of
5087 // elements.
5088 if (!isa<ConstantArrayType>(AT))
5089 PType = PVDecl->getType();
5090 } else if (PType->isFunctionType())
5091 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005092 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005093 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5094 S, true /*Extended*/);
5095 else
5096 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005097 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005098 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005099 }
John McCall351762c2011-02-07 10:33:21 +00005100
5101 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005102}
5103
Douglas Gregora9d84932011-05-27 01:19:52 +00005104bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005105 std::string& S) {
5106 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005107 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005108 CharUnits ParmOffset;
5109 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005110 for (auto PI : Decl->params()) {
5111 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005112 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005113 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005114 continue;
5115
David Chisnall50e4eba2010-12-30 14:05:53 +00005116 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005117 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005118 ParmOffset += sz;
5119 }
5120 S += charUnitsToString(ParmOffset);
5121 ParmOffset = CharUnits::Zero();
5122
5123 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005124 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005125 QualType PType = PVDecl->getOriginalType();
5126 if (const ArrayType *AT =
5127 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5128 // Use array's original type only if it has known number of
5129 // elements.
5130 if (!isa<ConstantArrayType>(AT))
5131 PType = PVDecl->getType();
5132 } else if (PType->isFunctionType())
5133 PType = PVDecl->getType();
5134 getObjCEncodingForType(PType, S);
5135 S += charUnitsToString(ParmOffset);
5136 ParmOffset += getObjCEncodingTypeSize(PType);
5137 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005138
5139 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005140}
5141
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005142/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5143/// method parameter or return type. If Extended, include class names and
5144/// block object types.
5145void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5146 QualType T, std::string& S,
5147 bool Extended) const {
5148 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5149 getObjCEncodingForTypeQualifier(QT, S);
5150 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005151 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005152 true /*OutermostType*/,
5153 false /*EncodingProperty*/,
5154 false /*StructField*/,
5155 Extended /*EncodeBlockParameters*/,
5156 Extended /*EncodeClassNames*/);
5157}
5158
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005159/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005160/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005161bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005162 std::string& S,
5163 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005164 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005165 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005166 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5167 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005168 // Compute size of all parameters.
5169 // Start with computing size of a pointer in number of bytes.
5170 // FIXME: There might(should) be a better way of doing this computation!
5171 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005172 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005173 // The first two arguments (self and _cmd) are pointers; account for
5174 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005175 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005176 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005177 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005178 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005179 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005180 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005181 continue;
5182
Ken Dyck40775002010-01-11 17:06:35 +00005183 assert (sz.isPositive() &&
5184 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005185 ParmOffset += sz;
5186 }
Ken Dyck40775002010-01-11 17:06:35 +00005187 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005188 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005189 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005190
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005191 // Argument types.
5192 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005193 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005194 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005195 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005196 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005197 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005198 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5199 // Use array's original type only if it has known number of
5200 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005201 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005202 PType = PVDecl->getType();
5203 } else if (PType->isFunctionType())
5204 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005205 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5206 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005207 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005208 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005209 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005210
5211 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005212}
5213
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005214ObjCPropertyImplDecl *
5215ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5216 const ObjCPropertyDecl *PD,
5217 const Decl *Container) const {
5218 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005219 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005220 if (const ObjCCategoryImplDecl *CID =
5221 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005222 for (auto *PID : CID->property_impls())
5223 if (PID->getPropertyDecl() == PD)
5224 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005225 } else {
5226 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5227 for (auto *PID : OID->property_impls())
5228 if (PID->getPropertyDecl() == PD)
5229 return PID;
5230 }
5231 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005232}
5233
Daniel Dunbar4932b362008-08-28 04:38:10 +00005234/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005235/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005236/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5237/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005238/// Property attributes are stored as a comma-delimited C string. The simple
5239/// attributes readonly and bycopy are encoded as single characters. The
5240/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5241/// encoded as single characters, followed by an identifier. Property types
5242/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005243/// these attributes are defined by the following enumeration:
5244/// @code
5245/// enum PropertyAttributes {
5246/// kPropertyReadOnly = 'R', // property is read-only.
5247/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5248/// kPropertyByref = '&', // property is a reference to the value last assigned
5249/// kPropertyDynamic = 'D', // property is dynamic
5250/// kPropertyGetter = 'G', // followed by getter selector name
5251/// kPropertySetter = 'S', // followed by setter selector name
5252/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005253/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005254/// kPropertyWeak = 'W' // 'weak' property
5255/// kPropertyStrong = 'P' // property GC'able
5256/// kPropertyNonAtomic = 'N' // property non-atomic
5257/// };
5258/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005259void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005260 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005261 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005262 // Collect information from the property implementation decl(s).
5263 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005264 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005265
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005266 if (ObjCPropertyImplDecl *PropertyImpDecl =
5267 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5268 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5269 Dynamic = true;
5270 else
5271 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005272 }
5273
5274 // FIXME: This is not very efficient.
5275 S = "T";
5276
5277 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005278 // GCC has some special rules regarding encoding of properties which
5279 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005280 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005281
5282 if (PD->isReadOnly()) {
5283 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005284 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5285 S += ",C";
5286 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5287 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005288 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5289 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005290 } else {
5291 switch (PD->getSetterKind()) {
5292 case ObjCPropertyDecl::Assign: break;
5293 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005294 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005295 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005296 }
5297 }
5298
5299 // It really isn't clear at all what this means, since properties
5300 // are "dynamic by default".
5301 if (Dynamic)
5302 S += ",D";
5303
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005304 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5305 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005306
Daniel Dunbar4932b362008-08-28 04:38:10 +00005307 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5308 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005309 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005310 }
5311
5312 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5313 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005314 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005315 }
5316
5317 if (SynthesizePID) {
5318 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5319 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005320 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005321 }
5322
5323 // FIXME: OBJCGC: weak & strong
5324}
5325
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005326/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005327/// Another legacy compatibility encoding: 32-bit longs are encoded as
5328/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005329/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5330///
5331void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005332 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005333 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005334 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005335 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005336 else
Jay Foad39c79802011-01-12 09:06:06 +00005337 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005338 PointeeTy = IntTy;
5339 }
5340 }
5341}
5342
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005343void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005344 const FieldDecl *Field,
5345 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005346 // We follow the behavior of gcc, expanding structures which are
5347 // directly pointed to, and expanding embedded structures. Note that
5348 // these rules are sufficient to prevent recursive encoding of the
5349 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005350 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005351 true /* outermost type */, false, false,
5352 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005353}
5354
Joe Groff98ac7d22014-07-07 22:25:15 +00005355void ASTContext::getObjCEncodingForPropertyType(QualType T,
5356 std::string& S) const {
5357 // Encode result type.
5358 // GCC has some special rules regarding encoding of properties which
5359 // closely resembles encoding of ivars.
5360 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5361 true /* outermost type */,
5362 true /* encoding property */);
5363}
5364
John McCall393a78d2012-12-20 02:45:14 +00005365static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5366 BuiltinType::Kind kind) {
5367 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005368 case BuiltinType::Void: return 'v';
5369 case BuiltinType::Bool: return 'B';
5370 case BuiltinType::Char_U:
5371 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005372 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005373 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005374 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005375 case BuiltinType::UInt: return 'I';
5376 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005377 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005378 case BuiltinType::UInt128: return 'T';
5379 case BuiltinType::ULongLong: return 'Q';
5380 case BuiltinType::Char_S:
5381 case BuiltinType::SChar: return 'c';
5382 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005383 case BuiltinType::WChar_S:
5384 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005385 case BuiltinType::Int: return 'i';
5386 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005387 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005388 case BuiltinType::LongLong: return 'q';
5389 case BuiltinType::Int128: return 't';
5390 case BuiltinType::Float: return 'f';
5391 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005392 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005393 case BuiltinType::NullPtr: return '*'; // like char*
5394
5395 case BuiltinType::Half:
5396 // FIXME: potentially need @encodes for these!
5397 return ' ';
5398
5399 case BuiltinType::ObjCId:
5400 case BuiltinType::ObjCClass:
5401 case BuiltinType::ObjCSel:
5402 llvm_unreachable("@encoding ObjC primitive type");
5403
5404 // OpenCL and placeholder types don't need @encodings.
5405 case BuiltinType::OCLImage1d:
5406 case BuiltinType::OCLImage1dArray:
5407 case BuiltinType::OCLImage1dBuffer:
5408 case BuiltinType::OCLImage2d:
5409 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005410 case BuiltinType::OCLImage2dDepth:
5411 case BuiltinType::OCLImage2dArrayDepth:
5412 case BuiltinType::OCLImage2dMSAA:
5413 case BuiltinType::OCLImage2dArrayMSAA:
5414 case BuiltinType::OCLImage2dMSAADepth:
5415 case BuiltinType::OCLImage2dArrayMSAADepth:
John McCall393a78d2012-12-20 02:45:14 +00005416 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005417 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005418 case BuiltinType::OCLClkEvent:
5419 case BuiltinType::OCLQueue:
5420 case BuiltinType::OCLNDRange:
5421 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005422 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005423 case BuiltinType::Dependent:
5424#define BUILTIN_TYPE(KIND, ID)
5425#define PLACEHOLDER_TYPE(KIND, ID) \
5426 case BuiltinType::KIND:
5427#include "clang/AST/BuiltinTypes.def"
5428 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005429 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005430 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005431}
5432
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005433static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5434 EnumDecl *Enum = ET->getDecl();
5435
5436 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5437 if (!Enum->isFixed())
5438 return 'i';
5439
5440 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005441 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5442 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005443}
5444
Jay Foad39c79802011-01-12 09:06:06 +00005445static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005446 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005447 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005448 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005449 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5450 // The GNU runtime requires more information; bitfields are encoded as b,
5451 // then the offset (in bits) of the first element, then the type of the
5452 // bitfield, then the size in bits. For example, in this structure:
5453 //
5454 // struct
5455 // {
5456 // int integer;
5457 // int flags:2;
5458 // };
5459 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5460 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5461 // information is not especially sensible, but we're stuck with it for
5462 // compatibility with GCC, although providing it breaks anything that
5463 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005464 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005465 const RecordDecl *RD = FD->getParent();
5466 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005467 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005468 if (const EnumType *ET = T->getAs<EnumType>())
5469 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005470 else {
5471 const BuiltinType *BT = T->castAs<BuiltinType>();
5472 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5473 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005474 }
Richard Smithcaf33902011-10-10 18:28:20 +00005475 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005476}
5477
Daniel Dunbar07d07852009-10-18 21:17:35 +00005478// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005479void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5480 bool ExpandPointedToStructures,
5481 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005482 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005483 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005484 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005485 bool StructField,
5486 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005487 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005488 bool EncodePointerToObjCTypedef,
5489 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005490 CanQualType CT = getCanonicalType(T);
5491 switch (CT->getTypeClass()) {
5492 case Type::Builtin:
5493 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005494 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005495 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005496 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5497 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5498 else
5499 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005500 return;
Mike Stump11289f42009-09-09 15:08:12 +00005501
John McCall393a78d2012-12-20 02:45:14 +00005502 case Type::Complex: {
5503 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005504 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005505 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005506 return;
5507 }
John McCall393a78d2012-12-20 02:45:14 +00005508
5509 case Type::Atomic: {
5510 const AtomicType *AT = T->castAs<AtomicType>();
5511 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005512 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005513 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005514 }
John McCall393a78d2012-12-20 02:45:14 +00005515
5516 // encoding for pointer or reference types.
5517 case Type::Pointer:
5518 case Type::LValueReference:
5519 case Type::RValueReference: {
5520 QualType PointeeTy;
5521 if (isa<PointerType>(CT)) {
5522 const PointerType *PT = T->castAs<PointerType>();
5523 if (PT->isObjCSelType()) {
5524 S += ':';
5525 return;
5526 }
5527 PointeeTy = PT->getPointeeType();
5528 } else {
5529 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5530 }
5531
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005532 bool isReadOnly = false;
5533 // For historical/compatibility reasons, the read-only qualifier of the
5534 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5535 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005536 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005537 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005538 if (OutermostType && T.isConstQualified()) {
5539 isReadOnly = true;
5540 S += 'r';
5541 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005542 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005543 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005544 while (P->getAs<PointerType>())
5545 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005546 if (P.isConstQualified()) {
5547 isReadOnly = true;
5548 S += 'r';
5549 }
5550 }
5551 if (isReadOnly) {
5552 // Another legacy compatibility encoding. Some ObjC qualifier and type
5553 // combinations need to be rearranged.
5554 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005555 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005556 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005557 }
Mike Stump11289f42009-09-09 15:08:12 +00005558
Anders Carlssond8499822007-10-29 05:01:08 +00005559 if (PointeeTy->isCharType()) {
5560 // char pointer types should be encoded as '*' unless it is a
5561 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005562 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005563 S += '*';
5564 return;
5565 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005566 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005567 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5568 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5569 S += '#';
5570 return;
5571 }
5572 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5573 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5574 S += '@';
5575 return;
5576 }
5577 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005578 }
Anders Carlssond8499822007-10-29 05:01:08 +00005579 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005580 getLegacyIntegralTypeEncoding(PointeeTy);
5581
Mike Stump11289f42009-09-09 15:08:12 +00005582 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005583 nullptr, false, false, false, false, false, false,
5584 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005585 return;
5586 }
John McCall393a78d2012-12-20 02:45:14 +00005587
5588 case Type::ConstantArray:
5589 case Type::IncompleteArray:
5590 case Type::VariableArray: {
5591 const ArrayType *AT = cast<ArrayType>(CT);
5592
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005593 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005594 // Incomplete arrays are encoded as a pointer to the array element.
5595 S += '^';
5596
Mike Stump11289f42009-09-09 15:08:12 +00005597 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005598 false, ExpandStructures, FD);
5599 } else {
5600 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005601
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005602 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5603 S += llvm::utostr(CAT->getSize().getZExtValue());
5604 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005605 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005606 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5607 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005608 S += '0';
5609 }
Mike Stump11289f42009-09-09 15:08:12 +00005610
5611 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005612 false, ExpandStructures, FD,
5613 false, false, false, false, false, false,
5614 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005615 S += ']';
5616 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005617 return;
5618 }
Mike Stump11289f42009-09-09 15:08:12 +00005619
John McCall393a78d2012-12-20 02:45:14 +00005620 case Type::FunctionNoProto:
5621 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005622 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005623 return;
Mike Stump11289f42009-09-09 15:08:12 +00005624
John McCall393a78d2012-12-20 02:45:14 +00005625 case Type::Record: {
5626 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005627 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005628 // Anonymous structures print as '?'
5629 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5630 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005631 if (ClassTemplateSpecializationDecl *Spec
5632 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5633 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005634 llvm::raw_string_ostream OS(S);
5635 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005636 TemplateArgs.data(),
5637 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005638 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005639 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005640 } else {
5641 S += '?';
5642 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005643 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005644 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005645 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005646 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005647 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005648 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005649 if (FD) {
5650 S += '"';
5651 S += Field->getNameAsString();
5652 S += '"';
5653 }
Mike Stump11289f42009-09-09 15:08:12 +00005654
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005655 // Special case bit-fields.
5656 if (Field->isBitField()) {
5657 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005658 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005659 } else {
5660 QualType qt = Field->getType();
5661 getLegacyIntegralTypeEncoding(qt);
5662 getObjCEncodingForTypeImpl(qt, S, false, true,
5663 FD, /*OutermostType*/false,
5664 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005665 /*StructField*/true,
5666 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005667 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005668 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005669 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005670 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005671 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005672 return;
5673 }
Mike Stump11289f42009-09-09 15:08:12 +00005674
John McCall393a78d2012-12-20 02:45:14 +00005675 case Type::BlockPointer: {
5676 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005677 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005678 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005679 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005680
5681 S += '<';
5682 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005683 getObjCEncodingForTypeImpl(
5684 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5685 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005686 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5687 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005688 // Block self
5689 S += "@?";
5690 // Block parameters
5691 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005692 for (const auto &I : FPT->param_types())
5693 getObjCEncodingForTypeImpl(
5694 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5695 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005696 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5697 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005698 }
5699 S += '>';
5700 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005701 return;
5702 }
Mike Stump11289f42009-09-09 15:08:12 +00005703
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005704 case Type::ObjCObject: {
5705 // hack to match legacy encoding of *id and *Class
5706 QualType Ty = getObjCObjectPointerType(CT);
5707 if (Ty->isObjCIdType()) {
5708 S += "{objc_object=}";
5709 return;
5710 }
5711 else if (Ty->isObjCClassType()) {
5712 S += "{objc_class=}";
5713 return;
5714 }
5715 }
5716
John McCall393a78d2012-12-20 02:45:14 +00005717 case Type::ObjCInterface: {
5718 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005719 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005720 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005721 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005722 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005723 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005724 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005725 DeepCollectObjCIvars(OI, true, Ivars);
5726 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005727 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005728 if (Field->isBitField())
5729 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005730 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005731 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5732 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005733 EncodePointerToObjCTypedef,
5734 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005735 }
5736 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005737 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005738 }
Mike Stump11289f42009-09-09 15:08:12 +00005739
John McCall393a78d2012-12-20 02:45:14 +00005740 case Type::ObjCObjectPointer: {
5741 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005742 if (OPT->isObjCIdType()) {
5743 S += '@';
5744 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005745 }
Mike Stump11289f42009-09-09 15:08:12 +00005746
Steve Narofff0c86112009-10-28 22:03:49 +00005747 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5748 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5749 // Since this is a binary compatibility issue, need to consult with runtime
5750 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005751 S += '#';
5752 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005753 }
Mike Stump11289f42009-09-09 15:08:12 +00005754
Chris Lattnere7cabb92009-07-13 00:10:46 +00005755 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005756 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005757 ExpandPointedToStructures,
5758 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005759 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005760 // Note that we do extended encoding of protocol qualifer list
5761 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005762 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005763 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005764 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005765 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005766 S += '>';
5767 }
5768 S += '"';
5769 }
5770 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005771 }
Mike Stump11289f42009-09-09 15:08:12 +00005772
Chris Lattnere7cabb92009-07-13 00:10:46 +00005773 QualType PointeeTy = OPT->getPointeeType();
5774 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005775 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5776 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005777 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005778 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005779 // {...};
5780 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005781 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005782 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005783 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5784 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5785 DeepCollectObjCIvars(OI, true, Ivars);
5786 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5787 if (cast<FieldDecl>(Ivars[i]) == FD) {
5788 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005789 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005790 S += '}';
5791 return;
5792 }
5793 }
5794 }
Mike Stump11289f42009-09-09 15:08:12 +00005795 getObjCEncodingForTypeImpl(PointeeTy, S,
5796 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005797 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005798 false, false, false, false, false,
5799 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005800 return;
5801 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005802
5803 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005804 if (OPT->getInterfaceDecl() &&
5805 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005806 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005807 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005808 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005809 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005810 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005811 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005812 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005813 S += '"';
5814 }
5815 return;
5816 }
Mike Stump11289f42009-09-09 15:08:12 +00005817
John McCalla9e6e8d2010-05-17 23:56:34 +00005818 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005819 // FIXME: we shoul do better than that. 'M' is available.
5820 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005821 // This matches gcc's encoding, even though technically it is insufficient.
5822 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005823 case Type::Vector:
5824 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005825 // Until we have a coherent encoding of these three types, issue warning.
5826 { if (NotEncodedT)
5827 *NotEncodedT = T;
5828 return;
5829 }
5830
5831 // We could see an undeduced auto type here during error recovery.
5832 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005833 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005834 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005835
Richard Smith27d807c2013-04-30 13:56:41 +00005836
John McCall393a78d2012-12-20 02:45:14 +00005837#define ABSTRACT_TYPE(KIND, BASE)
5838#define TYPE(KIND, BASE)
5839#define DEPENDENT_TYPE(KIND, BASE) \
5840 case Type::KIND:
5841#define NON_CANONICAL_TYPE(KIND, BASE) \
5842 case Type::KIND:
5843#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5844 case Type::KIND:
5845#include "clang/AST/TypeNodes.def"
5846 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005847 }
John McCall393a78d2012-12-20 02:45:14 +00005848 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005849}
5850
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005851void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5852 std::string &S,
5853 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005854 bool includeVBases,
5855 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005856 assert(RDecl && "Expected non-null RecordDecl");
5857 assert(!RDecl->isUnion() && "Should not be called for unions");
5858 if (!RDecl->getDefinition())
5859 return;
5860
5861 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5862 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5863 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5864
5865 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005866 for (const auto &BI : CXXRec->bases()) {
5867 if (!BI.isVirtual()) {
5868 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005869 if (base->isEmpty())
5870 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005871 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005872 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5873 std::make_pair(offs, base));
5874 }
5875 }
5876 }
5877
5878 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005879 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005880 uint64_t offs = layout.getFieldOffset(i);
5881 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005882 std::make_pair(offs, Field));
5883 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005884 }
5885
5886 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005887 for (const auto &BI : CXXRec->vbases()) {
5888 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005889 if (base->isEmpty())
5890 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005891 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005892 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5893 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005894 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5895 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005896 }
5897 }
5898
5899 CharUnits size;
5900 if (CXXRec) {
5901 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5902 } else {
5903 size = layout.getSize();
5904 }
5905
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005906#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005907 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005908#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005909 std::multimap<uint64_t, NamedDecl *>::iterator
5910 CurLayObj = FieldOrBaseOffsets.begin();
5911
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005912 if (CXXRec && CXXRec->isDynamicClass() &&
5913 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005914 if (FD) {
5915 S += "\"_vptr$";
5916 std::string recname = CXXRec->getNameAsString();
5917 if (recname.empty()) recname = "?";
5918 S += recname;
5919 S += '"';
5920 }
5921 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005922#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005923 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005924#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005925 }
5926
5927 if (!RDecl->hasFlexibleArrayMember()) {
5928 // Mark the end of the structure.
5929 uint64_t offs = toBits(size);
5930 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005931 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005932 }
5933
5934 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005935#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005936 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005937 if (CurOffs < CurLayObj->first) {
5938 uint64_t padding = CurLayObj->first - CurOffs;
5939 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5940 // packing/alignment of members is different that normal, in which case
5941 // the encoding will be out-of-sync with the real layout.
5942 // If the runtime switches to just consider the size of types without
5943 // taking into account alignment, we could make padding explicit in the
5944 // encoding (e.g. using arrays of chars). The encoding strings would be
5945 // longer then though.
5946 CurOffs += padding;
5947 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005948#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005949
5950 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005951 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005952 break; // reached end of structure.
5953
5954 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5955 // We expand the bases without their virtual bases since those are going
5956 // in the initial structure. Note that this differs from gcc which
5957 // expands virtual bases each time one is encountered in the hierarchy,
5958 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005959 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5960 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005961 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005962#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005963 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005964#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005965 } else {
5966 FieldDecl *field = cast<FieldDecl>(dcl);
5967 if (FD) {
5968 S += '"';
5969 S += field->getNameAsString();
5970 S += '"';
5971 }
5972
5973 if (field->isBitField()) {
5974 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005975#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005976 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005977#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005978 } else {
5979 QualType qt = field->getType();
5980 getLegacyIntegralTypeEncoding(qt);
5981 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5982 /*OutermostType*/false,
5983 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005984 /*StructField*/true,
5985 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005986#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005987 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005988#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005989 }
5990 }
5991 }
5992}
5993
Mike Stump11289f42009-09-09 15:08:12 +00005994void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005995 std::string& S) const {
5996 if (QT & Decl::OBJC_TQ_In)
5997 S += 'n';
5998 if (QT & Decl::OBJC_TQ_Inout)
5999 S += 'N';
6000 if (QT & Decl::OBJC_TQ_Out)
6001 S += 'o';
6002 if (QT & Decl::OBJC_TQ_Bycopy)
6003 S += 'O';
6004 if (QT & Decl::OBJC_TQ_Byref)
6005 S += 'R';
6006 if (QT & Decl::OBJC_TQ_Oneway)
6007 S += 'V';
6008}
6009
Douglas Gregor3ea72692011-08-12 05:46:01 +00006010TypedefDecl *ASTContext::getObjCIdDecl() const {
6011 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006012 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006013 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006014 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006015 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006016 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006017}
6018
Douglas Gregor52e02802011-08-12 06:17:30 +00006019TypedefDecl *ASTContext::getObjCSelDecl() const {
6020 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006021 QualType T = getPointerType(ObjCBuiltinSelTy);
6022 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006023 }
6024 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006025}
6026
Douglas Gregor0a586182011-08-12 05:59:41 +00006027TypedefDecl *ASTContext::getObjCClassDecl() const {
6028 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006029 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006030 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006031 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006032 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006033 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006034}
6035
Douglas Gregord53ae832012-01-17 18:09:05 +00006036ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6037 if (!ObjCProtocolClassDecl) {
6038 ObjCProtocolClassDecl
6039 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6040 SourceLocation(),
6041 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006042 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006043 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006044 SourceLocation(), true);
6045 }
6046
6047 return ObjCProtocolClassDecl;
6048}
6049
Meador Inge5d3fb222012-06-16 03:34:49 +00006050//===----------------------------------------------------------------------===//
6051// __builtin_va_list Construction Functions
6052//===----------------------------------------------------------------------===//
6053
Charles Davisc7d5c942015-09-17 20:55:33 +00006054static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6055 StringRef Name) {
6056 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006057 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006058 return Context->buildImplicitTypedef(T, Name);
6059}
6060
6061static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6062 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6063}
6064
6065static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6066 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006067}
6068
6069static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6070 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006071 QualType T = Context->getPointerType(Context->VoidTy);
6072 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006073}
6074
Tim Northover9bb857a2013-01-31 12:13:10 +00006075static TypedefDecl *
6076CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006077 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006078 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006079 if (Context->getLangOpts().CPlusPlus) {
6080 // namespace std { struct __va_list {
6081 NamespaceDecl *NS;
6082 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6083 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006084 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006085 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006086 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006087 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006088 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006089 }
6090
6091 VaListTagDecl->startDefinition();
6092
6093 const size_t NumFields = 5;
6094 QualType FieldTypes[NumFields];
6095 const char *FieldNames[NumFields];
6096
6097 // void *__stack;
6098 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6099 FieldNames[0] = "__stack";
6100
6101 // void *__gr_top;
6102 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6103 FieldNames[1] = "__gr_top";
6104
6105 // void *__vr_top;
6106 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6107 FieldNames[2] = "__vr_top";
6108
6109 // int __gr_offs;
6110 FieldTypes[3] = Context->IntTy;
6111 FieldNames[3] = "__gr_offs";
6112
6113 // int __vr_offs;
6114 FieldTypes[4] = Context->IntTy;
6115 FieldNames[4] = "__vr_offs";
6116
6117 // Create fields
6118 for (unsigned i = 0; i < NumFields; ++i) {
6119 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6120 VaListTagDecl,
6121 SourceLocation(),
6122 SourceLocation(),
6123 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006124 FieldTypes[i], /*TInfo=*/nullptr,
6125 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006126 /*Mutable=*/false,
6127 ICIS_NoInit);
6128 Field->setAccess(AS_public);
6129 VaListTagDecl->addDecl(Field);
6130 }
6131 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006132 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006133 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006134
6135 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006136 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006137}
6138
Meador Inge5d3fb222012-06-16 03:34:49 +00006139static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6140 // typedef struct __va_list_tag {
6141 RecordDecl *VaListTagDecl;
6142
Alp Toker2dea15b2013-12-17 01:22:38 +00006143 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006144 VaListTagDecl->startDefinition();
6145
6146 const size_t NumFields = 5;
6147 QualType FieldTypes[NumFields];
6148 const char *FieldNames[NumFields];
6149
6150 // unsigned char gpr;
6151 FieldTypes[0] = Context->UnsignedCharTy;
6152 FieldNames[0] = "gpr";
6153
6154 // unsigned char fpr;
6155 FieldTypes[1] = Context->UnsignedCharTy;
6156 FieldNames[1] = "fpr";
6157
6158 // unsigned short reserved;
6159 FieldTypes[2] = Context->UnsignedShortTy;
6160 FieldNames[2] = "reserved";
6161
6162 // void* overflow_arg_area;
6163 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6164 FieldNames[3] = "overflow_arg_area";
6165
6166 // void* reg_save_area;
6167 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6168 FieldNames[4] = "reg_save_area";
6169
6170 // Create fields
6171 for (unsigned i = 0; i < NumFields; ++i) {
6172 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6173 SourceLocation(),
6174 SourceLocation(),
6175 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006176 FieldTypes[i], /*TInfo=*/nullptr,
6177 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006178 /*Mutable=*/false,
6179 ICIS_NoInit);
6180 Field->setAccess(AS_public);
6181 VaListTagDecl->addDecl(Field);
6182 }
6183 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006184 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006185 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6186
6187 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006188 TypedefDecl *VaListTagTypedefDecl =
6189 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6190
Meador Inge5d3fb222012-06-16 03:34:49 +00006191 QualType VaListTagTypedefType =
6192 Context->getTypedefType(VaListTagTypedefDecl);
6193
6194 // typedef __va_list_tag __builtin_va_list[1];
6195 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6196 QualType VaListTagArrayType
6197 = Context->getConstantArrayType(VaListTagTypedefType,
6198 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006199 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006200}
6201
6202static TypedefDecl *
6203CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006204 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006205 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006206 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006207 VaListTagDecl->startDefinition();
6208
6209 const size_t NumFields = 4;
6210 QualType FieldTypes[NumFields];
6211 const char *FieldNames[NumFields];
6212
6213 // unsigned gp_offset;
6214 FieldTypes[0] = Context->UnsignedIntTy;
6215 FieldNames[0] = "gp_offset";
6216
6217 // unsigned fp_offset;
6218 FieldTypes[1] = Context->UnsignedIntTy;
6219 FieldNames[1] = "fp_offset";
6220
6221 // void* overflow_arg_area;
6222 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6223 FieldNames[2] = "overflow_arg_area";
6224
6225 // void* reg_save_area;
6226 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6227 FieldNames[3] = "reg_save_area";
6228
6229 // Create fields
6230 for (unsigned i = 0; i < NumFields; ++i) {
6231 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6232 VaListTagDecl,
6233 SourceLocation(),
6234 SourceLocation(),
6235 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006236 FieldTypes[i], /*TInfo=*/nullptr,
6237 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006238 /*Mutable=*/false,
6239 ICIS_NoInit);
6240 Field->setAccess(AS_public);
6241 VaListTagDecl->addDecl(Field);
6242 }
6243 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006244 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006245 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6246
Richard Smith9b88a4c2015-07-27 05:40:23 +00006247 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006248
Richard Smith9b88a4c2015-07-27 05:40:23 +00006249 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006250 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006251 QualType VaListTagArrayType =
6252 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006253 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006254}
6255
6256static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6257 // typedef int __builtin_va_list[4];
6258 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6259 QualType IntArrayType
6260 = Context->getConstantArrayType(Context->IntTy,
6261 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006262 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006263}
6264
Logan Chien57086ce2012-10-10 06:56:20 +00006265static TypedefDecl *
6266CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006267 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006268 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006269 if (Context->getLangOpts().CPlusPlus) {
6270 // namespace std { struct __va_list {
6271 NamespaceDecl *NS;
6272 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6273 Context->getTranslationUnitDecl(),
6274 /*Inline*/false, SourceLocation(),
6275 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006276 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006277 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006278 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006279 }
6280
6281 VaListDecl->startDefinition();
6282
6283 // void * __ap;
6284 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6285 VaListDecl,
6286 SourceLocation(),
6287 SourceLocation(),
6288 &Context->Idents.get("__ap"),
6289 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006290 /*TInfo=*/nullptr,
6291 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006292 /*Mutable=*/false,
6293 ICIS_NoInit);
6294 Field->setAccess(AS_public);
6295 VaListDecl->addDecl(Field);
6296
6297 // };
6298 VaListDecl->completeDefinition();
6299
6300 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006301 QualType T = Context->getRecordType(VaListDecl);
6302 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006303}
6304
Ulrich Weigand47445072013-05-06 16:26:41 +00006305static TypedefDecl *
6306CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006307 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006308 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006309 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006310 VaListTagDecl->startDefinition();
6311
6312 const size_t NumFields = 4;
6313 QualType FieldTypes[NumFields];
6314 const char *FieldNames[NumFields];
6315
6316 // long __gpr;
6317 FieldTypes[0] = Context->LongTy;
6318 FieldNames[0] = "__gpr";
6319
6320 // long __fpr;
6321 FieldTypes[1] = Context->LongTy;
6322 FieldNames[1] = "__fpr";
6323
6324 // void *__overflow_arg_area;
6325 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6326 FieldNames[2] = "__overflow_arg_area";
6327
6328 // void *__reg_save_area;
6329 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6330 FieldNames[3] = "__reg_save_area";
6331
6332 // Create fields
6333 for (unsigned i = 0; i < NumFields; ++i) {
6334 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6335 VaListTagDecl,
6336 SourceLocation(),
6337 SourceLocation(),
6338 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006339 FieldTypes[i], /*TInfo=*/nullptr,
6340 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006341 /*Mutable=*/false,
6342 ICIS_NoInit);
6343 Field->setAccess(AS_public);
6344 VaListTagDecl->addDecl(Field);
6345 }
6346 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006347 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006348 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006349
Richard Smith9b88a4c2015-07-27 05:40:23 +00006350 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006351
6352 // typedef __va_list_tag __builtin_va_list[1];
6353 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006354 QualType VaListTagArrayType =
6355 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006356
Alp Toker56b5cc92013-12-15 10:36:26 +00006357 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006358}
6359
Meador Inge5d3fb222012-06-16 03:34:49 +00006360static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6361 TargetInfo::BuiltinVaListKind Kind) {
6362 switch (Kind) {
6363 case TargetInfo::CharPtrBuiltinVaList:
6364 return CreateCharPtrBuiltinVaListDecl(Context);
6365 case TargetInfo::VoidPtrBuiltinVaList:
6366 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006367 case TargetInfo::AArch64ABIBuiltinVaList:
6368 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006369 case TargetInfo::PowerABIBuiltinVaList:
6370 return CreatePowerABIBuiltinVaListDecl(Context);
6371 case TargetInfo::X86_64ABIBuiltinVaList:
6372 return CreateX86_64ABIBuiltinVaListDecl(Context);
6373 case TargetInfo::PNaClABIBuiltinVaList:
6374 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006375 case TargetInfo::AAPCSABIBuiltinVaList:
6376 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006377 case TargetInfo::SystemZBuiltinVaList:
6378 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006379 }
6380
6381 llvm_unreachable("Unhandled __builtin_va_list type kind");
6382}
6383
6384TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006385 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006386 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006387 assert(BuiltinVaListDecl->isImplicit());
6388 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006389
6390 return BuiltinVaListDecl;
6391}
6392
Richard Smith9b88a4c2015-07-27 05:40:23 +00006393Decl *ASTContext::getVaListTagDecl() const {
6394 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006395 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006396 if (!VaListTagDecl)
6397 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006398
Richard Smith9b88a4c2015-07-27 05:40:23 +00006399 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006400}
6401
Charles Davisc7d5c942015-09-17 20:55:33 +00006402TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6403 if (!BuiltinMSVaListDecl)
6404 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6405
6406 return BuiltinMSVaListDecl;
6407}
6408
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006409void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006410 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006411 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006412
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006413 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006414}
6415
John McCalld28ae272009-12-02 08:04:21 +00006416/// \brief Retrieve the template name that corresponds to a non-empty
6417/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006418TemplateName
6419ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6420 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006421 unsigned size = End - Begin;
6422 assert(size > 1 && "set is not overloaded!");
6423
6424 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6425 size * sizeof(FunctionTemplateDecl*));
6426 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6427
6428 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006429 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006430 NamedDecl *D = *I;
6431 assert(isa<FunctionTemplateDecl>(D) ||
6432 (isa<UsingShadowDecl>(D) &&
6433 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6434 *Storage++ = D;
6435 }
6436
6437 return TemplateName(OT);
6438}
6439
Douglas Gregordc572a32009-03-30 22:58:21 +00006440/// \brief Retrieve the template name that represents a qualified
6441/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006442TemplateName
6443ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6444 bool TemplateKeyword,
6445 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006446 assert(NNS && "Missing nested-name-specifier in qualified template name");
6447
Douglas Gregorc42075a2010-02-04 18:10:26 +00006448 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006449 llvm::FoldingSetNodeID ID;
6450 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6451
Craig Topper36250ad2014-05-12 05:36:57 +00006452 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006453 QualifiedTemplateName *QTN =
6454 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6455 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006456 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6457 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006458 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6459 }
6460
6461 return TemplateName(QTN);
6462}
6463
6464/// \brief Retrieve the template name that represents a dependent
6465/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006466TemplateName
6467ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6468 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006469 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006470 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006471
6472 llvm::FoldingSetNodeID ID;
6473 DependentTemplateName::Profile(ID, NNS, Name);
6474
Craig Topper36250ad2014-05-12 05:36:57 +00006475 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006476 DependentTemplateName *QTN =
6477 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6478
6479 if (QTN)
6480 return TemplateName(QTN);
6481
6482 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6483 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006484 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6485 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006486 } else {
6487 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006488 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6489 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006490 DependentTemplateName *CheckQTN =
6491 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6492 assert(!CheckQTN && "Dependent type name canonicalization broken");
6493 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006494 }
6495
6496 DependentTemplateNames.InsertNode(QTN, InsertPos);
6497 return TemplateName(QTN);
6498}
6499
Douglas Gregor71395fa2009-11-04 00:56:37 +00006500/// \brief Retrieve the template name that represents a dependent
6501/// template name such as \c MetaFun::template operator+.
6502TemplateName
6503ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006504 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006505 assert((!NNS || NNS->isDependent()) &&
6506 "Nested name specifier must be dependent");
6507
6508 llvm::FoldingSetNodeID ID;
6509 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006510
6511 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006512 DependentTemplateName *QTN
6513 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006514
6515 if (QTN)
6516 return TemplateName(QTN);
6517
6518 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6519 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006520 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6521 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006522 } else {
6523 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006524 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6525 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006526
6527 DependentTemplateName *CheckQTN
6528 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6529 assert(!CheckQTN && "Dependent template name canonicalization broken");
6530 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006531 }
6532
6533 DependentTemplateNames.InsertNode(QTN, InsertPos);
6534 return TemplateName(QTN);
6535}
6536
Douglas Gregor5590be02011-01-15 06:45:20 +00006537TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006538ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6539 TemplateName replacement) const {
6540 llvm::FoldingSetNodeID ID;
6541 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006542
6543 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006544 SubstTemplateTemplateParmStorage *subst
6545 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6546
6547 if (!subst) {
6548 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6549 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6550 }
6551
6552 return TemplateName(subst);
6553}
6554
6555TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006556ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6557 const TemplateArgument &ArgPack) const {
6558 ASTContext &Self = const_cast<ASTContext &>(*this);
6559 llvm::FoldingSetNodeID ID;
6560 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006561
6562 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006563 SubstTemplateTemplateParmPackStorage *Subst
6564 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6565
6566 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006567 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006568 ArgPack.pack_size(),
6569 ArgPack.pack_begin());
6570 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6571 }
6572
6573 return TemplateName(Subst);
6574}
6575
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006576/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006577/// TargetInfo, produce the corresponding type. The unsigned @p Type
6578/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006579CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006580 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006581 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006582 case TargetInfo::SignedChar: return SignedCharTy;
6583 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006584 case TargetInfo::SignedShort: return ShortTy;
6585 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6586 case TargetInfo::SignedInt: return IntTy;
6587 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6588 case TargetInfo::SignedLong: return LongTy;
6589 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6590 case TargetInfo::SignedLongLong: return LongLongTy;
6591 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6592 }
6593
David Blaikie83d382b2011-09-23 05:06:16 +00006594 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006595}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006596
6597//===----------------------------------------------------------------------===//
6598// Type Predicates.
6599//===----------------------------------------------------------------------===//
6600
Fariborz Jahanian96207692009-02-18 21:49:28 +00006601/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6602/// garbage collection attribute.
6603///
John McCall553d45a2011-01-12 00:34:59 +00006604Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006605 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006606 return Qualifiers::GCNone;
6607
David Blaikiebbafb8a2012-03-11 07:00:24 +00006608 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006609 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6610
6611 // Default behaviour under objective-C's gc is for ObjC pointers
6612 // (or pointers to them) be treated as though they were declared
6613 // as __strong.
6614 if (GCAttrs == Qualifiers::GCNone) {
6615 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6616 return Qualifiers::Strong;
6617 else if (Ty->isPointerType())
6618 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6619 } else {
6620 // It's not valid to set GC attributes on anything that isn't a
6621 // pointer.
6622#ifndef NDEBUG
6623 QualType CT = Ty->getCanonicalTypeInternal();
6624 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6625 CT = AT->getElementType();
6626 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6627#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006628 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006629 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006630}
6631
Chris Lattner49af6a42008-04-07 06:51:04 +00006632//===----------------------------------------------------------------------===//
6633// Type Compatibility Testing
6634//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006635
Mike Stump11289f42009-09-09 15:08:12 +00006636/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006637/// compatible.
6638static bool areCompatVectorTypes(const VectorType *LHS,
6639 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006640 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006641 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006642 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006643}
6644
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006645bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6646 QualType SecondVec) {
6647 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6648 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6649
6650 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6651 return true;
6652
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006653 // Treat Neon vector types and most AltiVec vector types as if they are the
6654 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006655 const VectorType *First = FirstVec->getAs<VectorType>();
6656 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006657 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006658 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006659 First->getVectorKind() != VectorType::AltiVecPixel &&
6660 First->getVectorKind() != VectorType::AltiVecBool &&
6661 Second->getVectorKind() != VectorType::AltiVecPixel &&
6662 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006663 return true;
6664
6665 return false;
6666}
6667
Steve Naroff8e6aee52009-07-23 01:01:38 +00006668//===----------------------------------------------------------------------===//
6669// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6670//===----------------------------------------------------------------------===//
6671
6672/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6673/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006674bool
6675ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6676 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006677 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006678 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006679 for (auto *PI : rProto->protocols())
6680 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006681 return true;
6682 return false;
6683}
6684
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006685/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6686/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006687bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6688 QualType rhs) {
6689 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6690 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6691 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6692
Aaron Ballman83731462014-03-17 16:14:00 +00006693 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006694 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006695 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006696 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6697 match = true;
6698 break;
6699 }
6700 }
6701 if (!match)
6702 return false;
6703 }
6704 return true;
6705}
6706
Steve Naroff8e6aee52009-07-23 01:01:38 +00006707/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6708/// ObjCQualifiedIDType.
6709bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6710 bool compare) {
6711 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006712 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006713 lhs->isObjCIdType() || lhs->isObjCClassType())
6714 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006715 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006716 rhs->isObjCIdType() || rhs->isObjCClassType())
6717 return true;
6718
6719 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006720 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006721
Steve Naroff8e6aee52009-07-23 01:01:38 +00006722 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006723
Steve Naroff8e6aee52009-07-23 01:01:38 +00006724 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006725 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006726 // make sure we check the class hierarchy.
6727 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006728 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006729 // when comparing an id<P> on lhs with a static type on rhs,
6730 // see if static class implements all of id's protocols, directly or
6731 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006732 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006733 return false;
6734 }
6735 }
6736 // If there are no qualifiers and no interface, we have an 'id'.
6737 return true;
6738 }
Mike Stump11289f42009-09-09 15:08:12 +00006739 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006740 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006741 bool match = false;
6742
6743 // when comparing an id<P> on lhs with a static type on rhs,
6744 // see if static class implements all of id's protocols, directly or
6745 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006746 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006747 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6748 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6749 match = true;
6750 break;
6751 }
6752 }
Mike Stump11289f42009-09-09 15:08:12 +00006753 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006754 // make sure we check the class hierarchy.
6755 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006756 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006757 // when comparing an id<P> on lhs with a static type on rhs,
6758 // see if static class implements all of id's protocols, directly or
6759 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006760 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006761 match = true;
6762 break;
6763 }
6764 }
6765 }
6766 if (!match)
6767 return false;
6768 }
Mike Stump11289f42009-09-09 15:08:12 +00006769
Steve Naroff8e6aee52009-07-23 01:01:38 +00006770 return true;
6771 }
Mike Stump11289f42009-09-09 15:08:12 +00006772
Steve Naroff8e6aee52009-07-23 01:01:38 +00006773 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6774 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6775
Mike Stump11289f42009-09-09 15:08:12 +00006776 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006777 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006778 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006779 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006780 bool match = false;
6781
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006782 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006783 // see if static class implements all of id's protocols, directly or
6784 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006785 // First, lhs protocols in the qualifier list must be found, direct
6786 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006787 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006788 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6789 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6790 match = true;
6791 break;
6792 }
6793 }
6794 if (!match)
6795 return false;
6796 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006797
6798 // Static class's protocols, or its super class or category protocols
6799 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6800 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6801 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6802 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6803 // This is rather dubious but matches gcc's behavior. If lhs has
6804 // no type qualifier and its class has no static protocol(s)
6805 // assume that it is mismatch.
6806 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6807 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006808 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006809 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006810 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006811 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6812 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6813 match = true;
6814 break;
6815 }
6816 }
6817 if (!match)
6818 return false;
6819 }
6820 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006821 return true;
6822 }
6823 return false;
6824}
6825
Eli Friedman47f77112008-08-22 00:56:42 +00006826/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006827/// compatible for assignment from RHS to LHS. This handles validation of any
6828/// protocol qualifiers on the LHS or RHS.
6829///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006830bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6831 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006832 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6833 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6834
Steve Naroff1329fa02009-07-15 18:40:39 +00006835 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006836 if (LHS->isObjCUnqualifiedIdOrClass() ||
6837 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006838 return true;
6839
Douglas Gregorab209d82015-07-07 03:58:42 +00006840 // Function object that propagates a successful result or handles
6841 // __kindof types.
6842 auto finish = [&](bool succeeded) -> bool {
6843 if (succeeded)
6844 return true;
6845
6846 if (!RHS->isKindOfType())
6847 return false;
6848
6849 // Strip off __kindof and protocol qualifiers, then check whether
6850 // we can assign the other way.
6851 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6852 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6853 };
6854
6855 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6856 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6857 QualType(RHSOPT,0),
6858 false));
6859 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006860
Douglas Gregorab209d82015-07-07 03:58:42 +00006861 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6862 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6863 QualType(RHSOPT,0)));
6864 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006865
John McCall8b07ec22010-05-15 11:32:37 +00006866 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006867 if (LHS->getInterface() && RHS->getInterface()) {
6868 return finish(canAssignObjCInterfaces(LHS, RHS));
6869 }
Mike Stump11289f42009-09-09 15:08:12 +00006870
Steve Naroff8e6aee52009-07-23 01:01:38 +00006871 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006872}
6873
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006874/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006875/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006876/// arguments in block literals. When passed as arguments, passing 'A*' where
6877/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6878/// not OK. For the return type, the opposite is not OK.
6879bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6880 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006881 const ObjCObjectPointerType *RHSOPT,
6882 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006883
6884 // Function object that propagates a successful result or handles
6885 // __kindof types.
6886 auto finish = [&](bool succeeded) -> bool {
6887 if (succeeded)
6888 return true;
6889
6890 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6891 if (!Expected->isKindOfType())
6892 return false;
6893
6894 // Strip off __kindof and protocol qualifiers, then check whether
6895 // we can assign the other way.
6896 return canAssignObjCInterfacesInBlockPointer(
6897 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6898 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6899 BlockReturnType);
6900 };
6901
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006902 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006903 return true;
6904
6905 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006906 return finish(RHSOPT->isObjCBuiltinType() ||
6907 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006908 }
6909
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006910 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00006911 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6912 QualType(RHSOPT,0),
6913 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006914
6915 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6916 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6917 if (LHS && RHS) { // We have 2 user-defined types.
6918 if (LHS != RHS) {
6919 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006920 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006921 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006922 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006923 }
6924 else
6925 return true;
6926 }
6927 return false;
6928}
6929
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006930/// Comparison routine for Objective-C protocols to be used with
6931/// llvm::array_pod_sort.
6932static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6933 ObjCProtocolDecl * const *rhs) {
6934 return (*lhs)->getName().compare((*rhs)->getName());
6935
6936}
6937
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006938/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006939/// of protocols inherited from two distinct objective-c pointer objects with
6940/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006941/// It is used to build composite qualifier list of the composite type of
6942/// the conditional expression involving two objective-c pointer objects.
6943static
6944void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006945 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006946 const ObjCObjectPointerType *LHSOPT,
6947 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006948 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006949
John McCall8b07ec22010-05-15 11:32:37 +00006950 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6951 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6952 assert(LHS->getInterface() && "LHS must have an interface base");
6953 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006954
6955 // Add all of the protocols for the LHS.
6956 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6957
6958 // Start with the protocol qualifiers.
6959 for (auto proto : LHS->quals()) {
6960 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006961 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006962
6963 // Also add the protocols associated with the LHS interface.
6964 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6965
6966 // Add all of the protocls for the RHS.
6967 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6968
6969 // Start with the protocol qualifiers.
6970 for (auto proto : RHS->quals()) {
6971 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006972 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006973
6974 // Also add the protocols associated with the RHS interface.
6975 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
6976
6977 // Compute the intersection of the collected protocol sets.
6978 for (auto proto : LHSProtocolSet) {
6979 if (RHSProtocolSet.count(proto))
6980 IntersectionSet.push_back(proto);
6981 }
6982
6983 // Compute the set of protocols that is implied by either the common type or
6984 // the protocols within the intersection.
6985 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
6986 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
6987
6988 // Remove any implied protocols from the list of inherited protocols.
6989 if (!ImpliedProtocols.empty()) {
6990 IntersectionSet.erase(
6991 std::remove_if(IntersectionSet.begin(),
6992 IntersectionSet.end(),
6993 [&](ObjCProtocolDecl *proto) -> bool {
6994 return ImpliedProtocols.count(proto) > 0;
6995 }),
6996 IntersectionSet.end());
6997 }
6998
6999 // Sort the remaining protocols by name.
7000 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7001 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007002}
7003
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007004/// Determine whether the first type is a subtype of the second.
7005static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7006 QualType rhs) {
7007 // Common case: two object pointers.
7008 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7009 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7010 if (lhsOPT && rhsOPT)
7011 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7012
7013 // Two block pointers.
7014 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7015 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7016 if (lhsBlock && rhsBlock)
7017 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7018
7019 // If either is an unqualified 'id' and the other is a block, it's
7020 // acceptable.
7021 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7022 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7023 return true;
7024
7025 return false;
7026}
7027
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007028// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007029static bool sameObjCTypeArgs(ASTContext &ctx,
7030 const ObjCInterfaceDecl *iface,
7031 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007032 ArrayRef<QualType> rhsArgs,
7033 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007034 if (lhsArgs.size() != rhsArgs.size())
7035 return false;
7036
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007037 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007038 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007039 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7040 continue;
7041
7042 switch (typeParams->begin()[i]->getVariance()) {
7043 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007044 if (!stripKindOf ||
7045 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7046 rhsArgs[i].stripObjCKindOfType(ctx))) {
7047 return false;
7048 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007049 break;
7050
7051 case ObjCTypeParamVariance::Covariant:
7052 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7053 return false;
7054 break;
7055
7056 case ObjCTypeParamVariance::Contravariant:
7057 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7058 return false;
7059 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007060 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007061 }
7062
7063 return true;
7064}
7065
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007066QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007067 const ObjCObjectPointerType *Lptr,
7068 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007069 const ObjCObjectType *LHS = Lptr->getObjectType();
7070 const ObjCObjectType *RHS = Rptr->getObjectType();
7071 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7072 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007073
7074 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007075 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007076
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007077 // Follow the left-hand side up the class hierarchy until we either hit a
7078 // root or find the RHS. Record the ancestors in case we don't find it.
7079 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7080 LHSAncestors;
7081 while (true) {
7082 // Record this ancestor. We'll need this if the common type isn't in the
7083 // path from the LHS to the root.
7084 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007085
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007086 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7087 // Get the type arguments.
7088 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7089 bool anyChanges = false;
7090 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7091 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007092 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7093 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007094 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007095 return QualType();
7096 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7097 // If only one has type arguments, the result will not have type
7098 // arguments.
7099 LHSTypeArgs = { };
7100 anyChanges = true;
7101 }
7102
7103 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007104 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007105 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7106 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007107 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007108 anyChanges = true;
7109
7110 // If anything in the LHS will have changed, build a new result type.
7111 if (anyChanges) {
7112 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007113 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7114 LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007115 return getObjCObjectPointerType(Result);
7116 }
7117
7118 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007119 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007120
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007121 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007122 QualType LHSSuperType = LHS->getSuperClassType();
7123 if (LHSSuperType.isNull())
7124 break;
7125
7126 LHS = LHSSuperType->castAs<ObjCObjectType>();
7127 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007128
7129 // We didn't find anything by following the LHS to its root; now check
7130 // the RHS against the cached set of ancestors.
7131 while (true) {
7132 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7133 if (KnownLHS != LHSAncestors.end()) {
7134 LHS = KnownLHS->second;
7135
7136 // Get the type arguments.
7137 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7138 bool anyChanges = false;
7139 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7140 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007141 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7142 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007143 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007144 return QualType();
7145 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7146 // If only one has type arguments, the result will not have type
7147 // arguments.
7148 RHSTypeArgs = { };
7149 anyChanges = true;
7150 }
7151
7152 // Compute the intersection of protocols.
7153 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7154 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7155 Protocols);
7156 if (!Protocols.empty())
7157 anyChanges = true;
7158
7159 if (anyChanges) {
7160 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007161 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7162 RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007163 return getObjCObjectPointerType(Result);
7164 }
7165
7166 return getObjCObjectPointerType(QualType(RHS, 0));
7167 }
7168
7169 // Find the superclass of the RHS.
7170 QualType RHSSuperType = RHS->getSuperClassType();
7171 if (RHSSuperType.isNull())
7172 break;
7173
7174 RHS = RHSSuperType->castAs<ObjCObjectType>();
7175 }
7176
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007177 return QualType();
7178}
7179
John McCall8b07ec22010-05-15 11:32:37 +00007180bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7181 const ObjCObjectType *RHS) {
7182 assert(LHS->getInterface() && "LHS is not an interface type");
7183 assert(RHS->getInterface() && "RHS is not an interface type");
7184
Chris Lattner49af6a42008-04-07 06:51:04 +00007185 // Verify that the base decls are compatible: the RHS must be a subclass of
7186 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007187 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7188 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7189 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007190 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007191
Douglas Gregore83b9562015-07-07 03:57:53 +00007192 // If the LHS has protocol qualifiers, determine whether all of them are
7193 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7194 // LHS).
7195 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007196 // OK if conversion of LHS to SuperClass results in narrowing of types
7197 // ; i.e., SuperClass may implement at least one of the protocols
7198 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7199 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7200 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7201 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7202 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7203 // qualifiers.
7204 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007205 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007206 // If there is no protocols associated with RHS, it is not a match.
7207 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007208 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007209
7210 for (const auto *LHSProto : LHS->quals()) {
7211 bool SuperImplementsProtocol = false;
7212 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7213 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7214 SuperImplementsProtocol = true;
7215 break;
7216 }
7217 if (!SuperImplementsProtocol)
7218 return false;
7219 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007220 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007221
7222 // If the LHS is specialized, we may need to check type arguments.
7223 if (LHS->isSpecialized()) {
7224 // Follow the superclass chain until we've matched the LHS class in the
7225 // hierarchy. This substitutes type arguments through.
7226 const ObjCObjectType *RHSSuper = RHS;
7227 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7228 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7229
7230 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007231 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007232 !sameObjCTypeArgs(*this, LHS->getInterface(),
7233 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007234 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007235 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007236 }
7237 }
7238
7239 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007240}
7241
Steve Naroffb7605152009-02-12 17:52:19 +00007242bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7243 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007244 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7245 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007246
Steve Naroff7cae42b2009-07-10 23:34:53 +00007247 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007248 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007249
7250 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7251 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007252}
7253
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007254bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7255 return canAssignObjCInterfaces(
7256 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7257 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7258}
7259
Mike Stump11289f42009-09-09 15:08:12 +00007260/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007261/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007262/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007263/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007264bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7265 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007266 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007267 return hasSameType(LHS, RHS);
7268
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007269 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007270}
7271
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007272bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007273 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007274}
7275
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007276bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7277 return !mergeTypes(LHS, RHS, true).isNull();
7278}
7279
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007280/// mergeTransparentUnionType - if T is a transparent union type and a member
7281/// of T is compatible with SubType, return the merged type, else return
7282/// QualType()
7283QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7284 bool OfBlockPointer,
7285 bool Unqualified) {
7286 if (const RecordType *UT = T->getAsUnionType()) {
7287 RecordDecl *UD = UT->getDecl();
7288 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007289 for (const auto *I : UD->fields()) {
7290 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007291 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7292 if (!MT.isNull())
7293 return MT;
7294 }
7295 }
7296 }
7297
7298 return QualType();
7299}
7300
Alp Toker9cacbab2014-01-20 20:26:09 +00007301/// mergeFunctionParameterTypes - merge two types which appear as function
7302/// parameter types
7303QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7304 bool OfBlockPointer,
7305 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007306 // GNU extension: two types are compatible if they appear as a function
7307 // argument, one of the types is a transparent union type and the other
7308 // type is compatible with a union member
7309 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7310 Unqualified);
7311 if (!lmerge.isNull())
7312 return lmerge;
7313
7314 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7315 Unqualified);
7316 if (!rmerge.isNull())
7317 return rmerge;
7318
7319 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7320}
7321
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007322QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007323 bool OfBlockPointer,
7324 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007325 const FunctionType *lbase = lhs->getAs<FunctionType>();
7326 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007327 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7328 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007329 bool allLTypes = true;
7330 bool allRTypes = true;
7331
7332 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007333 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007334 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007335 QualType RHS = rbase->getReturnType();
7336 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007337 bool UnqualifiedResult = Unqualified;
7338 if (!UnqualifiedResult)
7339 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007340 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007341 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007342 else
Alp Toker314cc812014-01-25 16:55:45 +00007343 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007344 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007345 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007346
7347 if (Unqualified)
7348 retType = retType.getUnqualifiedType();
7349
Alp Toker314cc812014-01-25 16:55:45 +00007350 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7351 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007352 if (Unqualified) {
7353 LRetType = LRetType.getUnqualifiedType();
7354 RRetType = RRetType.getUnqualifiedType();
7355 }
7356
7357 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007358 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007359 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007360 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007361
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007362 // FIXME: double check this
7363 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7364 // rbase->getRegParmAttr() != 0 &&
7365 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007366 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7367 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007368
Douglas Gregor8c940862010-01-18 17:14:39 +00007369 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007370 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007371 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007372
John McCall8c6b56f2010-12-15 01:06:38 +00007373 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007374 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7375 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007376 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7377 return QualType();
7378
John McCall31168b02011-06-15 23:02:42 +00007379 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7380 return QualType();
7381
John McCall8c6b56f2010-12-15 01:06:38 +00007382 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7383 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007384
Rafael Espindola8778c282012-11-29 16:09:03 +00007385 if (lbaseInfo.getNoReturn() != NoReturn)
7386 allLTypes = false;
7387 if (rbaseInfo.getNoReturn() != NoReturn)
7388 allRTypes = false;
7389
John McCall31168b02011-06-15 23:02:42 +00007390 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007391
Eli Friedman47f77112008-08-22 00:56:42 +00007392 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007393 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7394 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007395 // Compatible functions must have the same number of parameters
7396 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007397 return QualType();
7398
7399 // Variadic and non-variadic functions aren't compatible
7400 if (lproto->isVariadic() != rproto->isVariadic())
7401 return QualType();
7402
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007403 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7404 return QualType();
7405
Fariborz Jahanian97676972011-09-28 21:52:05 +00007406 if (LangOpts.ObjCAutoRefCount &&
7407 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7408 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007409
7410 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007411 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007412 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7413 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7414 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7415 QualType paramType = mergeFunctionParameterTypes(
7416 lParamType, rParamType, OfBlockPointer, Unqualified);
7417 if (paramType.isNull())
7418 return QualType();
7419
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007420 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007421 paramType = paramType.getUnqualifiedType();
7422
7423 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007424 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007425 lParamType = lParamType.getUnqualifiedType();
7426 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007427 }
Alp Toker601b22c2014-01-21 23:35:24 +00007428
7429 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007430 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007431 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007432 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007433 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007434
Eli Friedman47f77112008-08-22 00:56:42 +00007435 if (allLTypes) return lhs;
7436 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007437
7438 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7439 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007440 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007441 }
7442
7443 if (lproto) allRTypes = false;
7444 if (rproto) allLTypes = false;
7445
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007446 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007447 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007448 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007449 if (proto->isVariadic()) return QualType();
7450 // Check that the types are compatible with the types that
7451 // would result from default argument promotions (C99 6.7.5.3p15).
7452 // The only types actually affected are promotable integer
7453 // types and floats, which would be passed as a different
7454 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007455 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7456 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007457
Eli Friedman448ce402012-08-30 00:44:15 +00007458 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007459 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007460 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7461 paramTy = Enum->getDecl()->getIntegerType();
7462 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007463 return QualType();
7464 }
Alp Toker601b22c2014-01-21 23:35:24 +00007465
7466 if (paramTy->isPromotableIntegerType() ||
7467 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007468 return QualType();
7469 }
7470
7471 if (allLTypes) return lhs;
7472 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007473
7474 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7475 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007476 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007477 }
7478
7479 if (allLTypes) return lhs;
7480 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007481 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007482}
7483
John McCall433c2e62013-03-21 00:10:07 +00007484/// Given that we have an enum type and a non-enum type, try to merge them.
7485static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7486 QualType other, bool isBlockReturnType) {
7487 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7488 // a signed integer type, or an unsigned integer type.
7489 // Compatibility is based on the underlying type, not the promotion
7490 // type.
7491 QualType underlyingType = ET->getDecl()->getIntegerType();
7492 if (underlyingType.isNull()) return QualType();
7493 if (Context.hasSameType(underlyingType, other))
7494 return other;
7495
7496 // In block return types, we're more permissive and accept any
7497 // integral type of the same size.
7498 if (isBlockReturnType && other->isIntegerType() &&
7499 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7500 return other;
7501
7502 return QualType();
7503}
7504
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007505QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007506 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007507 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007508 // C++ [expr]: If an expression initially has the type "reference to T", the
7509 // type is adjusted to "T" prior to any further analysis, the expression
7510 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007511 // expression is an lvalue unless the reference is an rvalue reference and
7512 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007513 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7514 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007515
7516 if (Unqualified) {
7517 LHS = LHS.getUnqualifiedType();
7518 RHS = RHS.getUnqualifiedType();
7519 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007520
Eli Friedman47f77112008-08-22 00:56:42 +00007521 QualType LHSCan = getCanonicalType(LHS),
7522 RHSCan = getCanonicalType(RHS);
7523
7524 // If two types are identical, they are compatible.
7525 if (LHSCan == RHSCan)
7526 return LHS;
7527
John McCall8ccfcb52009-09-24 19:53:00 +00007528 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007529 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7530 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007531 if (LQuals != RQuals) {
7532 // If any of these qualifiers are different, we have a type
7533 // mismatch.
7534 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007535 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7536 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007537 return QualType();
7538
7539 // Exactly one GC qualifier difference is allowed: __strong is
7540 // okay if the other type has no GC qualifier but is an Objective
7541 // C object pointer (i.e. implicitly strong by default). We fix
7542 // this by pretending that the unqualified type was actually
7543 // qualified __strong.
7544 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7545 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7546 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7547
7548 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7549 return QualType();
7550
7551 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7552 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7553 }
7554 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7555 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7556 }
Eli Friedman47f77112008-08-22 00:56:42 +00007557 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007558 }
7559
7560 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007561
Eli Friedmandcca6332009-06-01 01:22:52 +00007562 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7563 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007564
Chris Lattnerfd652912008-01-14 05:45:46 +00007565 // We want to consider the two function types to be the same for these
7566 // comparisons, just force one to the other.
7567 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7568 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007569
7570 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007571 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7572 LHSClass = Type::ConstantArray;
7573 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7574 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007575
John McCall8b07ec22010-05-15 11:32:37 +00007576 // ObjCInterfaces are just specialized ObjCObjects.
7577 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7578 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7579
Nate Begemance4d7fc2008-04-18 23:10:10 +00007580 // Canonicalize ExtVector -> Vector.
7581 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7582 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007583
Chris Lattner95554662008-04-07 05:43:21 +00007584 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007585 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007586 // Note that we only have special rules for turning block enum
7587 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007588 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007589 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007590 }
John McCall9dd450b2009-09-21 23:43:11 +00007591 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007592 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007593 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007594 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007595 if (OfBlockPointer && !BlockReturnType) {
7596 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7597 return LHS;
7598 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7599 return RHS;
7600 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007601
Eli Friedman47f77112008-08-22 00:56:42 +00007602 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007603 }
Eli Friedman47f77112008-08-22 00:56:42 +00007604
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007605 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007606 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007607#define TYPE(Class, Base)
7608#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007609#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007610#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7611#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7612#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007613 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007614
Richard Smith27d807c2013-04-30 13:56:41 +00007615 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007616 case Type::LValueReference:
7617 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007618 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007619 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007620
John McCall8b07ec22010-05-15 11:32:37 +00007621 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007622 case Type::IncompleteArray:
7623 case Type::VariableArray:
7624 case Type::FunctionProto:
7625 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007626 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007627
Chris Lattnerfd652912008-01-14 05:45:46 +00007628 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007629 {
7630 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007631 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7632 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007633 if (Unqualified) {
7634 LHSPointee = LHSPointee.getUnqualifiedType();
7635 RHSPointee = RHSPointee.getUnqualifiedType();
7636 }
7637 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7638 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007639 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007640 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007641 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007642 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007643 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007644 return getPointerType(ResultType);
7645 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007646 case Type::BlockPointer:
7647 {
7648 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007649 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7650 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007651 if (Unqualified) {
7652 LHSPointee = LHSPointee.getUnqualifiedType();
7653 RHSPointee = RHSPointee.getUnqualifiedType();
7654 }
7655 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7656 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007657 if (ResultType.isNull()) return QualType();
7658 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7659 return LHS;
7660 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7661 return RHS;
7662 return getBlockPointerType(ResultType);
7663 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007664 case Type::Atomic:
7665 {
7666 // Merge two pointer types, while trying to preserve typedef info
7667 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7668 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7669 if (Unqualified) {
7670 LHSValue = LHSValue.getUnqualifiedType();
7671 RHSValue = RHSValue.getUnqualifiedType();
7672 }
7673 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7674 Unqualified);
7675 if (ResultType.isNull()) return QualType();
7676 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7677 return LHS;
7678 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7679 return RHS;
7680 return getAtomicType(ResultType);
7681 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007682 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007683 {
7684 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7685 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7686 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7687 return QualType();
7688
7689 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7690 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007691 if (Unqualified) {
7692 LHSElem = LHSElem.getUnqualifiedType();
7693 RHSElem = RHSElem.getUnqualifiedType();
7694 }
7695
7696 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007697 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007698 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7699 return LHS;
7700 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7701 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007702 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7703 ArrayType::ArraySizeModifier(), 0);
7704 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7705 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007706 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7707 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007708 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7709 return LHS;
7710 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7711 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007712 if (LVAT) {
7713 // FIXME: This isn't correct! But tricky to implement because
7714 // the array's size has to be the size of LHS, but the type
7715 // has to be different.
7716 return LHS;
7717 }
7718 if (RVAT) {
7719 // FIXME: This isn't correct! But tricky to implement because
7720 // the array's size has to be the size of RHS, but the type
7721 // has to be different.
7722 return RHS;
7723 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007724 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7725 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007726 return getIncompleteArrayType(ResultType,
7727 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007728 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007729 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007730 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007731 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007732 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007733 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007734 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007735 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007736 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007737 case Type::Complex:
7738 // Distinct complex types are incompatible.
7739 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007740 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007741 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007742 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7743 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007744 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007745 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007746 case Type::ObjCObject: {
7747 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007748 // FIXME: This should be type compatibility, e.g. whether
7749 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007750 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7751 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7752 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007753 return LHS;
7754
Eli Friedman47f77112008-08-22 00:56:42 +00007755 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007756 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007757 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007758 if (OfBlockPointer) {
7759 if (canAssignObjCInterfacesInBlockPointer(
7760 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007761 RHS->getAs<ObjCObjectPointerType>(),
7762 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007763 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007764 return QualType();
7765 }
John McCall9dd450b2009-09-21 23:43:11 +00007766 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7767 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007768 return LHS;
7769
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007770 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007771 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007772 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007773
David Blaikie8a40f702012-01-17 06:56:22 +00007774 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007775}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007776
Fariborz Jahanian97676972011-09-28 21:52:05 +00007777bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7778 const FunctionProtoType *FromFunctionType,
7779 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007780 if (FromFunctionType->hasAnyConsumedParams() !=
7781 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007782 return false;
7783 FunctionProtoType::ExtProtoInfo FromEPI =
7784 FromFunctionType->getExtProtoInfo();
7785 FunctionProtoType::ExtProtoInfo ToEPI =
7786 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007787 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007788 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7789 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007790 return false;
7791 }
7792 return true;
7793}
7794
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007795/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7796/// 'RHS' attributes and returns the merged version; including for function
7797/// return types.
7798QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7799 QualType LHSCan = getCanonicalType(LHS),
7800 RHSCan = getCanonicalType(RHS);
7801 // If two types are identical, they are compatible.
7802 if (LHSCan == RHSCan)
7803 return LHS;
7804 if (RHSCan->isFunctionType()) {
7805 if (!LHSCan->isFunctionType())
7806 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007807 QualType OldReturnType =
7808 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007809 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007810 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007811 QualType ResReturnType =
7812 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7813 if (ResReturnType.isNull())
7814 return QualType();
7815 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7816 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7817 // In either case, use OldReturnType to build the new function type.
7818 const FunctionType *F = LHS->getAs<FunctionType>();
7819 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007820 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7821 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007822 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007823 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007824 return ResultType;
7825 }
7826 }
7827 return QualType();
7828 }
7829
7830 // If the qualifiers are different, the types can still be merged.
7831 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7832 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7833 if (LQuals != RQuals) {
7834 // If any of these qualifiers are different, we have a type mismatch.
7835 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7836 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7837 return QualType();
7838
7839 // Exactly one GC qualifier difference is allowed: __strong is
7840 // okay if the other type has no GC qualifier but is an Objective
7841 // C object pointer (i.e. implicitly strong by default). We fix
7842 // this by pretending that the unqualified type was actually
7843 // qualified __strong.
7844 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7845 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7846 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7847
7848 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7849 return QualType();
7850
7851 if (GC_L == Qualifiers::Strong)
7852 return LHS;
7853 if (GC_R == Qualifiers::Strong)
7854 return RHS;
7855 return QualType();
7856 }
7857
7858 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7859 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7860 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7861 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7862 if (ResQT == LHSBaseQT)
7863 return LHS;
7864 if (ResQT == RHSBaseQT)
7865 return RHS;
7866 }
7867 return QualType();
7868}
7869
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007870//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007871// Integer Predicates
7872//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007873
Jay Foad39c79802011-01-12 09:06:06 +00007874unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007875 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007876 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007877 if (T->isBooleanType())
7878 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007879 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007880 return (unsigned)getTypeSize(T);
7881}
7882
Abramo Bagnara13640492012-09-09 10:21:24 +00007883QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007884 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007885
7886 // Turn <4 x signed int> -> <4 x unsigned int>
7887 if (const VectorType *VTy = T->getAs<VectorType>())
7888 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007889 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007890
7891 // For enums, we return the unsigned version of the base type.
7892 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007893 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007894
7895 const BuiltinType *BTy = T->getAs<BuiltinType>();
7896 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007897 switch (BTy->getKind()) {
7898 case BuiltinType::Char_S:
7899 case BuiltinType::SChar:
7900 return UnsignedCharTy;
7901 case BuiltinType::Short:
7902 return UnsignedShortTy;
7903 case BuiltinType::Int:
7904 return UnsignedIntTy;
7905 case BuiltinType::Long:
7906 return UnsignedLongTy;
7907 case BuiltinType::LongLong:
7908 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007909 case BuiltinType::Int128:
7910 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007911 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007912 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007913 }
7914}
7915
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007916ASTMutationListener::~ASTMutationListener() { }
7917
Richard Smith1fa5d642013-05-11 05:45:24 +00007918void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7919 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007920
7921//===----------------------------------------------------------------------===//
7922// Builtin Type Computation
7923//===----------------------------------------------------------------------===//
7924
7925/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007926/// pointer over the consumed characters. This returns the resultant type. If
7927/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7928/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7929/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007930///
7931/// RequiresICE is filled in on return to indicate whether the value is required
7932/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007933static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007934 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007935 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007936 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007937 // Modifiers.
7938 int HowLong = 0;
7939 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007940 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007941
Chris Lattnerdc226c22010-10-01 22:42:38 +00007942 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007943 bool Done = false;
7944 while (!Done) {
7945 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007946 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007947 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007948 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007949 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007950 case 'S':
7951 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7952 assert(!Signed && "Can't use 'S' modifier multiple times!");
7953 Signed = true;
7954 break;
7955 case 'U':
7956 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007957 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007958 Unsigned = true;
7959 break;
7960 case 'L':
7961 assert(HowLong <= 2 && "Can't have LLLL modifier");
7962 ++HowLong;
7963 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007964 case 'W':
7965 // This modifier represents int64 type.
7966 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7967 switch (Context.getTargetInfo().getInt64Type()) {
7968 default:
7969 llvm_unreachable("Unexpected integer type");
7970 case TargetInfo::SignedLong:
7971 HowLong = 1;
7972 break;
7973 case TargetInfo::SignedLongLong:
7974 HowLong = 2;
7975 break;
7976 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007977 }
7978 }
7979
7980 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007981
Chris Lattnerecd79c62009-06-14 00:45:47 +00007982 // Read the base type.
7983 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007984 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007985 case 'v':
7986 assert(HowLong == 0 && !Signed && !Unsigned &&
7987 "Bad modifiers used with 'v'!");
7988 Type = Context.VoidTy;
7989 break;
Jack Carter24bef982013-08-15 15:16:57 +00007990 case 'h':
7991 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00007992 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00007993 Type = Context.HalfTy;
7994 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007995 case 'f':
7996 assert(HowLong == 0 && !Signed && !Unsigned &&
7997 "Bad modifiers used with 'f'!");
7998 Type = Context.FloatTy;
7999 break;
8000 case 'd':
8001 assert(HowLong < 2 && !Signed && !Unsigned &&
8002 "Bad modifiers used with 'd'!");
8003 if (HowLong)
8004 Type = Context.LongDoubleTy;
8005 else
8006 Type = Context.DoubleTy;
8007 break;
8008 case 's':
8009 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8010 if (Unsigned)
8011 Type = Context.UnsignedShortTy;
8012 else
8013 Type = Context.ShortTy;
8014 break;
8015 case 'i':
8016 if (HowLong == 3)
8017 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8018 else if (HowLong == 2)
8019 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8020 else if (HowLong == 1)
8021 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8022 else
8023 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8024 break;
8025 case 'c':
8026 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8027 if (Signed)
8028 Type = Context.SignedCharTy;
8029 else if (Unsigned)
8030 Type = Context.UnsignedCharTy;
8031 else
8032 Type = Context.CharTy;
8033 break;
8034 case 'b': // boolean
8035 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8036 Type = Context.BoolTy;
8037 break;
8038 case 'z': // size_t.
8039 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8040 Type = Context.getSizeType();
8041 break;
8042 case 'F':
8043 Type = Context.getCFConstantStringType();
8044 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008045 case 'G':
8046 Type = Context.getObjCIdType();
8047 break;
8048 case 'H':
8049 Type = Context.getObjCSelType();
8050 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008051 case 'M':
8052 Type = Context.getObjCSuperType();
8053 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008054 case 'a':
8055 Type = Context.getBuiltinVaListType();
8056 assert(!Type.isNull() && "builtin va list type not initialized!");
8057 break;
8058 case 'A':
8059 // This is a "reference" to a va_list; however, what exactly
8060 // this means depends on how va_list is defined. There are two
8061 // different kinds of va_list: ones passed by value, and ones
8062 // passed by reference. An example of a by-value va_list is
8063 // x86, where va_list is a char*. An example of by-ref va_list
8064 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8065 // we want this argument to be a char*&; for x86-64, we want
8066 // it to be a __va_list_tag*.
8067 Type = Context.getBuiltinVaListType();
8068 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008069 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008070 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008071 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008072 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008073 break;
8074 case 'V': {
8075 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008076 unsigned NumElements = strtoul(Str, &End, 10);
8077 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008078 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008079
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008080 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8081 RequiresICE, false);
8082 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008083
8084 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008085 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008086 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008087 break;
8088 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008089 case 'E': {
8090 char *End;
8091
8092 unsigned NumElements = strtoul(Str, &End, 10);
8093 assert(End != Str && "Missing vector size");
8094
8095 Str = End;
8096
8097 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8098 false);
8099 Type = Context.getExtVectorType(ElementType, NumElements);
8100 break;
8101 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008102 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008103 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8104 false);
8105 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008106 Type = Context.getComplexType(ElementType);
8107 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008108 }
8109 case 'Y' : {
8110 Type = Context.getPointerDiffType();
8111 break;
8112 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008113 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008114 Type = Context.getFILEType();
8115 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008116 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008117 return QualType();
8118 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008119 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008120 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008121 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008122 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008123 else
8124 Type = Context.getjmp_bufType();
8125
Mike Stump2adb4da2009-07-28 23:47:15 +00008126 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008127 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008128 return QualType();
8129 }
8130 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008131 case 'K':
8132 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8133 Type = Context.getucontext_tType();
8134
8135 if (Type.isNull()) {
8136 Error = ASTContext::GE_Missing_ucontext;
8137 return QualType();
8138 }
8139 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008140 case 'p':
8141 Type = Context.getProcessIDType();
8142 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008143 }
Mike Stump11289f42009-09-09 15:08:12 +00008144
Chris Lattnerdc226c22010-10-01 22:42:38 +00008145 // If there are modifiers and if we're allowed to parse them, go for it.
8146 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008147 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008148 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008149 default: Done = true; --Str; break;
8150 case '*':
8151 case '&': {
8152 // Both pointers and references can have their pointee types
8153 // qualified with an address space.
8154 char *End;
8155 unsigned AddrSpace = strtoul(Str, &End, 10);
8156 if (End != Str && AddrSpace != 0) {
8157 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8158 Str = End;
8159 }
8160 if (c == '*')
8161 Type = Context.getPointerType(Type);
8162 else
8163 Type = Context.getLValueReferenceType(Type);
8164 break;
8165 }
8166 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8167 case 'C':
8168 Type = Type.withConst();
8169 break;
8170 case 'D':
8171 Type = Context.getVolatileType(Type);
8172 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008173 case 'R':
8174 Type = Type.withRestrict();
8175 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008176 }
8177 }
Chris Lattner84733392010-10-01 07:13:18 +00008178
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008179 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008180 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008181
Chris Lattnerecd79c62009-06-14 00:45:47 +00008182 return Type;
8183}
8184
8185/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008186QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008187 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008188 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008189 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008190
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008191 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008192
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008193 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008194 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008195 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8196 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008197 if (Error != GE_None)
8198 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008199
8200 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8201
Chris Lattnerecd79c62009-06-14 00:45:47 +00008202 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008203 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008204 if (Error != GE_None)
8205 return QualType();
8206
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008207 // If this argument is required to be an IntegerConstantExpression and the
8208 // caller cares, fill in the bitmask we return.
8209 if (RequiresICE && IntegerConstantArgs)
8210 *IntegerConstantArgs |= 1 << ArgTypes.size();
8211
Chris Lattnerecd79c62009-06-14 00:45:47 +00008212 // Do array -> pointer decay. The builtin should use the decayed type.
8213 if (Ty->isArrayType())
8214 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008215
Chris Lattnerecd79c62009-06-14 00:45:47 +00008216 ArgTypes.push_back(Ty);
8217 }
8218
David Majnemerba3e5ec2015-03-13 18:26:17 +00008219 if (Id == Builtin::BI__GetExceptionInfo)
8220 return QualType();
8221
Chris Lattnerecd79c62009-06-14 00:45:47 +00008222 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8223 "'.' should only occur at end of builtin type list!");
8224
Reid Kleckner78af0702013-08-27 23:08:25 +00008225 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008226 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8227
8228 bool Variadic = (TypeStr[0] == '.');
8229
8230 // We really shouldn't be making a no-proto type here, especially in C++.
8231 if (ArgTypes.empty() && Variadic)
8232 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008233
John McCalldb40c7f2010-12-14 08:05:40 +00008234 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008235 EPI.ExtInfo = EI;
8236 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008237
Jordan Rose5c382722013-03-08 21:51:21 +00008238 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008239}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008240
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008241static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8242 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008243 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008244 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008245
Rafael Espindola3ae00052013-05-13 00:12:11 +00008246 GVALinkage External = GVA_StrongExternal;
8247 switch (FD->getTemplateSpecializationKind()) {
8248 case TSK_Undeclared:
8249 case TSK_ExplicitSpecialization:
8250 External = GVA_StrongExternal;
8251 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008252
Rafael Espindola3ae00052013-05-13 00:12:11 +00008253 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008254 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008255
David Majnemerc3d07332014-05-15 06:25:57 +00008256 // C++11 [temp.explicit]p10:
8257 // [ Note: The intent is that an inline function that is the subject of
8258 // an explicit instantiation declaration will still be implicitly
8259 // instantiated when used so that the body can be considered for
8260 // inlining, but that no out-of-line copy of the inline function would be
8261 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008262 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008263 return GVA_AvailableExternally;
8264
Rafael Espindola3ae00052013-05-13 00:12:11 +00008265 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008266 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008267 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008268 }
8269
8270 if (!FD->isInlined())
8271 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008272
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008273 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
8274 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008275 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008276 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8277
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008278 // GNU or C99 inline semantics. Determine whether this symbol should be
8279 // externally visible.
8280 if (FD->isInlineDefinitionExternallyVisible())
8281 return External;
8282
8283 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008284 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008285 }
8286
David Majnemer54e3ba52014-04-02 23:17:29 +00008287 // Functions specified with extern and inline in -fms-compatibility mode
8288 // forcibly get emitted. While the body of the function cannot be later
8289 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008290 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008291 return GVA_StrongODR;
8292
David Majnemer27d69db2014-04-28 22:17:59 +00008293 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008294}
8295
Artem Belevich7b41f702015-09-23 17:44:53 +00008296static GVALinkage adjustGVALinkageForAttributes(GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008297 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8298 // dllexport/dllimport on inline functions.
8299 if (D->hasAttr<DLLImportAttr>()) {
8300 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8301 return GVA_AvailableExternally;
Artem Belevich7b41f702015-09-23 17:44:53 +00008302 } else if (D->hasAttr<DLLExportAttr>() || D->hasAttr<CUDAGlobalAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008303 if (L == GVA_DiscardableODR)
8304 return GVA_StrongODR;
8305 }
8306 return L;
8307}
8308
8309GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevich7b41f702015-09-23 17:44:53 +00008310 return adjustGVALinkageForAttributes(basicGVALinkageForFunction(*this, FD),
8311 FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008312}
8313
8314static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8315 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008316 if (!VD->isExternallyVisible())
8317 return GVA_Internal;
8318
David Majnemer27d69db2014-04-28 22:17:59 +00008319 if (VD->isStaticLocal()) {
8320 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8321 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8322 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8323 LexicalContext = LexicalContext->getLexicalParent();
8324
Richard Smith9e2341d2015-03-23 03:25:59 +00008325 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008326 // enclosing function.
8327 if (LexicalContext)
8328 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008329 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008330
8331 // GVA_StrongODR function linkage is stronger than what we need,
8332 // downgrade to GVA_DiscardableODR.
8333 // This allows us to discard the variable if we never end up needing it.
8334 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8335 : StaticLocalLinkage;
8336 }
8337
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008338 // MSVC treats in-class initialized static data members as definitions.
8339 // By giving them non-strong linkage, out-of-line definitions won't
8340 // cause link errors.
8341 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8342 return GVA_DiscardableODR;
8343
Richard Smith8809a0c2013-09-27 20:14:12 +00008344 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008345 case TSK_Undeclared:
Rafael Espindola3ae00052013-05-13 00:12:11 +00008346 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008347
David Majnemer6d1780c2015-07-17 23:36:49 +00008348 case TSK_ExplicitSpecialization:
8349 return Context.getLangOpts().MSVCCompat && VD->isStaticDataMember()
8350 ? GVA_StrongODR
8351 : GVA_StrongExternal;
8352
Rafael Espindola3ae00052013-05-13 00:12:11 +00008353 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008354 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008355
David Majnemer27d69db2014-04-28 22:17:59 +00008356 case TSK_ExplicitInstantiationDeclaration:
8357 return GVA_AvailableExternally;
8358
Rafael Espindola3ae00052013-05-13 00:12:11 +00008359 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008360 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008361 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008362
8363 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008364}
8365
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008366GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevich7b41f702015-09-23 17:44:53 +00008367 return adjustGVALinkageForAttributes(basicGVALinkageForVariable(*this, VD),
8368 VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008369}
8370
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008371bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008372 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8373 if (!VD->isFileVarDecl())
8374 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008375 // Global named register variables (GNU extension) are never emitted.
8376 if (VD->getStorageClass() == SC_Register)
8377 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008378 if (VD->getDescribedVarTemplate() ||
8379 isa<VarTemplatePartialSpecializationDecl>(VD))
8380 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008381 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8382 // We never need to emit an uninstantiated function template.
8383 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8384 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008385 } else if (isa<OMPThreadPrivateDecl>(D))
8386 return true;
8387 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008388 return false;
8389
8390 // If this is a member of a class template, we do not need to emit it.
8391 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008392 return false;
8393
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008394 // Weak references don't produce any output by themselves.
8395 if (D->hasAttr<WeakRefAttr>())
8396 return false;
8397
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008398 // Aliases and used decls are required.
8399 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8400 return true;
8401
8402 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8403 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008404 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008405 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008406
8407 // Constructors and destructors are required.
8408 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8409 return true;
8410
John McCall6bd2a892013-01-25 22:31:03 +00008411 // The key function for a class is required. This rule only comes
8412 // into play when inline functions can be key functions, though.
8413 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8414 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8415 const CXXRecordDecl *RD = MD->getParent();
8416 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8417 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8418 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8419 return true;
8420 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008421 }
8422 }
8423
8424 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8425
8426 // static, static inline, always_inline, and extern inline functions can
8427 // always be deferred. Normal inline functions can be deferred in C99/C++.
8428 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008429 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8430 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008431 return false;
8432 return true;
8433 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008434
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008435 const VarDecl *VD = cast<VarDecl>(D);
8436 assert(VD->isFileVarDecl() && "Expected file scoped var");
8437
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008438 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8439 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008440 return false;
8441
Richard Smitha0e5e542012-11-12 21:38:00 +00008442 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008443 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008444 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8445 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008446 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008447
Richard Smitha0e5e542012-11-12 21:38:00 +00008448 // Variables that have destruction with side-effects are required.
8449 if (VD->getType().isDestructedType())
8450 return true;
8451
8452 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008453 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8454 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008455 return true;
8456
8457 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008458}
Charles Davis53c59df2010-08-16 03:33:14 +00008459
Reid Kleckner78af0702013-08-27 23:08:25 +00008460CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8461 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008462 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008463 if (IsCXXMethod)
8464 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008465
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008466 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8467
8468 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008469}
8470
Jay Foad39c79802011-01-12 09:06:06 +00008471bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008472 // Pass through to the C++ ABI object
8473 return ABI->isNearlyEmpty(RD);
8474}
8475
Reid Kleckner96f8f932014-02-05 17:27:08 +00008476VTableContextBase *ASTContext::getVTableContext() {
8477 if (!VTContext.get()) {
8478 if (Target->getCXXABI().isMicrosoft())
8479 VTContext.reset(new MicrosoftVTableContext(*this));
8480 else
8481 VTContext.reset(new ItaniumVTableContext(*this));
8482 }
8483 return VTContext.get();
8484}
8485
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008486MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008487 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008488 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008489 case TargetCXXABI::GenericItanium:
8490 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008491 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008492 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008493 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008494 case TargetCXXABI::WebAssembly:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008495 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008496 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008497 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008498 }
David Blaikie83d382b2011-09-23 05:06:16 +00008499 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008500}
8501
Charles Davis53c59df2010-08-16 03:33:14 +00008502CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008503
8504size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008505 return ASTRecordLayouts.getMemorySize() +
8506 llvm::capacity_in_bytes(ObjCLayouts) +
8507 llvm::capacity_in_bytes(KeyFunctions) +
8508 llvm::capacity_in_bytes(ObjCImpls) +
8509 llvm::capacity_in_bytes(BlockVarCopyInits) +
8510 llvm::capacity_in_bytes(DeclAttrs) +
8511 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8512 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8513 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8514 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8515 llvm::capacity_in_bytes(OverriddenMethods) +
8516 llvm::capacity_in_bytes(Types) +
8517 llvm::capacity_in_bytes(VariableArrayTypes) +
8518 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008519}
Ted Kremenek540017e2011-10-06 05:00:56 +00008520
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008521/// getIntTypeForBitwidth -
8522/// sets integer QualTy according to specified details:
8523/// bitwidth, signed/unsigned.
8524/// Returns empty type if there is no appropriate target types.
8525QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8526 unsigned Signed) const {
8527 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8528 CanQualType QualTy = getFromTargetType(Ty);
8529 if (!QualTy && DestWidth == 128)
8530 return Signed ? Int128Ty : UnsignedInt128Ty;
8531 return QualTy;
8532}
8533
8534/// getRealTypeForBitwidth -
8535/// sets floating point QualTy according to specified bitwidth.
8536/// Returns empty type if there is no appropriate target types.
8537QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8538 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8539 switch (Ty) {
8540 case TargetInfo::Float:
8541 return FloatTy;
8542 case TargetInfo::Double:
8543 return DoubleTy;
8544 case TargetInfo::LongDouble:
8545 return LongDoubleTy;
8546 case TargetInfo::NoFloat:
8547 return QualType();
8548 }
8549
8550 llvm_unreachable("Unhandled TargetInfo::RealType value");
8551}
8552
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008553void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8554 if (Number > 1)
8555 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008556}
8557
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008558unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8559 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8560 MangleNumbers.find(ND);
8561 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008562}
8563
David Majnemer2206bf52014-03-05 08:57:59 +00008564void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8565 if (Number > 1)
8566 StaticLocalNumbers[VD] = Number;
8567}
8568
8569unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8570 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8571 StaticLocalNumbers.find(VD);
8572 return I != StaticLocalNumbers.end() ? I->second : 1;
8573}
8574
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008575MangleNumberingContext &
8576ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008577 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8578 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8579 if (!MCtx)
8580 MCtx = createMangleNumberingContext();
8581 return *MCtx;
8582}
8583
8584MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8585 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008586}
8587
David Majnemere7a818f2015-03-06 18:53:55 +00008588const CXXConstructorDecl *
8589ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8590 return ABI->getCopyConstructorForExceptionObject(
8591 cast<CXXRecordDecl>(RD->getFirstDecl()));
8592}
8593
8594void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8595 CXXConstructorDecl *CD) {
8596 return ABI->addCopyConstructorForExceptionObject(
8597 cast<CXXRecordDecl>(RD->getFirstDecl()),
8598 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8599}
8600
David Majnemerdfa6d202015-03-11 18:36:39 +00008601void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8602 unsigned ParmIdx, Expr *DAE) {
8603 ABI->addDefaultArgExprForConstructor(
8604 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8605}
8606
8607Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8608 unsigned ParmIdx) {
8609 return ABI->getDefaultArgExprForConstructor(
8610 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8611}
8612
David Majnemer00350522015-08-31 18:48:39 +00008613void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8614 TypedefNameDecl *DD) {
8615 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8616}
8617
8618TypedefNameDecl *
8619ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8620 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8621}
8622
8623void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8624 DeclaratorDecl *DD) {
8625 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8626}
8627
8628DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8629 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8630}
8631
Ted Kremenek540017e2011-10-06 05:00:56 +00008632void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8633 ParamIndices[D] = index;
8634}
8635
8636unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8637 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8638 assert(I != ParamIndices.end() &&
8639 "ParmIndices lacks entry set by ParmVarDecl");
8640 return I->second;
8641}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008642
Richard Smithe6c01442013-06-05 00:46:14 +00008643APValue *
8644ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8645 bool MayCreate) {
8646 assert(E && E->getStorageDuration() == SD_Static &&
8647 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008648 if (MayCreate) {
8649 APValue *&MTVI = MaterializedTemporaryValues[E];
8650 if (!MTVI)
8651 MTVI = new (*this) APValue;
8652 return MTVI;
8653 }
Richard Smithe6c01442013-06-05 00:46:14 +00008654
David Majnemer2dcef9e2015-08-13 23:50:15 +00008655 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008656}
8657
Fariborz Jahanian615de762013-05-28 17:37:39 +00008658bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8659 const llvm::Triple &T = getTargetInfo().getTriple();
8660 if (!T.isOSDarwin())
8661 return false;
8662
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008663 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8664 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8665 return false;
8666
Fariborz Jahanian615de762013-05-28 17:37:39 +00008667 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8668 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8669 uint64_t Size = sizeChars.getQuantity();
8670 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8671 unsigned Align = alignChars.getQuantity();
8672 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8673 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8674}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008675
8676namespace {
8677
8678 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8679 /// parents as defined by the \c RecursiveASTVisitor.
8680 ///
8681 /// Note that the relationship described here is purely in terms of AST
8682 /// traversal - there are other relationships (for example declaration context)
8683 /// in the AST that are better modeled by special matchers.
8684 ///
8685 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8686 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8687
8688 public:
8689 /// \brief Builds and returns the translation unit's parent map.
8690 ///
8691 /// The caller takes ownership of the returned \c ParentMap.
8692 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8693 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8694 Visitor.TraverseDecl(&TU);
8695 return Visitor.Parents;
8696 }
8697
8698 private:
8699 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8700
8701 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8702 }
8703
8704 bool shouldVisitTemplateInstantiations() const {
8705 return true;
8706 }
8707 bool shouldVisitImplicitCode() const {
8708 return true;
8709 }
8710 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8711 // are not triggered during data recursion.
8712 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8713 return false;
8714 }
8715
8716 template <typename T>
8717 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008718 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008719 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008720 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008721 // FIXME: Currently we add the same parent multiple times, but only
8722 // when no memoization data is available for the type.
8723 // For example when we visit all subexpressions of template
8724 // instantiations; this is suboptimal, but benign: the only way to
8725 // visit those is with hasAncestor / hasParent, and those do not create
8726 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008727 // The plan is to enable DynTypedNode to be storable in a map or hash
8728 // map. The main problem there is to implement hash functions /
8729 // comparison operators for all types that DynTypedNode supports that
8730 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008731 auto &NodeOrVector = (*Parents)[Node];
8732 if (NodeOrVector.isNull()) {
8733 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008734 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008735 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8736 auto *Node =
8737 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8738 auto *Vector = new ASTContext::ParentVector(1, *Node);
8739 NodeOrVector = Vector;
8740 delete Node;
8741 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008742 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008743
8744 auto *Vector =
8745 NodeOrVector.template get<ASTContext::ParentVector *>();
8746 // Skip duplicates for types that have memoization data.
8747 // We must check that the type has memoization data before calling
8748 // std::find() because DynTypedNode::operator== can't compare all
8749 // types.
8750 bool Found = ParentStack.back().getMemoizationData() &&
8751 std::find(Vector->begin(), Vector->end(),
8752 ParentStack.back()) != Vector->end();
8753 if (!Found)
8754 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008755 }
8756 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008757 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8758 bool Result = (this ->* traverse) (Node);
8759 ParentStack.pop_back();
8760 return Result;
8761 }
8762
8763 bool TraverseDecl(Decl *DeclNode) {
8764 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8765 }
8766
8767 bool TraverseStmt(Stmt *StmtNode) {
8768 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8769 }
8770
8771 ASTContext::ParentMap *Parents;
8772 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8773
8774 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8775 };
8776
8777} // end namespace
8778
Benjamin Kramer07935292014-10-04 17:01:26 +00008779ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008780ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8781 assert(Node.getMemoizationData() &&
8782 "Invariant broken: only nodes that support memoization may be "
8783 "used in the parent map.");
8784 if (!AllParents) {
8785 // We always need to run over the whole translation unit, as
8786 // hasAncestor can escape any subtree.
8787 AllParents.reset(
8788 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8789 }
8790 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8791 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008792 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008793 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008794 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8795 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008796 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008797 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008798}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008799
8800bool
8801ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8802 const ObjCMethodDecl *MethodImpl) {
8803 // No point trying to match an unavailable/deprecated mothod.
8804 if (MethodDecl->hasAttr<UnavailableAttr>()
8805 || MethodDecl->hasAttr<DeprecatedAttr>())
8806 return false;
8807 if (MethodDecl->getObjCDeclQualifier() !=
8808 MethodImpl->getObjCDeclQualifier())
8809 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008810 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008811 return false;
8812
8813 if (MethodDecl->param_size() != MethodImpl->param_size())
8814 return false;
8815
8816 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8817 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8818 EF = MethodDecl->param_end();
8819 IM != EM && IF != EF; ++IM, ++IF) {
8820 const ParmVarDecl *DeclVar = (*IF);
8821 const ParmVarDecl *ImplVar = (*IM);
8822 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8823 return false;
8824 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8825 return false;
8826 }
8827 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8828
8829}
Richard Smith053f6c62014-05-16 23:01:30 +00008830
8831// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8832// doesn't include ASTContext.h
8833template
8834clang::LazyGenerationalUpdatePtr<
8835 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8836clang::LazyGenerationalUpdatePtr<
8837 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8838 const clang::ASTContext &Ctx, Decl *Value);