blob: a9d606c60dc47b81cdbd55a9a636ca79ddf404a8 [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:
John McCall359b8852013-01-25 22:30:49 +0000685 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000686 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000687 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000688 return CreateMicrosoftCXXABI(*this);
689 }
David Blaikie8a40f702012-01-17 06:56:22 +0000690 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000691}
692
Douglas Gregore8bbc122011-09-02 00:18:52 +0000693static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000694 const LangOptions &LOpts) {
695 if (LOpts.FakeAddressSpaceMap) {
696 // The fake address space map must have a distinct entry for each
697 // language-specific address space.
698 static const unsigned FakeAddrSpaceMap[] = {
699 1, // opencl_global
700 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000701 3, // opencl_constant
702 4, // cuda_device
703 5, // cuda_constant
704 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000705 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000706 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000707 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000708 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000709 }
710}
711
David Tweed31d09b02013-09-13 12:04:22 +0000712static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
713 const LangOptions &LangOpts) {
714 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000715 case LangOptions::ASMM_Target:
716 return TI.useAddressSpaceMapMangling();
717 case LangOptions::ASMM_On:
718 return true;
719 case LangOptions::ASMM_Off:
720 return false;
721 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000722 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000723}
724
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000725ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000726 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000727 Builtin::Context &builtins)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000728 : FunctionProtoTypes(this_()),
729 TemplateSpecializationTypes(this_()),
730 DependentTemplateSpecializationTypes(this_()),
731 SubstTemplateTemplateParmPacks(this_()),
Craig Topper36250ad2014-05-12 05:36:57 +0000732 GlobalNestedNameSpecifier(nullptr),
733 Int128Decl(nullptr), UInt128Decl(nullptr), Float128StubDecl(nullptr),
734 BuiltinVaListDecl(nullptr),
735 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
736 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
737 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
738 FILEDecl(nullptr),
739 jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
740 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
741 cudaConfigureCallDecl(nullptr),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000742 NullTypeSourceInfo(QualType()),
743 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000744 SourceMgr(SM), LangOpts(LOpts),
Craig Topper36250ad2014-05-12 05:36:57 +0000745 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000746 Idents(idents), Selectors(sels),
747 BuiltinInfo(builtins),
748 DeclarationNames(*this),
Craig Topper36250ad2014-05-12 05:36:57 +0000749 ExternalSource(nullptr), Listener(nullptr),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000750 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000751 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Craig Topper36250ad2014-05-12 05:36:57 +0000752 LastSDM(nullptr, 0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000753{
Daniel Dunbar221fa942008-08-11 04:54:23 +0000754 TUDecl = TranslationUnitDecl::Create(*this);
755}
756
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000757ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000758 ReleaseParentMapEntries();
759
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000760 // Release the DenseMaps associated with DeclContext objects.
761 // FIXME: Is this the ideal solution?
762 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000763
Manuel Klimeka7328992013-06-03 13:51:33 +0000764 // Call all of the deallocation functions on all of their targets.
765 for (DeallocationMap::const_iterator I = Deallocations.begin(),
766 E = Deallocations.end(); I != E; ++I)
767 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
768 (I->first)((I->second)[J]);
769
Ted Kremenek076baeb2010-06-08 23:00:58 +0000770 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000771 // because they can contain DenseMaps.
772 for (llvm::DenseMap<const ObjCContainerDecl*,
773 const ASTRecordLayout*>::iterator
774 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
777 R->Destroy(*this);
778
Ted Kremenek076baeb2010-06-08 23:00:58 +0000779 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
780 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
781 // Increment in loop to prevent using deallocated memory.
782 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
783 R->Destroy(*this);
784 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000785
786 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
787 AEnd = DeclAttrs.end();
788 A != AEnd; ++A)
789 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000790
Reid Kleckner588c9372014-02-19 23:44:52 +0000791 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000792}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000793
Manuel Klimek95403e62014-05-21 13:28:59 +0000794void ASTContext::ReleaseParentMapEntries() {
795 if (!AllParents) return;
796 for (const auto &Entry : *AllParents) {
797 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
798 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
799 } else {
800 assert(Entry.second.is<ParentVector *>());
801 delete Entry.second.get<ParentVector *>();
802 }
803 }
804}
805
Douglas Gregor1a809332010-05-23 18:26:36 +0000806void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000807 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000808}
809
Mike Stump11289f42009-09-09 15:08:12 +0000810void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000811ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
812 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000813}
814
Chris Lattner4eb445d2007-01-26 01:27:23 +0000815void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000816 llvm::errs() << "\n*** AST Context Stats:\n";
817 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000818
Douglas Gregora30d0462009-05-26 14:40:08 +0000819 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000820#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000821#define ABSTRACT_TYPE(Name, Parent)
822#include "clang/AST/TypeNodes.def"
823 0 // Extra
824 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000825
Chris Lattner4eb445d2007-01-26 01:27:23 +0000826 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
827 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000828 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000829 }
830
Douglas Gregora30d0462009-05-26 14:40:08 +0000831 unsigned Idx = 0;
832 unsigned TotalBytes = 0;
833#define TYPE(Name, Parent) \
834 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000835 llvm::errs() << " " << counts[Idx] << " " << #Name \
836 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000837 TotalBytes += counts[Idx] * sizeof(Name##Type); \
838 ++Idx;
839#define ABSTRACT_TYPE(Name, Parent)
840#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000841
Chandler Carruth3c147a72011-07-04 05:32:14 +0000842 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
843
Douglas Gregor7454c562010-07-02 20:37:36 +0000844 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000845 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
846 << NumImplicitDefaultConstructors
847 << " implicit default constructors created\n";
848 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
849 << NumImplicitCopyConstructors
850 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000851 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000852 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
853 << NumImplicitMoveConstructors
854 << " implicit move constructors created\n";
855 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
856 << NumImplicitCopyAssignmentOperators
857 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000858 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000859 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
860 << NumImplicitMoveAssignmentOperators
861 << " implicit move assignment operators created\n";
862 llvm::errs() << NumImplicitDestructorsDeclared << "/"
863 << NumImplicitDestructors
864 << " implicit destructors created\n";
865
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000866 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000867 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000868 ExternalSource->PrintStats();
869 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000870
Douglas Gregor5b11d492010-07-25 17:53:33 +0000871 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000872}
873
Alp Toker2dea15b2013-12-17 01:22:38 +0000874RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
875 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000876 SourceLocation Loc;
877 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000878 if (getLangOpts().CPlusPlus)
879 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
880 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000881 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000882 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
883 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000884 NewDecl->setImplicit();
885 return NewDecl;
886}
887
888TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
889 StringRef Name) const {
890 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
891 TypedefDecl *NewDecl = TypedefDecl::Create(
892 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
893 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
894 NewDecl->setImplicit();
895 return NewDecl;
896}
897
Douglas Gregor801c99d2011-08-12 06:49:56 +0000898TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000899 if (!Int128Decl)
900 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000901 return Int128Decl;
902}
903
904TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000905 if (!UInt128Decl)
906 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000907 return UInt128Decl;
908}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000909
Nico Webere1687c52013-06-20 21:44:55 +0000910TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000911 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000912 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000913 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000914
Nico Webere1687c52013-06-20 21:44:55 +0000915 return Float128StubDecl;
916}
917
John McCall48f2d582009-10-23 23:03:21 +0000918void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000919 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000920 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000921 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000922}
923
Douglas Gregore8bbc122011-09-02 00:18:52 +0000924void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
925 assert((!this->Target || this->Target == &Target) &&
926 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000927 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000928
Douglas Gregore8bbc122011-09-02 00:18:52 +0000929 this->Target = &Target;
930
931 ABI.reset(createCXXABI(Target));
932 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000933 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000934
Chris Lattner970e54e2006-11-12 00:37:36 +0000935 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000936 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000937
Chris Lattner970e54e2006-11-12 00:37:36 +0000938 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000939 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000940 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000941 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000942 InitBuiltinType(CharTy, BuiltinType::Char_S);
943 else
944 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000945 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000946 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
947 InitBuiltinType(ShortTy, BuiltinType::Short);
948 InitBuiltinType(IntTy, BuiltinType::Int);
949 InitBuiltinType(LongTy, BuiltinType::Long);
950 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000951
Chris Lattner970e54e2006-11-12 00:37:36 +0000952 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000953 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
954 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
955 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
956 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
957 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000958
Chris Lattner970e54e2006-11-12 00:37:36 +0000959 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000960 InitBuiltinType(FloatTy, BuiltinType::Float);
961 InitBuiltinType(DoubleTy, BuiltinType::Double);
962 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000963
Chris Lattnerf122cef2009-04-30 02:43:43 +0000964 // GNU extension, 128-bit integers.
965 InitBuiltinType(Int128Ty, BuiltinType::Int128);
966 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
967
Hans Wennborg0d81e012013-05-10 10:08:40 +0000968 // C++ 3.9.1p5
969 if (TargetInfo::isTypeSigned(Target.getWCharType()))
970 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
971 else // -fshort-wchar makes wchar_t be unsigned.
972 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
973 if (LangOpts.CPlusPlus && LangOpts.WChar)
974 WideCharTy = WCharTy;
975 else {
976 // C99 (or C++ using -fno-wchar).
977 WideCharTy = getFromTargetType(Target.getWCharType());
978 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000979
James Molloy36365542012-05-04 10:55:22 +0000980 WIntTy = getFromTargetType(Target.getWIntType());
981
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000982 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
983 InitBuiltinType(Char16Ty, BuiltinType::Char16);
984 else // C99
985 Char16Ty = getFromTargetType(Target.getChar16Type());
986
987 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
988 InitBuiltinType(Char32Ty, BuiltinType::Char32);
989 else // C99
990 Char32Ty = getFromTargetType(Target.getChar32Type());
991
Douglas Gregor4619e432008-12-05 23:32:09 +0000992 // Placeholder type for type-dependent expressions whose type is
993 // completely unknown. No code should ever check a type against
994 // DependentTy and users should never see it; however, it is here to
995 // help diagnose failures to properly check for type-dependent
996 // expressions.
997 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000998
John McCall36e7fe32010-10-12 00:20:44 +0000999 // Placeholder type for functions.
1000 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1001
John McCall0009fcc2011-04-26 20:42:42 +00001002 // Placeholder type for bound members.
1003 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1004
John McCall526ab472011-10-25 17:37:35 +00001005 // Placeholder type for pseudo-objects.
1006 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1007
John McCall31996342011-04-07 08:22:57 +00001008 // "any" type; useful for debugger-like clients.
1009 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1010
John McCall8a6b59a2011-10-17 18:09:15 +00001011 // Placeholder type for unbridged ARC casts.
1012 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1013
Eli Friedman34866c72012-08-31 00:14:07 +00001014 // Placeholder type for builtin functions.
1015 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1016
Chris Lattner970e54e2006-11-12 00:37:36 +00001017 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001018 FloatComplexTy = getComplexType(FloatTy);
1019 DoubleComplexTy = getComplexType(DoubleTy);
1020 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001021
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001022 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001023 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1024 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001025 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001026
1027 if (LangOpts.OpenCL) {
1028 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1029 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1030 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1031 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1032 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1033 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001034
Guy Benyei61054192013-02-07 10:55:47 +00001035 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001036 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001037 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001038
1039 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001040 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1041 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001042
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001043 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001044
1045 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001046
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001047 // void * type
1048 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001049
1050 // nullptr type (C++0x 2.14.7)
1051 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001052
1053 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1054 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001055
1056 // Builtin type used to help define __builtin_va_list.
1057 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001058}
1059
David Blaikie9c902b52011-09-25 23:23:43 +00001060DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001061 return SourceMgr.getDiagnostics();
1062}
1063
Douglas Gregor561eceb2010-08-30 16:49:28 +00001064AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1065 AttrVec *&Result = DeclAttrs[D];
1066 if (!Result) {
1067 void *Mem = Allocate(sizeof(AttrVec));
1068 Result = new (Mem) AttrVec;
1069 }
1070
1071 return *Result;
1072}
1073
1074/// \brief Erase the attributes corresponding to the given declaration.
1075void ASTContext::eraseDeclAttrs(const Decl *D) {
1076 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1077 if (Pos != DeclAttrs.end()) {
1078 Pos->second->~AttrVec();
1079 DeclAttrs.erase(Pos);
1080 }
1081}
1082
Larisse Voufo39a1e502013-08-06 01:03:05 +00001083// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001084MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001085ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001086 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001087 return getTemplateOrSpecializationInfo(Var)
1088 .dyn_cast<MemberSpecializationInfo *>();
1089}
1090
1091ASTContext::TemplateOrSpecializationInfo
1092ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1093 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1094 TemplateOrInstantiation.find(Var);
1095 if (Pos == TemplateOrInstantiation.end())
1096 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001097
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001098 return Pos->second;
1099}
1100
Mike Stump11289f42009-09-09 15:08:12 +00001101void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001102ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001103 TemplateSpecializationKind TSK,
1104 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001105 assert(Inst->isStaticDataMember() && "Not a static data member");
1106 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001107 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1108 Tmpl, TSK, PointOfInstantiation));
1109}
1110
1111void
1112ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1113 TemplateOrSpecializationInfo TSI) {
1114 assert(!TemplateOrInstantiation[Inst] &&
1115 "Already noted what the variable was instantiated from");
1116 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001117}
1118
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001119FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1120 const FunctionDecl *FD){
1121 assert(FD && "Specialization is 0");
1122 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001123 = ClassScopeSpecializationPattern.find(FD);
1124 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001125 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001126
1127 return Pos->second;
1128}
1129
1130void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1131 FunctionDecl *Pattern) {
1132 assert(FD && "Specialization is 0");
1133 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001134 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001135}
1136
John McCalle61f2ba2009-11-18 02:36:19 +00001137NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001138ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001139 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001140 = InstantiatedFromUsingDecl.find(UUD);
1141 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001142 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001143
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001144 return Pos->second;
1145}
1146
1147void
John McCallb96ec562009-12-04 22:46:56 +00001148ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1149 assert((isa<UsingDecl>(Pattern) ||
1150 isa<UnresolvedUsingValueDecl>(Pattern) ||
1151 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1152 "pattern decl is not a using decl");
1153 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1154 InstantiatedFromUsingDecl[Inst] = Pattern;
1155}
1156
1157UsingShadowDecl *
1158ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1159 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1160 = InstantiatedFromUsingShadowDecl.find(Inst);
1161 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001162 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001163
1164 return Pos->second;
1165}
1166
1167void
1168ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1169 UsingShadowDecl *Pattern) {
1170 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1171 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001172}
1173
Anders Carlsson5da84842009-09-01 04:26:58 +00001174FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1175 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1176 = InstantiatedFromUnnamedFieldDecl.find(Field);
1177 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001178 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001179
Anders Carlsson5da84842009-09-01 04:26:58 +00001180 return Pos->second;
1181}
1182
1183void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1184 FieldDecl *Tmpl) {
1185 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1186 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1187 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1188 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001189
Anders Carlsson5da84842009-09-01 04:26:58 +00001190 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1191}
1192
Douglas Gregor832940b2010-03-02 23:58:15 +00001193ASTContext::overridden_cxx_method_iterator
1194ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1195 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001196 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001197 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001198 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001199
1200 return Pos->second.begin();
1201}
1202
1203ASTContext::overridden_cxx_method_iterator
1204ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1205 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001206 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001207 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001208 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001209
1210 return Pos->second.end();
1211}
1212
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001213unsigned
1214ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1215 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001216 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001217 if (Pos == OverriddenMethods.end())
1218 return 0;
1219
1220 return Pos->second.size();
1221}
1222
Douglas Gregor832940b2010-03-02 23:58:15 +00001223void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1224 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001225 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001226 OverriddenMethods[Method].push_back(Overridden);
1227}
1228
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001229void ASTContext::getOverriddenMethods(
1230 const NamedDecl *D,
1231 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001232 assert(D);
1233
1234 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001235 Overridden.append(overridden_methods_begin(CXXMethod),
1236 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001237 return;
1238 }
1239
1240 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1241 if (!Method)
1242 return;
1243
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001244 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1245 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001246 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001247}
1248
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001249void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1250 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1251 assert(!Import->isFromASTFile() && "Non-local import declaration");
1252 if (!FirstLocalImport) {
1253 FirstLocalImport = Import;
1254 LastLocalImport = Import;
1255 return;
1256 }
1257
1258 LastLocalImport->NextLocalImport = Import;
1259 LastLocalImport = Import;
1260}
1261
Chris Lattner53cfe802007-07-18 17:52:12 +00001262//===----------------------------------------------------------------------===//
1263// Type Sizing and Analysis
1264//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001265
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001266/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1267/// scalar floating point type.
1268const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001269 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001270 assert(BT && "Not a floating point type!");
1271 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001272 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001273 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001274 case BuiltinType::Float: return Target->getFloatFormat();
1275 case BuiltinType::Double: return Target->getDoubleFormat();
1276 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001277 }
1278}
1279
Rafael Espindola71eccb32013-08-08 19:53:46 +00001280CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001281 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001282
John McCall94268702010-10-08 18:24:19 +00001283 bool UseAlignAttrOnly = false;
1284 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1285 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001286
John McCall94268702010-10-08 18:24:19 +00001287 // __attribute__((aligned)) can increase or decrease alignment
1288 // *except* on a struct or struct member, where it only increases
1289 // alignment unless 'packed' is also specified.
1290 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001291 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001292 // ignore that possibility; Sema should diagnose it.
1293 if (isa<FieldDecl>(D)) {
1294 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1295 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1296 } else {
1297 UseAlignAttrOnly = true;
1298 }
1299 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001300 else if (isa<FieldDecl>(D))
1301 UseAlignAttrOnly =
1302 D->hasAttr<PackedAttr>() ||
1303 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001304
John McCall4e819612011-01-20 07:57:12 +00001305 // If we're using the align attribute only, just ignore everything
1306 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001307 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001308 // do nothing
1309
John McCall94268702010-10-08 18:24:19 +00001310 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001311 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001312 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001313 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001314 T = RT->getPointeeType();
1315 else
1316 T = getPointerType(RT->getPointeeType());
1317 }
Richard Smithf6d70302014-06-10 23:34:28 +00001318 QualType BaseT = getBaseElementType(T);
1319 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001320 // Adjust alignments of declarations with array type by the
1321 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001322 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001323 unsigned MinWidth = Target->getLargeArrayMinWidth();
1324 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001325 if (isa<VariableArrayType>(arrayType))
1326 Align = std::max(Align, Target->getLargeArrayAlign());
1327 else if (isa<ConstantArrayType>(arrayType) &&
1328 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1329 Align = std::max(Align, Target->getLargeArrayAlign());
1330 }
John McCall33ddac02011-01-19 10:06:00 +00001331 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001332 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001333 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1334 if (VD->hasGlobalStorage())
1335 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1336 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001337 }
John McCall4e819612011-01-20 07:57:12 +00001338
1339 // Fields can be subject to extra alignment constraints, like if
1340 // the field is packed, the struct is packed, or the struct has a
1341 // a max-field-alignment constraint (#pragma pack). So calculate
1342 // the actual alignment of the field within the struct, and then
1343 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001344 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1345 const RecordDecl *Parent = Field->getParent();
1346 // We can only produce a sensible answer if the record is valid.
1347 if (!Parent->isInvalidDecl()) {
1348 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001349
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001350 // Start with the record's overall alignment.
1351 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001352
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001353 // Use the GCD of that and the offset within the record.
1354 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1355 if (Offset > 0) {
1356 // Alignment is always a power of 2, so the GCD will be a power of 2,
1357 // which means we get to do this crazy thing instead of Euclid's.
1358 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1359 if (LowBitOfOffset < FieldAlign)
1360 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1361 }
1362
1363 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001364 }
Charles Davis3fc51072010-02-23 04:52:00 +00001365 }
Chris Lattner68061312009-01-24 21:53:27 +00001366 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001367
Ken Dyckcc56c542011-01-15 18:38:59 +00001368 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001369}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001370
John McCallf1249922012-08-21 04:10:00 +00001371// getTypeInfoDataSizeInChars - Return the size of a type, in
1372// chars. If the type is a record, its data size is returned. This is
1373// the size of the memcpy that's performed when assigning this type
1374// using a trivial copy/move assignment operator.
1375std::pair<CharUnits, CharUnits>
1376ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1377 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1378
1379 // In C++, objects can sometimes be allocated into the tail padding
1380 // of a base-class subobject. We decide whether that's possible
1381 // during class layout, so here we can just trust the layout results.
1382 if (getLangOpts().CPlusPlus) {
1383 if (const RecordType *RT = T->getAs<RecordType>()) {
1384 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1385 sizeAndAlign.first = layout.getDataSize();
1386 }
1387 }
1388
1389 return sizeAndAlign;
1390}
1391
Richard Trieu04d2d942013-05-14 21:59:17 +00001392/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1393/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1394std::pair<CharUnits, CharUnits>
1395static getConstantArrayInfoInChars(const ASTContext &Context,
1396 const ConstantArrayType *CAT) {
1397 std::pair<CharUnits, CharUnits> EltInfo =
1398 Context.getTypeInfoInChars(CAT->getElementType());
1399 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001400 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1401 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001402 "Overflow in array type char size evaluation");
1403 uint64_t Width = EltInfo.first.getQuantity() * Size;
1404 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001405 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1406 Context.getTargetInfo().getPointerWidth(0) == 64)
1407 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001408 return std::make_pair(CharUnits::fromQuantity(Width),
1409 CharUnits::fromQuantity(Align));
1410}
1411
John McCall87fe5d52010-05-20 01:18:31 +00001412std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001413ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001414 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1415 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001416 TypeInfo Info = getTypeInfo(T);
1417 return std::make_pair(toCharUnitsFromBits(Info.Width),
1418 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001419}
1420
1421std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001422ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001423 return getTypeInfoInChars(T.getTypePtr());
1424}
1425
David Majnemer34b57492014-07-30 01:30:47 +00001426bool ASTContext::isAlignmentRequired(const Type *T) const {
1427 return getTypeInfo(T).AlignIsRequired;
1428}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001429
David Majnemer34b57492014-07-30 01:30:47 +00001430bool ASTContext::isAlignmentRequired(QualType T) const {
1431 return isAlignmentRequired(T.getTypePtr());
1432}
1433
1434TypeInfo ASTContext::getTypeInfo(const Type *T) const {
Rafael Espindolae122ee12014-07-30 02:37:26 +00001435 TypeInfo TI = MemoizedTypeInfo[T];
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001436 if (!TI.Align) {
1437 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1438 TI = getTypeInfoImpl(T);
1439 MemoizedTypeInfo[T] = TI;
1440 }
1441 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001442}
1443
1444/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1445/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001446///
1447/// FIXME: Pointers into different addr spaces could have different sizes and
1448/// alignment requirements: getPointerInfo should take an AddrSpace, this
1449/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001450TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1451 uint64_t Width = 0;
1452 unsigned Align = 8;
1453 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001454 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001455#define TYPE(Class, Base)
1456#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001457#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001458#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001459#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1460 case Type::Class: \
1461 assert(!T->isDependentType() && "should not see dependent types here"); \
1462 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001463#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001464 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001465
Chris Lattner355332d2007-07-13 22:27:08 +00001466 case Type::FunctionNoProto:
1467 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001468 // GCC extension: alignof(function) = 32 bits
1469 Width = 0;
1470 Align = 32;
1471 break;
1472
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001473 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001474 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001475 Width = 0;
1476 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1477 break;
1478
Steve Naroff5c131802007-08-30 01:06:46 +00001479 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001480 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001481
David Majnemer34b57492014-07-30 01:30:47 +00001482 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001483 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001484 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001485 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001486 Width = EltInfo.Width * Size;
1487 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001488 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1489 getTargetInfo().getPointerWidth(0) == 64)
1490 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001491 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001492 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001493 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001494 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001495 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001496 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1497 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001498 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001499 // If the alignment is not a power of 2, round up to the next power of 2.
1500 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001501 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001502 Align = llvm::NextPowerOf2(Align);
1503 Width = llvm::RoundUpToAlignment(Width, Align);
1504 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001505 // Adjust the alignment based on the target max.
1506 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1507 if (TargetVectorAlign && TargetVectorAlign < Align)
1508 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001509 break;
1510 }
Chris Lattner647fb222007-07-18 18:26:58 +00001511
Chris Lattner7570e9c2008-03-08 08:52:55 +00001512 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001513 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001514 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001515 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001516 // GCC extension: alignof(void) = 8 bits.
1517 Width = 0;
1518 Align = 8;
1519 break;
1520
Chris Lattner6a4f7452007-12-19 19:23:28 +00001521 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001522 Width = Target->getBoolWidth();
1523 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001524 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001525 case BuiltinType::Char_S:
1526 case BuiltinType::Char_U:
1527 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001528 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001529 Width = Target->getCharWidth();
1530 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001531 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001532 case BuiltinType::WChar_S:
1533 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001534 Width = Target->getWCharWidth();
1535 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001536 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001537 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001538 Width = Target->getChar16Width();
1539 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001540 break;
1541 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001542 Width = Target->getChar32Width();
1543 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001544 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001545 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001546 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001547 Width = Target->getShortWidth();
1548 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001549 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001550 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001551 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001552 Width = Target->getIntWidth();
1553 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001554 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001555 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001556 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001557 Width = Target->getLongWidth();
1558 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001559 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001560 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001561 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001562 Width = Target->getLongLongWidth();
1563 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001564 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001565 case BuiltinType::Int128:
1566 case BuiltinType::UInt128:
1567 Width = 128;
1568 Align = 128; // int128_t is 128-bit aligned on all targets.
1569 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001570 case BuiltinType::Half:
1571 Width = Target->getHalfWidth();
1572 Align = Target->getHalfAlign();
1573 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001574 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001575 Width = Target->getFloatWidth();
1576 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001577 break;
1578 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001579 Width = Target->getDoubleWidth();
1580 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001581 break;
1582 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001583 Width = Target->getLongDoubleWidth();
1584 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001585 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001586 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001587 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1588 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001589 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001590 case BuiltinType::ObjCId:
1591 case BuiltinType::ObjCClass:
1592 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001593 Width = Target->getPointerWidth(0);
1594 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001595 break;
Guy Benyei61054192013-02-07 10:55:47 +00001596 case BuiltinType::OCLSampler:
1597 // Samplers are modeled as integers.
1598 Width = Target->getIntWidth();
1599 Align = Target->getIntAlign();
1600 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001601 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001602 case BuiltinType::OCLImage1d:
1603 case BuiltinType::OCLImage1dArray:
1604 case BuiltinType::OCLImage1dBuffer:
1605 case BuiltinType::OCLImage2d:
1606 case BuiltinType::OCLImage2dArray:
1607 case BuiltinType::OCLImage3d:
1608 // Currently these types are pointers to opaque types.
1609 Width = Target->getPointerWidth(0);
1610 Align = Target->getPointerAlign(0);
1611 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001612 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001613 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001614 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001615 Width = Target->getPointerWidth(0);
1616 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001617 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001618 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001619 unsigned AS = getTargetAddressSpace(
1620 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001621 Width = Target->getPointerWidth(AS);
1622 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001623 break;
1624 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001625 case Type::LValueReference:
1626 case Type::RValueReference: {
1627 // alignof and sizeof should never enter this code path here, so we go
1628 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001629 unsigned AS = getTargetAddressSpace(
1630 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001631 Width = Target->getPointerWidth(AS);
1632 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001633 break;
1634 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001635 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001636 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001637 Width = Target->getPointerWidth(AS);
1638 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001639 break;
1640 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001641 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001642 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001643 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001644 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001645 }
Chris Lattner647fb222007-07-18 18:26:58 +00001646 case Type::Complex: {
1647 // Complex types have the same alignment as their elements, but twice the
1648 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001649 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1650 Width = EltInfo.Width * 2;
1651 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001652 break;
1653 }
John McCall8b07ec22010-05-15 11:32:37 +00001654 case Type::ObjCObject:
1655 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001656 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001657 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001658 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001659 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001660 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001661 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001662 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001663 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001664 break;
1665 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001666 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001667 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001668 const TagType *TT = cast<TagType>(T);
1669
1670 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001671 Width = 8;
1672 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001673 break;
1674 }
Mike Stump11289f42009-09-09 15:08:12 +00001675
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001676 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001677 return getTypeInfo(ET->getDecl()->getIntegerType());
1678
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001679 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001680 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001681 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001682 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001683 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001684 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001685
Chris Lattner63d2b362009-10-22 05:17:15 +00001686 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001687 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1688 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001689
Richard Smith30482bc2011-02-20 03:19:35 +00001690 case Type::Auto: {
1691 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001692 assert(!A->getDeducedType().isNull() &&
1693 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001694 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001695 }
1696
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001697 case Type::Paren:
1698 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1699
Douglas Gregoref462e62009-04-30 17:32:17 +00001700 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001701 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001702 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001703 // If the typedef has an aligned attribute on it, it overrides any computed
1704 // alignment we have. This violates the GCC documentation (which says that
1705 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001706 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001707 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001708 AlignIsRequired = true;
1709 } else
1710 Align = Info.Align;
1711 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001712 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001713 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001714
Abramo Bagnara6150c882010-05-11 21:36:43 +00001715 case Type::Elaborated:
1716 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001717
John McCall81904512011-01-06 01:58:22 +00001718 case Type::Attributed:
1719 return getTypeInfo(
1720 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1721
Eli Friedman0dfb8892011-10-06 23:00:33 +00001722 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001723 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001724 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1725 Width = Info.Width;
1726 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001727
1728 // If the size of the type doesn't exceed the platform's max
1729 // atomic promotion width, make the size and alignment more
1730 // favorable to atomic operations:
1731 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1732 // Round the size up to a power of 2.
1733 if (!llvm::isPowerOf2_64(Width))
1734 Width = llvm::NextPowerOf2(Width);
1735
1736 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001737 Align = static_cast<unsigned>(Width);
1738 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001739 }
1740
Douglas Gregoref462e62009-04-30 17:32:17 +00001741 }
Mike Stump11289f42009-09-09 15:08:12 +00001742
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001743 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001744 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001745}
1746
Ken Dyckcc56c542011-01-15 18:38:59 +00001747/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1748CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1749 return CharUnits::fromQuantity(BitSize / getCharWidth());
1750}
1751
Ken Dyckb0fcc592011-02-11 01:54:29 +00001752/// toBits - Convert a size in characters to a size in characters.
1753int64_t ASTContext::toBits(CharUnits CharSize) const {
1754 return CharSize.getQuantity() * getCharWidth();
1755}
1756
Ken Dyck8c89d592009-12-22 14:23:30 +00001757/// getTypeSizeInChars - Return the size of the specified type, in characters.
1758/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001759CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001760 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001761}
Jay Foad39c79802011-01-12 09:06:06 +00001762CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001763 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001764}
1765
Ken Dycka6046ab2010-01-26 17:25:18 +00001766/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001767/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001768CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001769 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001770}
Jay Foad39c79802011-01-12 09:06:06 +00001771CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001772 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001773}
1774
Chris Lattnera3402cd2009-01-27 18:08:34 +00001775/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1776/// type for the current target in bits. This can be different than the ABI
1777/// alignment in cases where it is beneficial for performance to overalign
1778/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001779unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001780 TypeInfo TI = getTypeInfo(T);
1781 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001782
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001783 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1784 return ABIAlign; // Never overalign on XCore.
1785
Eli Friedman7ab09572009-05-25 21:27:19 +00001786 // Double and long long should be naturally aligned if possible.
Richard Smithd7e1fe42014-06-10 23:43:44 +00001787 T = T->getBaseElementTypeUnsafe();
David Majnemer1d4db8f2014-02-24 23:43:27 +00001788 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001789 T = CT->getElementType().getTypePtr();
1790 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001791 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1792 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001793 // Don't increase the alignment if an alignment attribute was specified on a
1794 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001795 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001796 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001797
Chris Lattnera3402cd2009-01-27 18:08:34 +00001798 return ABIAlign;
1799}
1800
Ulrich Weigandfa806422013-05-06 16:23:57 +00001801/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1802/// to a global variable of the specified type.
1803unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1804 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1805}
1806
1807/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1808/// should be given to a global variable of the specified type.
1809CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1810 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1811}
1812
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001813/// DeepCollectObjCIvars -
1814/// This routine first collects all declared, but not synthesized, ivars in
1815/// super class and then collects all ivars, including those synthesized for
1816/// current class. This routine is used for implementation of current class
1817/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001818///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001819void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1820 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001821 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001822 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1823 DeepCollectObjCIvars(SuperClass, false, Ivars);
1824 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001825 for (const auto *I : OI->ivars())
1826 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001827 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001828 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001829 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001830 Iv= Iv->getNextIvar())
1831 Ivars.push_back(Iv);
1832 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001833}
1834
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001835/// CollectInheritedProtocols - Collect all protocols in current class and
1836/// those inherited by it.
1837void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001838 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001839 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001840 // We can use protocol_iterator here instead of
1841 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001842 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001843 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001844 for (auto *P : Proto->protocols()) {
1845 Protocols.insert(P->getCanonicalDecl());
1846 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001847 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001848 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001849
1850 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001851 for (const auto *Cat : OI->visible_categories())
1852 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001853
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001854 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1855 while (SD) {
1856 CollectInheritedProtocols(SD, Protocols);
1857 SD = SD->getSuperClass();
1858 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001859 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001860 for (auto *Proto : OC->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001861 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001862 for (const auto *P : Proto->protocols())
1863 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001864 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001865 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001866 for (auto *Proto : OP->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001867 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001868 for (const auto *P : Proto->protocols())
1869 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001870 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001871 }
1872}
1873
Jay Foad39c79802011-01-12 09:06:06 +00001874unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001875 unsigned count = 0;
1876 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001877 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001878 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001879
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001880 // Count ivar defined in this class's implementation. This
1881 // includes synthesized ivars.
1882 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001883 count += ImplDecl->ivar_size();
1884
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001885 return count;
1886}
1887
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001888bool ASTContext::isSentinelNullExpr(const Expr *E) {
1889 if (!E)
1890 return false;
1891
1892 // nullptr_t is always treated as null.
1893 if (E->getType()->isNullPtrType()) return true;
1894
1895 if (E->getType()->isAnyPointerType() &&
1896 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1897 Expr::NPC_ValueDependentIsNull))
1898 return true;
1899
1900 // Unfortunately, __null has type 'int'.
1901 if (isa<GNUNullExpr>(E)) return true;
1902
1903 return false;
1904}
1905
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001906/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1907ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1908 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1909 I = ObjCImpls.find(D);
1910 if (I != ObjCImpls.end())
1911 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001912 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001913}
1914/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1915ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1916 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1917 I = ObjCImpls.find(D);
1918 if (I != ObjCImpls.end())
1919 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001920 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001921}
1922
1923/// \brief Set the implementation of ObjCInterfaceDecl.
1924void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1925 ObjCImplementationDecl *ImplD) {
1926 assert(IFaceD && ImplD && "Passed null params");
1927 ObjCImpls[IFaceD] = ImplD;
1928}
1929/// \brief Set the implementation of ObjCCategoryDecl.
1930void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1931 ObjCCategoryImplDecl *ImplD) {
1932 assert(CatD && ImplD && "Passed null params");
1933 ObjCImpls[CatD] = ImplD;
1934}
1935
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001936const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1937 const NamedDecl *ND) const {
1938 if (const ObjCInterfaceDecl *ID =
1939 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001940 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001941 if (const ObjCCategoryDecl *CD =
1942 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001943 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001944 if (const ObjCImplDecl *IMD =
1945 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001946 return IMD->getClassInterface();
1947
Craig Topper36250ad2014-05-12 05:36:57 +00001948 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001949}
1950
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001951/// \brief Get the copy initialization expression of VarDecl,or NULL if
1952/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001953Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001954 assert(VD && "Passed null params");
1955 assert(VD->hasAttr<BlocksAttr>() &&
1956 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001957 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001958 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00001959 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001960}
1961
1962/// \brief Set the copy inialization expression of a block var decl.
1963void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1964 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001965 assert(VD->hasAttr<BlocksAttr>() &&
1966 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001967 BlockVarCopyInits[VD] = Init;
1968}
1969
John McCallbcd03502009-12-07 02:54:59 +00001970TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001971 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001972 if (!DataSize)
1973 DataSize = TypeLoc::getFullDataSizeForType(T);
1974 else
1975 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001976 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001977
John McCallbcd03502009-12-07 02:54:59 +00001978 TypeSourceInfo *TInfo =
1979 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1980 new (TInfo) TypeSourceInfo(T);
1981 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001982}
1983
John McCallbcd03502009-12-07 02:54:59 +00001984TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001985 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001986 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001987 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001988 return DI;
1989}
1990
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001991const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001992ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00001993 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001994}
1995
1996const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001997ASTContext::getASTObjCImplementationLayout(
1998 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001999 return getObjCLayout(D->getClassInterface(), D);
2000}
2001
Chris Lattner983a8bb2007-07-13 22:13:22 +00002002//===----------------------------------------------------------------------===//
2003// Type creation/memoization methods
2004//===----------------------------------------------------------------------===//
2005
Jay Foad39c79802011-01-12 09:06:06 +00002006QualType
John McCall33ddac02011-01-19 10:06:00 +00002007ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2008 unsigned fastQuals = quals.getFastQualifiers();
2009 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002010
2011 // Check if we've already instantiated this type.
2012 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002013 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002014 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002015 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2016 assert(eq->getQualifiers() == quals);
2017 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002018 }
2019
John McCall33ddac02011-01-19 10:06:00 +00002020 // If the base type is not canonical, make the appropriate canonical type.
2021 QualType canon;
2022 if (!baseType->isCanonicalUnqualified()) {
2023 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002024 canonSplit.Quals.addConsistentQualifiers(quals);
2025 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002026
2027 // Re-find the insert position.
2028 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2029 }
2030
2031 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2032 ExtQualNodes.InsertNode(eq, insertPos);
2033 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002034}
2035
Jay Foad39c79802011-01-12 09:06:06 +00002036QualType
2037ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002038 QualType CanT = getCanonicalType(T);
2039 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002040 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002041
John McCall8ccfcb52009-09-24 19:53:00 +00002042 // If we are composing extended qualifiers together, merge together
2043 // into one ExtQuals node.
2044 QualifierCollector Quals;
2045 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002046
John McCall8ccfcb52009-09-24 19:53:00 +00002047 // If this type already has an address space specified, it cannot get
2048 // another one.
2049 assert(!Quals.hasAddressSpace() &&
2050 "Type cannot be in multiple addr spaces!");
2051 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002052
John McCall8ccfcb52009-09-24 19:53:00 +00002053 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002054}
2055
Chris Lattnerd60183d2009-02-18 22:53:11 +00002056QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002057 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002058 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002059 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002060 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002061
John McCall53fa7142010-12-24 02:08:15 +00002062 if (const PointerType *ptr = T->getAs<PointerType>()) {
2063 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002064 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002065 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2066 return getPointerType(ResultType);
2067 }
2068 }
Mike Stump11289f42009-09-09 15:08:12 +00002069
John McCall8ccfcb52009-09-24 19:53:00 +00002070 // If we are composing extended qualifiers together, merge together
2071 // into one ExtQuals node.
2072 QualifierCollector Quals;
2073 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002074
John McCall8ccfcb52009-09-24 19:53:00 +00002075 // If this type already has an ObjCGC specified, it cannot get
2076 // another one.
2077 assert(!Quals.hasObjCGCAttr() &&
2078 "Type cannot have multiple ObjCGCs!");
2079 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002080
John McCall8ccfcb52009-09-24 19:53:00 +00002081 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002082}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002083
John McCall4f5019e2010-12-19 02:44:49 +00002084const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2085 FunctionType::ExtInfo Info) {
2086 if (T->getExtInfo() == Info)
2087 return T;
2088
2089 QualType Result;
2090 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002091 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002092 } else {
2093 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2094 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2095 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002096 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002097 }
2098
2099 return cast<FunctionType>(Result.getTypePtr());
2100}
2101
Richard Smith2a7d4812013-05-04 07:00:32 +00002102void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2103 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002104 FD = FD->getMostRecentDecl();
2105 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002106 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2107 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002108 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002109 if (FunctionDecl *Next = FD->getPreviousDecl())
2110 FD = Next;
2111 else
2112 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002113 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002114 if (ASTMutationListener *L = getASTMutationListener())
2115 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002116}
2117
Chris Lattnerc6395932007-06-22 20:56:16 +00002118/// getComplexType - Return the uniqued reference to the type for a complex
2119/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002120QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002121 // Unique pointers, to guarantee there is only one pointer of a particular
2122 // structure.
2123 llvm::FoldingSetNodeID ID;
2124 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002125
Craig Topper36250ad2014-05-12 05:36:57 +00002126 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002127 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2128 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002129
Chris Lattnerc6395932007-06-22 20:56:16 +00002130 // If the pointee type isn't canonical, this won't be a canonical type either,
2131 // so fill in the canonical type field.
2132 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002133 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002134 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002135
Chris Lattnerc6395932007-06-22 20:56:16 +00002136 // Get the new insert position for the node we care about.
2137 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002138 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002139 }
John McCall90d1c2d2009-09-24 23:30:46 +00002140 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002141 Types.push_back(New);
2142 ComplexTypes.InsertNode(New, InsertPos);
2143 return QualType(New, 0);
2144}
2145
Chris Lattner970e54e2006-11-12 00:37:36 +00002146/// getPointerType - Return the uniqued reference to the type for a pointer to
2147/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002148QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002149 // Unique pointers, to guarantee there is only one pointer of a particular
2150 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002151 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002152 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002153
Craig Topper36250ad2014-05-12 05:36:57 +00002154 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002155 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002156 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002157
Chris Lattner7ccecb92006-11-12 08:50:50 +00002158 // If the pointee type isn't canonical, this won't be a canonical type either,
2159 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002160 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002161 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002162 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002163
Bob Wilsonc8541f22013-03-15 17:12:43 +00002164 // Get the new insert position for the node we care about.
2165 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002166 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002167 }
John McCall90d1c2d2009-09-24 23:30:46 +00002168 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002169 Types.push_back(New);
2170 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002171 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002172}
2173
Reid Kleckner0503a872013-12-05 01:23:43 +00002174QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2175 llvm::FoldingSetNodeID ID;
2176 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002177 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002178 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2179 if (AT)
2180 return QualType(AT, 0);
2181
2182 QualType Canonical = getCanonicalType(New);
2183
2184 // Get the new insert position for the node we care about.
2185 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002186 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002187
2188 AT = new (*this, TypeAlignment)
2189 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2190 Types.push_back(AT);
2191 AdjustedTypes.InsertNode(AT, InsertPos);
2192 return QualType(AT, 0);
2193}
2194
Reid Kleckner8a365022013-06-24 17:51:48 +00002195QualType ASTContext::getDecayedType(QualType T) const {
2196 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2197
Reid Kleckner8a365022013-06-24 17:51:48 +00002198 QualType Decayed;
2199
2200 // C99 6.7.5.3p7:
2201 // A declaration of a parameter as "array of type" shall be
2202 // adjusted to "qualified pointer to type", where the type
2203 // qualifiers (if any) are those specified within the [ and ] of
2204 // the array type derivation.
2205 if (T->isArrayType())
2206 Decayed = getArrayDecayedType(T);
2207
2208 // C99 6.7.5.3p8:
2209 // A declaration of a parameter as "function returning type"
2210 // shall be adjusted to "pointer to function returning type", as
2211 // in 6.3.2.1.
2212 if (T->isFunctionType())
2213 Decayed = getPointerType(T);
2214
Reid Kleckner0503a872013-12-05 01:23:43 +00002215 llvm::FoldingSetNodeID ID;
2216 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002217 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002218 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2219 if (AT)
2220 return QualType(AT, 0);
2221
Reid Kleckner8a365022013-06-24 17:51:48 +00002222 QualType Canonical = getCanonicalType(Decayed);
2223
2224 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002225 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002226 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002227
Reid Kleckner0503a872013-12-05 01:23:43 +00002228 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2229 Types.push_back(AT);
2230 AdjustedTypes.InsertNode(AT, InsertPos);
2231 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002232}
2233
Mike Stump11289f42009-09-09 15:08:12 +00002234/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002235/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002236QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002237 assert(T->isFunctionType() && "block of function types only");
2238 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002239 // structure.
2240 llvm::FoldingSetNodeID ID;
2241 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002242
Craig Topper36250ad2014-05-12 05:36:57 +00002243 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002244 if (BlockPointerType *PT =
2245 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2246 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002247
2248 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002249 // type either so fill in the canonical type field.
2250 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002251 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002252 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002253
Steve Naroffec33ed92008-08-27 16:04:49 +00002254 // Get the new insert position for the node we care about.
2255 BlockPointerType *NewIP =
2256 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002257 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002258 }
John McCall90d1c2d2009-09-24 23:30:46 +00002259 BlockPointerType *New
2260 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002261 Types.push_back(New);
2262 BlockPointerTypes.InsertNode(New, InsertPos);
2263 return QualType(New, 0);
2264}
2265
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002266/// getLValueReferenceType - Return the uniqued reference to the type for an
2267/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002268QualType
2269ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002270 assert(getCanonicalType(T) != OverloadTy &&
2271 "Unresolved overloaded function type");
2272
Bill Wendling3708c182007-05-27 10:15:43 +00002273 // Unique pointers, to guarantee there is only one pointer of a particular
2274 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002275 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002276 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002277
Craig Topper36250ad2014-05-12 05:36:57 +00002278 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002279 if (LValueReferenceType *RT =
2280 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002281 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002282
John McCallfc93cf92009-10-22 22:37:11 +00002283 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2284
Bill Wendling3708c182007-05-27 10:15:43 +00002285 // If the referencee type isn't canonical, this won't be a canonical type
2286 // either, so fill in the canonical type field.
2287 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002288 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2289 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2290 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002291
Bill Wendling3708c182007-05-27 10:15:43 +00002292 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002293 LValueReferenceType *NewIP =
2294 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002295 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002296 }
2297
John McCall90d1c2d2009-09-24 23:30:46 +00002298 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002299 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2300 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002301 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002302 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002303
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002304 return QualType(New, 0);
2305}
2306
2307/// getRValueReferenceType - Return the uniqued reference to the type for an
2308/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002309QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002310 // Unique pointers, to guarantee there is only one pointer of a particular
2311 // structure.
2312 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002313 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002314
Craig Topper36250ad2014-05-12 05:36:57 +00002315 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002316 if (RValueReferenceType *RT =
2317 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2318 return QualType(RT, 0);
2319
John McCallfc93cf92009-10-22 22:37:11 +00002320 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2321
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002322 // If the referencee type isn't canonical, this won't be a canonical type
2323 // either, so fill in the canonical type field.
2324 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002325 if (InnerRef || !T.isCanonical()) {
2326 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2327 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002328
2329 // Get the new insert position for the node we care about.
2330 RValueReferenceType *NewIP =
2331 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002332 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002333 }
2334
John McCall90d1c2d2009-09-24 23:30:46 +00002335 RValueReferenceType *New
2336 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002337 Types.push_back(New);
2338 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002339 return QualType(New, 0);
2340}
2341
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002342/// getMemberPointerType - Return the uniqued reference to the type for a
2343/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002344QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002345 // Unique pointers, to guarantee there is only one pointer of a particular
2346 // structure.
2347 llvm::FoldingSetNodeID ID;
2348 MemberPointerType::Profile(ID, T, Cls);
2349
Craig Topper36250ad2014-05-12 05:36:57 +00002350 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002351 if (MemberPointerType *PT =
2352 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2353 return QualType(PT, 0);
2354
2355 // If the pointee or class type isn't canonical, this won't be a canonical
2356 // type either, so fill in the canonical type field.
2357 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002358 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002359 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2360
2361 // Get the new insert position for the node we care about.
2362 MemberPointerType *NewIP =
2363 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002364 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002365 }
John McCall90d1c2d2009-09-24 23:30:46 +00002366 MemberPointerType *New
2367 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002368 Types.push_back(New);
2369 MemberPointerTypes.InsertNode(New, InsertPos);
2370 return QualType(New, 0);
2371}
2372
Mike Stump11289f42009-09-09 15:08:12 +00002373/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002374/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002375QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002376 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002377 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002378 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002379 assert((EltTy->isDependentType() ||
2380 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002381 "Constant array of VLAs is illegal!");
2382
Chris Lattnere2df3f92009-05-13 04:12:56 +00002383 // Convert the array size into a canonical width matching the pointer size for
2384 // the target.
2385 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002386 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002387 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002388
Chris Lattner23b7eb62007-06-15 23:05:46 +00002389 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002390 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002391
Craig Topper36250ad2014-05-12 05:36:57 +00002392 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002393 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002394 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002395 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002396
John McCall33ddac02011-01-19 10:06:00 +00002397 // If the element type isn't canonical or has qualifiers, this won't
2398 // be a canonical type either, so fill in the canonical type field.
2399 QualType Canon;
2400 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2401 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002402 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002403 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002404 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002405
Chris Lattner36f8e652007-01-27 08:31:04 +00002406 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002407 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002408 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002409 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002410 }
Mike Stump11289f42009-09-09 15:08:12 +00002411
John McCall90d1c2d2009-09-24 23:30:46 +00002412 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002413 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002414 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002415 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002416 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002417}
2418
John McCall06549462011-01-18 08:40:38 +00002419/// getVariableArrayDecayedType - Turns the given type, which may be
2420/// variably-modified, into the corresponding type with all the known
2421/// sizes replaced with [*].
2422QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2423 // Vastly most common case.
2424 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002425
John McCall06549462011-01-18 08:40:38 +00002426 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002427
John McCall06549462011-01-18 08:40:38 +00002428 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002429 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002430 switch (ty->getTypeClass()) {
2431#define TYPE(Class, Base)
2432#define ABSTRACT_TYPE(Class, Base)
2433#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2434#include "clang/AST/TypeNodes.def"
2435 llvm_unreachable("didn't desugar past all non-canonical types?");
2436
2437 // These types should never be variably-modified.
2438 case Type::Builtin:
2439 case Type::Complex:
2440 case Type::Vector:
2441 case Type::ExtVector:
2442 case Type::DependentSizedExtVector:
2443 case Type::ObjCObject:
2444 case Type::ObjCInterface:
2445 case Type::ObjCObjectPointer:
2446 case Type::Record:
2447 case Type::Enum:
2448 case Type::UnresolvedUsing:
2449 case Type::TypeOfExpr:
2450 case Type::TypeOf:
2451 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002452 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002453 case Type::DependentName:
2454 case Type::InjectedClassName:
2455 case Type::TemplateSpecialization:
2456 case Type::DependentTemplateSpecialization:
2457 case Type::TemplateTypeParm:
2458 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002459 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002460 case Type::PackExpansion:
2461 llvm_unreachable("type should never be variably-modified");
2462
2463 // These types can be variably-modified but should never need to
2464 // further decay.
2465 case Type::FunctionNoProto:
2466 case Type::FunctionProto:
2467 case Type::BlockPointer:
2468 case Type::MemberPointer:
2469 return type;
2470
2471 // These types can be variably-modified. All these modifications
2472 // preserve structure except as noted by comments.
2473 // TODO: if we ever care about optimizing VLAs, there are no-op
2474 // optimizations available here.
2475 case Type::Pointer:
2476 result = getPointerType(getVariableArrayDecayedType(
2477 cast<PointerType>(ty)->getPointeeType()));
2478 break;
2479
2480 case Type::LValueReference: {
2481 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2482 result = getLValueReferenceType(
2483 getVariableArrayDecayedType(lv->getPointeeType()),
2484 lv->isSpelledAsLValue());
2485 break;
2486 }
2487
2488 case Type::RValueReference: {
2489 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2490 result = getRValueReferenceType(
2491 getVariableArrayDecayedType(lv->getPointeeType()));
2492 break;
2493 }
2494
Eli Friedman0dfb8892011-10-06 23:00:33 +00002495 case Type::Atomic: {
2496 const AtomicType *at = cast<AtomicType>(ty);
2497 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2498 break;
2499 }
2500
John McCall06549462011-01-18 08:40:38 +00002501 case Type::ConstantArray: {
2502 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2503 result = getConstantArrayType(
2504 getVariableArrayDecayedType(cat->getElementType()),
2505 cat->getSize(),
2506 cat->getSizeModifier(),
2507 cat->getIndexTypeCVRQualifiers());
2508 break;
2509 }
2510
2511 case Type::DependentSizedArray: {
2512 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2513 result = getDependentSizedArrayType(
2514 getVariableArrayDecayedType(dat->getElementType()),
2515 dat->getSizeExpr(),
2516 dat->getSizeModifier(),
2517 dat->getIndexTypeCVRQualifiers(),
2518 dat->getBracketsRange());
2519 break;
2520 }
2521
2522 // Turn incomplete types into [*] types.
2523 case Type::IncompleteArray: {
2524 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2525 result = getVariableArrayType(
2526 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002527 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002528 ArrayType::Normal,
2529 iat->getIndexTypeCVRQualifiers(),
2530 SourceRange());
2531 break;
2532 }
2533
2534 // Turn VLA types into [*] types.
2535 case Type::VariableArray: {
2536 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2537 result = getVariableArrayType(
2538 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002539 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002540 ArrayType::Star,
2541 vat->getIndexTypeCVRQualifiers(),
2542 vat->getBracketsRange());
2543 break;
2544 }
2545 }
2546
2547 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002548 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002549}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002550
Steve Naroffcadebd02007-08-30 18:14:25 +00002551/// getVariableArrayType - Returns a non-unique reference to the type for a
2552/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002553QualType ASTContext::getVariableArrayType(QualType EltTy,
2554 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002555 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002556 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002557 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002558 // Since we don't unique expressions, it isn't possible to unique VLA's
2559 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002560 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002561
John McCall33ddac02011-01-19 10:06:00 +00002562 // Be sure to pull qualifiers off the element type.
2563 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2564 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002565 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002566 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002567 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002568 }
2569
John McCall90d1c2d2009-09-24 23:30:46 +00002570 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002571 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002572
2573 VariableArrayTypes.push_back(New);
2574 Types.push_back(New);
2575 return QualType(New, 0);
2576}
2577
Douglas Gregor4619e432008-12-05 23:32:09 +00002578/// getDependentSizedArrayType - Returns a non-unique reference to
2579/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002580/// type.
John McCall33ddac02011-01-19 10:06:00 +00002581QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2582 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002583 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002584 unsigned elementTypeQuals,
2585 SourceRange brackets) const {
2586 assert((!numElements || numElements->isTypeDependent() ||
2587 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002588 "Size must be type- or value-dependent!");
2589
John McCall33ddac02011-01-19 10:06:00 +00002590 // Dependently-sized array types that do not have a specified number
2591 // of elements will have their sizes deduced from a dependent
2592 // initializer. We do no canonicalization here at all, which is okay
2593 // because they can't be used in most locations.
2594 if (!numElements) {
2595 DependentSizedArrayType *newType
2596 = new (*this, TypeAlignment)
2597 DependentSizedArrayType(*this, elementType, QualType(),
2598 numElements, ASM, elementTypeQuals,
2599 brackets);
2600 Types.push_back(newType);
2601 return QualType(newType, 0);
2602 }
2603
2604 // Otherwise, we actually build a new type every time, but we
2605 // also build a canonical type.
2606
2607 SplitQualType canonElementType = getCanonicalType(elementType).split();
2608
Craig Topper36250ad2014-05-12 05:36:57 +00002609 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002610 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002611 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002612 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002613 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002614
John McCall33ddac02011-01-19 10:06:00 +00002615 // Look for an existing type with these properties.
2616 DependentSizedArrayType *canonTy =
2617 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002618
John McCall33ddac02011-01-19 10:06:00 +00002619 // If we don't have one, build one.
2620 if (!canonTy) {
2621 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002622 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002623 QualType(), numElements, ASM, elementTypeQuals,
2624 brackets);
2625 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2626 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002627 }
2628
John McCall33ddac02011-01-19 10:06:00 +00002629 // Apply qualifiers from the element type to the array.
2630 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002631 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002632
John McCall33ddac02011-01-19 10:06:00 +00002633 // If we didn't need extra canonicalization for the element type,
2634 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002635 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002636 return canon;
2637
2638 // Otherwise, we need to build a type which follows the spelling
2639 // of the element type.
2640 DependentSizedArrayType *sugaredType
2641 = new (*this, TypeAlignment)
2642 DependentSizedArrayType(*this, elementType, canon, numElements,
2643 ASM, elementTypeQuals, brackets);
2644 Types.push_back(sugaredType);
2645 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002646}
2647
John McCall33ddac02011-01-19 10:06:00 +00002648QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002649 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002650 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002651 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002652 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002653
Craig Topper36250ad2014-05-12 05:36:57 +00002654 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002655 if (IncompleteArrayType *iat =
2656 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2657 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002658
2659 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002660 // either, so fill in the canonical type field. We also have to pull
2661 // qualifiers off the element type.
2662 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002663
John McCall33ddac02011-01-19 10:06:00 +00002664 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2665 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002666 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002667 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002668 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002669
2670 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002671 IncompleteArrayType *existing =
2672 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2673 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002674 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002675
John McCall33ddac02011-01-19 10:06:00 +00002676 IncompleteArrayType *newType = new (*this, TypeAlignment)
2677 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002678
John McCall33ddac02011-01-19 10:06:00 +00002679 IncompleteArrayTypes.InsertNode(newType, insertPos);
2680 Types.push_back(newType);
2681 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002682}
2683
Steve Naroff91fcddb2007-07-18 18:00:27 +00002684/// getVectorType - Return the unique reference to a vector type of
2685/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002686QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002687 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002688 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002689
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002690 // Check if we've already instantiated a vector of this type.
2691 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002692 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002693
Craig Topper36250ad2014-05-12 05:36:57 +00002694 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002695 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2696 return QualType(VTP, 0);
2697
2698 // If the element type isn't canonical, this won't be a canonical type either,
2699 // so fill in the canonical type field.
2700 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002701 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002702 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002703
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002704 // Get the new insert position for the node we care about.
2705 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002706 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002707 }
John McCall90d1c2d2009-09-24 23:30:46 +00002708 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002709 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002710 VectorTypes.InsertNode(New, InsertPos);
2711 Types.push_back(New);
2712 return QualType(New, 0);
2713}
2714
Nate Begemance4d7fc2008-04-18 23:10:10 +00002715/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002716/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002717QualType
2718ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002719 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002720
Steve Naroff91fcddb2007-07-18 18:00:27 +00002721 // Check if we've already instantiated a vector of this type.
2722 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002723 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002724 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002725 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002726 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2727 return QualType(VTP, 0);
2728
2729 // If the element type isn't canonical, this won't be a canonical type either,
2730 // so fill in the canonical type field.
2731 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002732 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002733 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002734
Steve Naroff91fcddb2007-07-18 18:00:27 +00002735 // Get the new insert position for the node we care about.
2736 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002737 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002738 }
John McCall90d1c2d2009-09-24 23:30:46 +00002739 ExtVectorType *New = new (*this, TypeAlignment)
2740 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002741 VectorTypes.InsertNode(New, InsertPos);
2742 Types.push_back(New);
2743 return QualType(New, 0);
2744}
2745
Jay Foad39c79802011-01-12 09:06:06 +00002746QualType
2747ASTContext::getDependentSizedExtVectorType(QualType vecType,
2748 Expr *SizeExpr,
2749 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002750 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002751 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002752 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002753
Craig Topper36250ad2014-05-12 05:36:57 +00002754 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002755 DependentSizedExtVectorType *Canon
2756 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2757 DependentSizedExtVectorType *New;
2758 if (Canon) {
2759 // We already have a canonical version of this array type; use it as
2760 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002761 New = new (*this, TypeAlignment)
2762 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2763 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002764 } else {
2765 QualType CanonVecTy = getCanonicalType(vecType);
2766 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002767 New = new (*this, TypeAlignment)
2768 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2769 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002770
2771 DependentSizedExtVectorType *CanonCheck
2772 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2773 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2774 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002775 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2776 } else {
2777 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2778 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002779 New = new (*this, TypeAlignment)
2780 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002781 }
2782 }
Mike Stump11289f42009-09-09 15:08:12 +00002783
Douglas Gregor758a8692009-06-17 21:51:59 +00002784 Types.push_back(New);
2785 return QualType(New, 0);
2786}
2787
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002788/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002789///
Jay Foad39c79802011-01-12 09:06:06 +00002790QualType
2791ASTContext::getFunctionNoProtoType(QualType ResultTy,
2792 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002793 const CallingConv CallConv = Info.getCC();
2794
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002795 // Unique functions, to guarantee there is only one function of a particular
2796 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002797 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002798 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002799
Craig Topper36250ad2014-05-12 05:36:57 +00002800 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002801 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002802 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002803 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002804
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002805 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002806 if (!ResultTy.isCanonical()) {
2807 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002808
Chris Lattner47955de2007-01-27 08:37:20 +00002809 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002810 FunctionNoProtoType *NewIP =
2811 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002812 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002813 }
Mike Stump11289f42009-09-09 15:08:12 +00002814
Roman Divacky65b88cd2011-03-01 17:40:53 +00002815 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002816 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002817 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002818 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002819 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002820 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002821}
2822
Douglas Gregorcd780372013-01-17 23:36:45 +00002823/// \brief Determine whether \p T is canonical as the result type of a function.
2824static bool isCanonicalResultType(QualType T) {
2825 return T.isCanonical() &&
2826 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2827 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2828}
2829
Jay Foad39c79802011-01-12 09:06:06 +00002830QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002831ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002832 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002833 size_t NumArgs = ArgArray.size();
2834
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002835 // Unique functions, to guarantee there is only one function of a particular
2836 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002837 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002838 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2839 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002840
Craig Topper36250ad2014-05-12 05:36:57 +00002841 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002842 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002843 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002844 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002845
2846 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002847 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002848 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002849 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002850 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002851 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002852 isCanonical = false;
2853
2854 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002855 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002856 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002857 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002858 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002859 CanonicalArgs.reserve(NumArgs);
2860 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002861 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002862
John McCalldb40c7f2010-12-14 08:05:40 +00002863 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002864 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002865 CanonicalEPI.ExceptionSpecType = EST_None;
2866 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002867
Douglas Gregorcd780372013-01-17 23:36:45 +00002868 // Result types do not have ARC lifetime qualifiers.
2869 QualType CanResultTy = getCanonicalType(ResultTy);
2870 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2871 Qualifiers Qs = CanResultTy.getQualifiers();
2872 Qs.removeObjCLifetime();
2873 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2874 }
2875
Jordan Rose5c382722013-03-08 21:51:21 +00002876 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002877
Chris Lattnerfd4de792007-01-27 01:15:32 +00002878 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002879 FunctionProtoType *NewIP =
2880 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002881 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002882 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002883
John McCall31168b02011-06-15 23:02:42 +00002884 // FunctionProtoType objects are allocated with extra bytes after
2885 // them for three variable size arrays at the end:
2886 // - parameter types
2887 // - exception types
2888 // - consumed-arguments flags
2889 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002890 // expression, or information used to resolve the exception
2891 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002892 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002893 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002894 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002895 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002896 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002897 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002898 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002899 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002900 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2901 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002902 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002903 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002904 Size += NumArgs * sizeof(bool);
2905
John McCalldb40c7f2010-12-14 08:05:40 +00002906 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002907 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002908 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002909 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002910 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002911 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002912}
Chris Lattneref51c202006-11-10 07:17:23 +00002913
John McCalle78aac42010-03-10 03:28:59 +00002914#ifndef NDEBUG
2915static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2916 if (!isa<CXXRecordDecl>(D)) return false;
2917 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2918 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2919 return true;
2920 if (RD->getDescribedClassTemplate() &&
2921 !isa<ClassTemplateSpecializationDecl>(RD))
2922 return true;
2923 return false;
2924}
2925#endif
2926
2927/// getInjectedClassNameType - Return the unique reference to the
2928/// injected class name type for the specified templated declaration.
2929QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002930 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002931 assert(NeedsInjectedClassNameType(Decl));
2932 if (Decl->TypeForDecl) {
2933 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002934 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002935 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2936 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2937 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2938 } else {
John McCall424cec92011-01-19 06:33:43 +00002939 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002940 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002941 Decl->TypeForDecl = newType;
2942 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002943 }
2944 return QualType(Decl->TypeForDecl, 0);
2945}
2946
Douglas Gregor83a586e2008-04-13 21:07:44 +00002947/// getTypeDeclType - Return the unique reference to the type for the
2948/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002949QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002950 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002951 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002952
Richard Smithdda56e42011-04-15 14:24:37 +00002953 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002954 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002955
John McCall96f0b5f2010-03-10 06:48:02 +00002956 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2957 "Template type parameter types are always available.");
2958
John McCall81e38502010-02-16 03:57:14 +00002959 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002960 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002961 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002962 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002963 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002964 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002965 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002966 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002967 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002968 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2969 Decl->TypeForDecl = newType;
2970 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002971 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002972 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002973
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002974 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002975}
2976
Chris Lattner32d920b2007-01-26 02:01:53 +00002977/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002978/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002979QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002980ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2981 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002982 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002983
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002984 if (Canonical.isNull())
2985 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002986 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002987 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002988 Decl->TypeForDecl = newType;
2989 Types.push_back(newType);
2990 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002991}
2992
Jay Foad39c79802011-01-12 09:06:06 +00002993QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002994 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2995
Douglas Gregorec9fd132012-01-14 16:38:05 +00002996 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002997 if (PrevDecl->TypeForDecl)
2998 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2999
John McCall424cec92011-01-19 06:33:43 +00003000 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3001 Decl->TypeForDecl = newType;
3002 Types.push_back(newType);
3003 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003004}
3005
Jay Foad39c79802011-01-12 09:06:06 +00003006QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003007 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3008
Douglas Gregorec9fd132012-01-14 16:38:05 +00003009 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003010 if (PrevDecl->TypeForDecl)
3011 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3012
John McCall424cec92011-01-19 06:33:43 +00003013 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3014 Decl->TypeForDecl = newType;
3015 Types.push_back(newType);
3016 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003017}
3018
John McCall81904512011-01-06 01:58:22 +00003019QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3020 QualType modifiedType,
3021 QualType equivalentType) {
3022 llvm::FoldingSetNodeID id;
3023 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3024
Craig Topper36250ad2014-05-12 05:36:57 +00003025 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003026 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3027 if (type) return QualType(type, 0);
3028
3029 QualType canon = getCanonicalType(equivalentType);
3030 type = new (*this, TypeAlignment)
3031 AttributedType(canon, attrKind, modifiedType, equivalentType);
3032
3033 Types.push_back(type);
3034 AttributedTypes.InsertNode(type, insertPos);
3035
3036 return QualType(type, 0);
3037}
3038
3039
John McCallcebee162009-10-18 09:09:24 +00003040/// \brief Retrieve a substitution-result type.
3041QualType
3042ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003043 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003044 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003045 && "replacement types must always be canonical");
3046
3047 llvm::FoldingSetNodeID ID;
3048 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003049 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003050 SubstTemplateTypeParmType *SubstParm
3051 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3052
3053 if (!SubstParm) {
3054 SubstParm = new (*this, TypeAlignment)
3055 SubstTemplateTypeParmType(Parm, Replacement);
3056 Types.push_back(SubstParm);
3057 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3058 }
3059
3060 return QualType(SubstParm, 0);
3061}
3062
Douglas Gregorada4b792011-01-14 02:55:32 +00003063/// \brief Retrieve a
3064QualType ASTContext::getSubstTemplateTypeParmPackType(
3065 const TemplateTypeParmType *Parm,
3066 const TemplateArgument &ArgPack) {
3067#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003068 for (const auto &P : ArgPack.pack_elements()) {
3069 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3070 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003071 }
3072#endif
3073
3074 llvm::FoldingSetNodeID ID;
3075 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003076 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003077 if (SubstTemplateTypeParmPackType *SubstParm
3078 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3079 return QualType(SubstParm, 0);
3080
3081 QualType Canon;
3082 if (!Parm->isCanonicalUnqualified()) {
3083 Canon = getCanonicalType(QualType(Parm, 0));
3084 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3085 ArgPack);
3086 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3087 }
3088
3089 SubstTemplateTypeParmPackType *SubstParm
3090 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3091 ArgPack);
3092 Types.push_back(SubstParm);
3093 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3094 return QualType(SubstParm, 0);
3095}
3096
Douglas Gregoreff93e02009-02-05 23:33:38 +00003097/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003098/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003099/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003100QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003101 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003102 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003103 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003104 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003105 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003106 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003107 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3108
3109 if (TypeParm)
3110 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003111
Chandler Carruth08836322011-05-01 00:51:33 +00003112 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003113 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003114 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003115
3116 TemplateTypeParmType *TypeCheck
3117 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3118 assert(!TypeCheck && "Template type parameter canonical type broken");
3119 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003120 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003121 TypeParm = new (*this, TypeAlignment)
3122 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003123
3124 Types.push_back(TypeParm);
3125 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3126
3127 return QualType(TypeParm, 0);
3128}
3129
John McCalle78aac42010-03-10 03:28:59 +00003130TypeSourceInfo *
3131ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3132 SourceLocation NameLoc,
3133 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003134 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003135 assert(!Name.getAsDependentTemplateName() &&
3136 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003137 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003138
3139 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003140 TemplateSpecializationTypeLoc TL =
3141 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003142 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003143 TL.setTemplateNameLoc(NameLoc);
3144 TL.setLAngleLoc(Args.getLAngleLoc());
3145 TL.setRAngleLoc(Args.getRAngleLoc());
3146 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3147 TL.setArgLocInfo(i, Args[i].getLocInfo());
3148 return DI;
3149}
3150
Mike Stump11289f42009-09-09 15:08:12 +00003151QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003152ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003153 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003154 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003155 assert(!Template.getAsDependentTemplateName() &&
3156 "No dependent template names here!");
3157
John McCall6b51f282009-11-23 01:53:49 +00003158 unsigned NumArgs = Args.size();
3159
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003160 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003161 ArgVec.reserve(NumArgs);
3162 for (unsigned i = 0; i != NumArgs; ++i)
3163 ArgVec.push_back(Args[i].getArgument());
3164
John McCall2408e322010-04-27 00:57:59 +00003165 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003166 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003167}
3168
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003169#ifndef NDEBUG
3170static bool hasAnyPackExpansions(const TemplateArgument *Args,
3171 unsigned NumArgs) {
3172 for (unsigned I = 0; I != NumArgs; ++I)
3173 if (Args[I].isPackExpansion())
3174 return true;
3175
3176 return true;
3177}
3178#endif
3179
John McCall0ad16662009-10-29 08:12:44 +00003180QualType
3181ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003182 const TemplateArgument *Args,
3183 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003184 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003185 assert(!Template.getAsDependentTemplateName() &&
3186 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003187 // Look through qualified template names.
3188 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3189 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003190
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003191 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003192 Template.getAsTemplateDecl() &&
3193 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003194 QualType CanonType;
3195 if (!Underlying.isNull())
3196 CanonType = getCanonicalType(Underlying);
3197 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003198 // We can get here with an alias template when the specialization contains
3199 // a pack expansion that does not match up with a parameter pack.
3200 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3201 "Caller must compute aliased type");
3202 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003203 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3204 NumArgs);
3205 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003206
Douglas Gregora8e02e72009-07-28 23:00:59 +00003207 // Allocate the (non-canonical) template specialization type, but don't
3208 // try to unique it: these types typically have location information that
3209 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003210 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3211 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003212 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003213 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003214 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003215 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3216 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003217
Douglas Gregor8bf42052009-02-09 18:46:07 +00003218 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003219 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003220}
3221
Mike Stump11289f42009-09-09 15:08:12 +00003222QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003223ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3224 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003225 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003226 assert(!Template.getAsDependentTemplateName() &&
3227 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003228
Douglas Gregore29139c2011-03-03 17:04:51 +00003229 // Look through qualified template names.
3230 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3231 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003232
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003233 // Build the canonical template specialization type.
3234 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003235 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003236 CanonArgs.reserve(NumArgs);
3237 for (unsigned I = 0; I != NumArgs; ++I)
3238 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3239
3240 // Determine whether this canonical template specialization type already
3241 // exists.
3242 llvm::FoldingSetNodeID ID;
3243 TemplateSpecializationType::Profile(ID, CanonTemplate,
3244 CanonArgs.data(), NumArgs, *this);
3245
Craig Topper36250ad2014-05-12 05:36:57 +00003246 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003247 TemplateSpecializationType *Spec
3248 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3249
3250 if (!Spec) {
3251 // Allocate a new canonical template specialization type.
3252 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3253 sizeof(TemplateArgument) * NumArgs),
3254 TypeAlignment);
3255 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3256 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003257 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003258 Types.push_back(Spec);
3259 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3260 }
3261
3262 assert(Spec->isDependentType() &&
3263 "Non-dependent template-id type must have a canonical type");
3264 return QualType(Spec, 0);
3265}
3266
3267QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003268ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3269 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003270 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003271 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003272 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003273
Craig Topper36250ad2014-05-12 05:36:57 +00003274 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003275 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003276 if (T)
3277 return QualType(T, 0);
3278
Douglas Gregorc42075a2010-02-04 18:10:26 +00003279 QualType Canon = NamedType;
3280 if (!Canon.isCanonical()) {
3281 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003282 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3283 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003284 (void)CheckT;
3285 }
3286
Abramo Bagnara6150c882010-05-11 21:36:43 +00003287 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003288 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003289 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003290 return QualType(T, 0);
3291}
3292
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003293QualType
Jay Foad39c79802011-01-12 09:06:06 +00003294ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003295 llvm::FoldingSetNodeID ID;
3296 ParenType::Profile(ID, InnerType);
3297
Craig Topper36250ad2014-05-12 05:36:57 +00003298 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003299 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3300 if (T)
3301 return QualType(T, 0);
3302
3303 QualType Canon = InnerType;
3304 if (!Canon.isCanonical()) {
3305 Canon = getCanonicalType(InnerType);
3306 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3307 assert(!CheckT && "Paren canonical type broken");
3308 (void)CheckT;
3309 }
3310
3311 T = new (*this) ParenType(InnerType, Canon);
3312 Types.push_back(T);
3313 ParenTypes.InsertNode(T, InsertPos);
3314 return QualType(T, 0);
3315}
3316
Douglas Gregor02085352010-03-31 20:19:30 +00003317QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3318 NestedNameSpecifier *NNS,
3319 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003320 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003321 if (Canon.isNull()) {
3322 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003323 ElaboratedTypeKeyword CanonKeyword = Keyword;
3324 if (Keyword == ETK_None)
3325 CanonKeyword = ETK_Typename;
3326
3327 if (CanonNNS != NNS || CanonKeyword != Keyword)
3328 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003329 }
3330
3331 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003332 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003333
Craig Topper36250ad2014-05-12 05:36:57 +00003334 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003335 DependentNameType *T
3336 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003337 if (T)
3338 return QualType(T, 0);
3339
Douglas Gregor02085352010-03-31 20:19:30 +00003340 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003341 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003342 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003343 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003344}
3345
Mike Stump11289f42009-09-09 15:08:12 +00003346QualType
John McCallc392f372010-06-11 00:33:02 +00003347ASTContext::getDependentTemplateSpecializationType(
3348 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003349 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003350 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003351 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003352 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003353 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003354 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3355 ArgCopy.push_back(Args[I].getArgument());
3356 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3357 ArgCopy.size(),
3358 ArgCopy.data());
3359}
3360
3361QualType
3362ASTContext::getDependentTemplateSpecializationType(
3363 ElaboratedTypeKeyword Keyword,
3364 NestedNameSpecifier *NNS,
3365 const IdentifierInfo *Name,
3366 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003367 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003368 assert((!NNS || NNS->isDependent()) &&
3369 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003370
Douglas Gregorc42075a2010-02-04 18:10:26 +00003371 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003372 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3373 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003374
Craig Topper36250ad2014-05-12 05:36:57 +00003375 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003376 DependentTemplateSpecializationType *T
3377 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003378 if (T)
3379 return QualType(T, 0);
3380
John McCallc392f372010-06-11 00:33:02 +00003381 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003382
John McCallc392f372010-06-11 00:33:02 +00003383 ElaboratedTypeKeyword CanonKeyword = Keyword;
3384 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3385
3386 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003387 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003388 for (unsigned I = 0; I != NumArgs; ++I) {
3389 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3390 if (!CanonArgs[I].structurallyEquals(Args[I]))
3391 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003392 }
3393
John McCallc392f372010-06-11 00:33:02 +00003394 QualType Canon;
3395 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3396 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3397 Name, NumArgs,
3398 CanonArgs.data());
3399
3400 // Find the insert position again.
3401 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3402 }
3403
3404 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3405 sizeof(TemplateArgument) * NumArgs),
3406 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003407 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003408 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003409 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003410 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003411 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003412}
3413
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003414QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003415 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003416 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003417 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003418
3419 assert(Pattern->containsUnexpandedParameterPack() &&
3420 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003421 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003422 PackExpansionType *T
3423 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3424 if (T)
3425 return QualType(T, 0);
3426
3427 QualType Canon;
3428 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003429 Canon = getCanonicalType(Pattern);
3430 // The canonical type might not contain an unexpanded parameter pack, if it
3431 // contains an alias template specialization which ignores one of its
3432 // parameters.
3433 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003434 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003435
Richard Smith68eea502012-07-16 00:20:35 +00003436 // Find the insert position again, in case we inserted an element into
3437 // PackExpansionTypes and invalidated our insert position.
3438 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3439 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003440 }
3441
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003442 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003443 Types.push_back(T);
3444 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003445 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003446}
3447
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003448/// CmpProtocolNames - Comparison predicate for sorting protocols
3449/// alphabetically.
3450static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3451 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003452 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003453}
3454
John McCall8b07ec22010-05-15 11:32:37 +00003455static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003456 unsigned NumProtocols) {
3457 if (NumProtocols == 0) return true;
3458
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003459 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3460 return false;
3461
John McCallfc93cf92009-10-22 22:37:11 +00003462 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003463 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3464 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003465 return false;
3466 return true;
3467}
3468
3469static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003470 unsigned &NumProtocols) {
3471 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003472
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003473 // Sort protocols, keyed by name.
3474 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3475
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003476 // Canonicalize.
3477 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3478 Protocols[I] = Protocols[I]->getCanonicalDecl();
3479
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003480 // Remove duplicates.
3481 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3482 NumProtocols = ProtocolsEnd-Protocols;
3483}
3484
John McCall8b07ec22010-05-15 11:32:37 +00003485QualType ASTContext::getObjCObjectType(QualType BaseType,
3486 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003487 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003488 // If the base type is an interface and there aren't any protocols
3489 // to add, then the interface type will do just fine.
3490 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3491 return BaseType;
3492
3493 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003494 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003495 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Craig Topper36250ad2014-05-12 05:36:57 +00003496 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003497 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3498 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003499
John McCall8b07ec22010-05-15 11:32:37 +00003500 // Build the canonical type, which has the canonical base type and
3501 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003502 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003503 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3504 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3505 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003506 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003507 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003508 unsigned UniqueCount = NumProtocols;
3509
John McCallfc93cf92009-10-22 22:37:11 +00003510 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003511 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3512 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003513 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003514 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3515 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003516 }
3517
3518 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003519 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3520 }
3521
3522 unsigned Size = sizeof(ObjCObjectTypeImpl);
3523 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3524 void *Mem = Allocate(Size, TypeAlignment);
3525 ObjCObjectTypeImpl *T =
3526 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3527
3528 Types.push_back(T);
3529 ObjCObjectTypes.InsertNode(T, InsertPos);
3530 return QualType(T, 0);
3531}
3532
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003533/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3534/// protocol list adopt all protocols in QT's qualified-id protocol
3535/// list.
3536bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3537 ObjCInterfaceDecl *IC) {
3538 if (!QT->isObjCQualifiedIdType())
3539 return false;
3540
3541 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3542 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003543 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003544 if (!IC->ClassImplementsProtocol(Proto, false))
3545 return false;
3546 }
3547 return true;
3548 }
3549 return false;
3550}
3551
3552/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3553/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3554/// of protocols.
3555bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3556 ObjCInterfaceDecl *IDecl) {
3557 if (!QT->isObjCQualifiedIdType())
3558 return false;
3559 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3560 if (!OPT)
3561 return false;
3562 if (!IDecl->hasDefinition())
3563 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003564 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3565 CollectInheritedProtocols(IDecl, InheritedProtocols);
3566 if (InheritedProtocols.empty())
3567 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003568 // Check that if every protocol in list of id<plist> conforms to a protcol
3569 // of IDecl's, then bridge casting is ok.
3570 bool Conforms = false;
3571 for (auto *Proto : OPT->quals()) {
3572 Conforms = false;
3573 for (auto *PI : InheritedProtocols) {
3574 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3575 Conforms = true;
3576 break;
3577 }
3578 }
3579 if (!Conforms)
3580 break;
3581 }
3582 if (Conforms)
3583 return true;
3584
Aaron Ballman83731462014-03-17 16:14:00 +00003585 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003586 // If both the right and left sides have qualifiers.
3587 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003588 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003589 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003590 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003591 break;
3592 }
3593 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003594 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003595 }
3596 return true;
3597}
3598
John McCall8b07ec22010-05-15 11:32:37 +00003599/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3600/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003601QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003602 llvm::FoldingSetNodeID ID;
3603 ObjCObjectPointerType::Profile(ID, ObjectT);
3604
Craig Topper36250ad2014-05-12 05:36:57 +00003605 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003606 if (ObjCObjectPointerType *QT =
3607 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3608 return QualType(QT, 0);
3609
3610 // Find the canonical object type.
3611 QualType Canonical;
3612 if (!ObjectT.isCanonical()) {
3613 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3614
3615 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003616 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3617 }
3618
Douglas Gregorf85bee62010-02-08 22:59:26 +00003619 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003620 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3621 ObjCObjectPointerType *QType =
3622 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003623
Steve Narofffb4330f2009-06-17 22:40:22 +00003624 Types.push_back(QType);
3625 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003626 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003627}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003628
Douglas Gregor1c283312010-08-11 12:19:30 +00003629/// getObjCInterfaceType - Return the unique reference to the type for the
3630/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003631QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3632 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003633 if (Decl->TypeForDecl)
3634 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003635
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003636 if (PrevDecl) {
3637 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3638 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3639 return QualType(PrevDecl->TypeForDecl, 0);
3640 }
3641
Douglas Gregor7671e532011-12-16 16:34:57 +00003642 // Prefer the definition, if there is one.
3643 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3644 Decl = Def;
3645
Douglas Gregor1c283312010-08-11 12:19:30 +00003646 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3647 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3648 Decl->TypeForDecl = T;
3649 Types.push_back(T);
3650 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003651}
3652
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003653/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3654/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003655/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003656/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003657/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003658QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003659 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003660 if (tofExpr->isTypeDependent()) {
3661 llvm::FoldingSetNodeID ID;
3662 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003663
Craig Topper36250ad2014-05-12 05:36:57 +00003664 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003665 DependentTypeOfExprType *Canon
3666 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3667 if (Canon) {
3668 // We already have a "canonical" version of an identical, dependent
3669 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003670 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003671 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003672 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003673 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003674 Canon
3675 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003676 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3677 toe = Canon;
3678 }
3679 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003680 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003681 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003682 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003683 Types.push_back(toe);
3684 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003685}
3686
Steve Naroffa773cd52007-08-01 18:02:17 +00003687/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003688/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003689/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003690/// an issue. This doesn't affect the type checker, since it operates
3691/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003692QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003693 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003694 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003695 Types.push_back(tot);
3696 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003697}
3698
Anders Carlssonad6bd352009-06-24 21:24:56 +00003699
Richard Smith8eb1d322014-06-05 20:13:13 +00003700/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3701/// nodes. This would never be helpful, since each such type has its own
3702/// expression, and would not give a significant memory saving, since there
3703/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003704QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003705 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003706
3707 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003708 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003709 // unique dependent type. Two such decltype-specifiers refer to the same
3710 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003711 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003712 llvm::FoldingSetNodeID ID;
3713 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003714
Craig Topper36250ad2014-05-12 05:36:57 +00003715 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003716 DependentDecltypeType *Canon
3717 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003718 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003719 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003720 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003721 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003722 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003723 dt = new (*this, TypeAlignment)
3724 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003725 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003726 dt = new (*this, TypeAlignment)
3727 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003728 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003729 Types.push_back(dt);
3730 return QualType(dt, 0);
3731}
3732
Alexis Hunte852b102011-05-24 22:41:36 +00003733/// getUnaryTransformationType - We don't unique these, since the memory
3734/// savings are minimal and these are rare.
3735QualType ASTContext::getUnaryTransformType(QualType BaseType,
3736 QualType UnderlyingType,
3737 UnaryTransformType::UTTKind Kind)
3738 const {
3739 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003740 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3741 Kind,
3742 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003743 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003744 Types.push_back(Ty);
3745 return QualType(Ty, 0);
3746}
3747
Richard Smith2a7d4812013-05-04 07:00:32 +00003748/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3749/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3750/// canonical deduced-but-dependent 'auto' type.
3751QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003752 bool IsDependent) const {
3753 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003754 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003755
Richard Smith2a7d4812013-05-04 07:00:32 +00003756 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003757 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003758 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003759 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003760 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3761 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003762
Richard Smith74aeef52013-04-26 16:15:35 +00003763 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003764 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003765 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003766 Types.push_back(AT);
3767 if (InsertPos)
3768 AutoTypes.InsertNode(AT, InsertPos);
3769 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003770}
3771
Eli Friedman0dfb8892011-10-06 23:00:33 +00003772/// getAtomicType - Return the uniqued reference to the atomic type for
3773/// the given value type.
3774QualType ASTContext::getAtomicType(QualType T) const {
3775 // Unique pointers, to guarantee there is only one pointer of a particular
3776 // structure.
3777 llvm::FoldingSetNodeID ID;
3778 AtomicType::Profile(ID, T);
3779
Craig Topper36250ad2014-05-12 05:36:57 +00003780 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003781 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3782 return QualType(AT, 0);
3783
3784 // If the atomic value type isn't canonical, this won't be a canonical type
3785 // either, so fill in the canonical type field.
3786 QualType Canonical;
3787 if (!T.isCanonical()) {
3788 Canonical = getAtomicType(getCanonicalType(T));
3789
3790 // Get the new insert position for the node we care about.
3791 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003792 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003793 }
3794 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3795 Types.push_back(New);
3796 AtomicTypes.InsertNode(New, InsertPos);
3797 return QualType(New, 0);
3798}
3799
Richard Smith02e85f32011-04-14 22:09:26 +00003800/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3801QualType ASTContext::getAutoDeductType() const {
3802 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003803 AutoDeductTy = QualType(
3804 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003805 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003806 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003807 return AutoDeductTy;
3808}
3809
3810/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3811QualType ASTContext::getAutoRRefDeductType() const {
3812 if (AutoRRefDeductTy.isNull())
3813 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3814 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3815 return AutoRRefDeductTy;
3816}
3817
Chris Lattnerfb072462007-01-23 05:45:31 +00003818/// getTagDeclType - Return the unique reference to the type for the
3819/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003820QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003821 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003822 // FIXME: What is the design on getTagDeclType when it requires casting
3823 // away const? mutable?
3824 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003825}
3826
Mike Stump11289f42009-09-09 15:08:12 +00003827/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3828/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3829/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003830CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003831 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003832}
Chris Lattnerfb072462007-01-23 05:45:31 +00003833
Hans Wennborg27541db2011-10-27 08:29:09 +00003834/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3835CanQualType ASTContext::getIntMaxType() const {
3836 return getFromTargetType(Target->getIntMaxType());
3837}
3838
3839/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3840CanQualType ASTContext::getUIntMaxType() const {
3841 return getFromTargetType(Target->getUIntMaxType());
3842}
3843
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003844/// getSignedWCharType - Return the type of "signed wchar_t".
3845/// Used when in C++, as a GCC extension.
3846QualType ASTContext::getSignedWCharType() const {
3847 // FIXME: derive from "Target" ?
3848 return WCharTy;
3849}
3850
3851/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3852/// Used when in C++, as a GCC extension.
3853QualType ASTContext::getUnsignedWCharType() const {
3854 // FIXME: derive from "Target" ?
3855 return UnsignedIntTy;
3856}
3857
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003858QualType ASTContext::getIntPtrType() const {
3859 return getFromTargetType(Target->getIntPtrType());
3860}
3861
3862QualType ASTContext::getUIntPtrType() const {
3863 return getCorrespondingUnsignedType(getIntPtrType());
3864}
3865
Hans Wennborg27541db2011-10-27 08:29:09 +00003866/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003867/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3868QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003869 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003870}
3871
Eli Friedman4e91899e2012-11-27 02:58:24 +00003872/// \brief Return the unique type for "pid_t" defined in
3873/// <sys/types.h>. We need this to compute the correct type for vfork().
3874QualType ASTContext::getProcessIDType() const {
3875 return getFromTargetType(Target->getProcessIDType());
3876}
3877
Chris Lattnera21ad802008-04-02 05:18:44 +00003878//===----------------------------------------------------------------------===//
3879// Type Operators
3880//===----------------------------------------------------------------------===//
3881
Jay Foad39c79802011-01-12 09:06:06 +00003882CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003883 // Push qualifiers into arrays, and then discard any remaining
3884 // qualifiers.
3885 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003886 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003887 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003888 QualType Result;
3889 if (isa<ArrayType>(Ty)) {
3890 Result = getArrayDecayedType(QualType(Ty,0));
3891 } else if (isa<FunctionType>(Ty)) {
3892 Result = getPointerType(QualType(Ty, 0));
3893 } else {
3894 Result = QualType(Ty, 0);
3895 }
3896
3897 return CanQualType::CreateUnsafe(Result);
3898}
3899
John McCall6c9dd522011-01-18 07:41:22 +00003900QualType ASTContext::getUnqualifiedArrayType(QualType type,
3901 Qualifiers &quals) {
3902 SplitQualType splitType = type.getSplitUnqualifiedType();
3903
3904 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3905 // the unqualified desugared type and then drops it on the floor.
3906 // We then have to strip that sugar back off with
3907 // getUnqualifiedDesugaredType(), which is silly.
3908 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003909 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003910
3911 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003912 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003913 quals = splitType.Quals;
3914 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003915 }
3916
John McCall6c9dd522011-01-18 07:41:22 +00003917 // Otherwise, recurse on the array's element type.
3918 QualType elementType = AT->getElementType();
3919 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3920
3921 // If that didn't change the element type, AT has no qualifiers, so we
3922 // can just use the results in splitType.
3923 if (elementType == unqualElementType) {
3924 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003925 quals = splitType.Quals;
3926 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003927 }
3928
3929 // Otherwise, add in the qualifiers from the outermost type, then
3930 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003931 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003932
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003933 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003934 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003935 CAT->getSizeModifier(), 0);
3936 }
3937
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003938 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003939 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003940 }
3941
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003942 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003943 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003944 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003945 VAT->getSizeModifier(),
3946 VAT->getIndexTypeCVRQualifiers(),
3947 VAT->getBracketsRange());
3948 }
3949
3950 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003951 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003952 DSAT->getSizeModifier(), 0,
3953 SourceRange());
3954}
3955
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003956/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3957/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3958/// they point to and return true. If T1 and T2 aren't pointer types
3959/// or pointer-to-member types, or if they are not similar at this
3960/// level, returns false and leaves T1 and T2 unchanged. Top-level
3961/// qualifiers on T1 and T2 are ignored. This function will typically
3962/// be called in a loop that successively "unwraps" pointer and
3963/// pointer-to-member types to compare them at each level.
3964bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3965 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3966 *T2PtrType = T2->getAs<PointerType>();
3967 if (T1PtrType && T2PtrType) {
3968 T1 = T1PtrType->getPointeeType();
3969 T2 = T2PtrType->getPointeeType();
3970 return true;
3971 }
3972
3973 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3974 *T2MPType = T2->getAs<MemberPointerType>();
3975 if (T1MPType && T2MPType &&
3976 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3977 QualType(T2MPType->getClass(), 0))) {
3978 T1 = T1MPType->getPointeeType();
3979 T2 = T2MPType->getPointeeType();
3980 return true;
3981 }
3982
David Blaikiebbafb8a2012-03-11 07:00:24 +00003983 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003984 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3985 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3986 if (T1OPType && T2OPType) {
3987 T1 = T1OPType->getPointeeType();
3988 T2 = T2OPType->getPointeeType();
3989 return true;
3990 }
3991 }
3992
3993 // FIXME: Block pointers, too?
3994
3995 return false;
3996}
3997
Jay Foad39c79802011-01-12 09:06:06 +00003998DeclarationNameInfo
3999ASTContext::getNameForTemplate(TemplateName Name,
4000 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004001 switch (Name.getKind()) {
4002 case TemplateName::QualifiedTemplate:
4003 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004004 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004005 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4006 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004007
John McCalld9dfe3a2011-06-30 08:33:18 +00004008 case TemplateName::OverloadedTemplate: {
4009 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4010 // DNInfo work in progress: CHECKME: what about DNLoc?
4011 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4012 }
4013
4014 case TemplateName::DependentTemplate: {
4015 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004016 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004017 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004018 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4019 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004020 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004021 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4022 // DNInfo work in progress: FIXME: source locations?
4023 DeclarationNameLoc DNLoc;
4024 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4025 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4026 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004027 }
4028 }
4029
John McCalld9dfe3a2011-06-30 08:33:18 +00004030 case TemplateName::SubstTemplateTemplateParm: {
4031 SubstTemplateTemplateParmStorage *subst
4032 = Name.getAsSubstTemplateTemplateParm();
4033 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4034 NameLoc);
4035 }
4036
4037 case TemplateName::SubstTemplateTemplateParmPack: {
4038 SubstTemplateTemplateParmPackStorage *subst
4039 = Name.getAsSubstTemplateTemplateParmPack();
4040 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4041 NameLoc);
4042 }
4043 }
4044
4045 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004046}
4047
Jay Foad39c79802011-01-12 09:06:06 +00004048TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004049 switch (Name.getKind()) {
4050 case TemplateName::QualifiedTemplate:
4051 case TemplateName::Template: {
4052 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004053 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004054 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004055 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4056
4057 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004058 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004059 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004060
John McCalld9dfe3a2011-06-30 08:33:18 +00004061 case TemplateName::OverloadedTemplate:
4062 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004063
John McCalld9dfe3a2011-06-30 08:33:18 +00004064 case TemplateName::DependentTemplate: {
4065 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4066 assert(DTN && "Non-dependent template names must refer to template decls.");
4067 return DTN->CanonicalTemplateName;
4068 }
4069
4070 case TemplateName::SubstTemplateTemplateParm: {
4071 SubstTemplateTemplateParmStorage *subst
4072 = Name.getAsSubstTemplateTemplateParm();
4073 return getCanonicalTemplateName(subst->getReplacement());
4074 }
4075
4076 case TemplateName::SubstTemplateTemplateParmPack: {
4077 SubstTemplateTemplateParmPackStorage *subst
4078 = Name.getAsSubstTemplateTemplateParmPack();
4079 TemplateTemplateParmDecl *canonParameter
4080 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4081 TemplateArgument canonArgPack
4082 = getCanonicalTemplateArgument(subst->getArgumentPack());
4083 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4084 }
4085 }
4086
4087 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004088}
4089
Douglas Gregoradee3e32009-11-11 23:06:43 +00004090bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4091 X = getCanonicalTemplateName(X);
4092 Y = getCanonicalTemplateName(Y);
4093 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4094}
4095
Mike Stump11289f42009-09-09 15:08:12 +00004096TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004097ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004098 switch (Arg.getKind()) {
4099 case TemplateArgument::Null:
4100 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004101
Douglas Gregora8e02e72009-07-28 23:00:59 +00004102 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004103 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004104
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004105 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004106 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4107 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004108 }
Mike Stump11289f42009-09-09 15:08:12 +00004109
Eli Friedmanb826a002012-09-26 02:36:12 +00004110 case TemplateArgument::NullPtr:
4111 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4112 /*isNullPtr*/true);
4113
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004114 case TemplateArgument::Template:
4115 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004116
4117 case TemplateArgument::TemplateExpansion:
4118 return TemplateArgument(getCanonicalTemplateName(
4119 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004120 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004121
Douglas Gregora8e02e72009-07-28 23:00:59 +00004122 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004123 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004124
Douglas Gregora8e02e72009-07-28 23:00:59 +00004125 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004126 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004127
Douglas Gregora8e02e72009-07-28 23:00:59 +00004128 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004129 if (Arg.pack_size() == 0)
4130 return Arg;
4131
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004132 TemplateArgument *CanonArgs
4133 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004134 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004135 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004136 AEnd = Arg.pack_end();
4137 A != AEnd; (void)++A, ++Idx)
4138 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004139
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004140 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004141 }
4142 }
4143
4144 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004145 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004146}
4147
Douglas Gregor333489b2009-03-27 23:10:48 +00004148NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004149ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004150 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004151 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004152
4153 switch (NNS->getKind()) {
4154 case NestedNameSpecifier::Identifier:
4155 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004156 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004157 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4158 NNS->getAsIdentifier());
4159
4160 case NestedNameSpecifier::Namespace:
4161 // A namespace is canonical; build a nested-name-specifier with
4162 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004163 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004164 NNS->getAsNamespace()->getOriginalNamespace());
4165
4166 case NestedNameSpecifier::NamespaceAlias:
4167 // A namespace is canonical; build a nested-name-specifier with
4168 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004169 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004170 NNS->getAsNamespaceAlias()->getNamespace()
4171 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004172
4173 case NestedNameSpecifier::TypeSpec:
4174 case NestedNameSpecifier::TypeSpecWithTemplate: {
4175 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004176
4177 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4178 // break it apart into its prefix and identifier, then reconsititute those
4179 // as the canonical nested-name-specifier. This is required to canonicalize
4180 // a dependent nested-name-specifier involving typedefs of dependent-name
4181 // types, e.g.,
4182 // typedef typename T::type T1;
4183 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004184 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4185 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004186 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004187
Eli Friedman5358a0a2012-03-03 04:09:56 +00004188 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4189 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4190 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004191 return NestedNameSpecifier::Create(*this, nullptr, false,
4192 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004193 }
4194
4195 case NestedNameSpecifier::Global:
4196 // The global specifier is canonical and unique.
4197 return NNS;
4198 }
4199
David Blaikie8a40f702012-01-17 06:56:22 +00004200 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004201}
4202
Chris Lattner7adf0762008-08-04 07:31:14 +00004203
Jay Foad39c79802011-01-12 09:06:06 +00004204const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004205 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004206 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004207 // Handle the common positive case fast.
4208 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4209 return AT;
4210 }
Mike Stump11289f42009-09-09 15:08:12 +00004211
John McCall8ccfcb52009-09-24 19:53:00 +00004212 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004213 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004214 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004215
John McCall8ccfcb52009-09-24 19:53:00 +00004216 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004217 // implements C99 6.7.3p8: "If the specification of an array type includes
4218 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004219
Chris Lattner7adf0762008-08-04 07:31:14 +00004220 // If we get here, we either have type qualifiers on the type, or we have
4221 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004222 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004223
John McCall33ddac02011-01-19 10:06:00 +00004224 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004225 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004226
Chris Lattner7adf0762008-08-04 07:31:14 +00004227 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004228 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004229 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004230 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004231
Chris Lattner7adf0762008-08-04 07:31:14 +00004232 // Otherwise, we have an array and we have qualifiers on it. Push the
4233 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004234 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004235
Chris Lattner7adf0762008-08-04 07:31:14 +00004236 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4237 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4238 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004239 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004240 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4241 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4242 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004243 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004244
Mike Stump11289f42009-09-09 15:08:12 +00004245 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004246 = dyn_cast<DependentSizedArrayType>(ATy))
4247 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004248 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004249 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004250 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004251 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004252 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004253
Chris Lattner7adf0762008-08-04 07:31:14 +00004254 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004255 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004256 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004257 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004258 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004259 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004260}
4261
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004262QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004263 if (T->isArrayType() || T->isFunctionType())
4264 return getDecayedType(T);
4265 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004266}
4267
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004268QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004269 T = getVariableArrayDecayedType(T);
4270 T = getAdjustedParameterType(T);
4271 return T.getUnqualifiedType();
4272}
4273
Chris Lattnera21ad802008-04-02 05:18:44 +00004274/// getArrayDecayedType - Return the properly qualified result of decaying the
4275/// specified array type to a pointer. This operation is non-trivial when
4276/// handling typedefs etc. The canonical type of "T" must be an array type,
4277/// this returns a pointer to a properly qualified element of the array.
4278///
4279/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004280QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004281 // Get the element type with 'getAsArrayType' so that we don't lose any
4282 // typedefs in the element type of the array. This also handles propagation
4283 // of type qualifiers from the array type into the element type if present
4284 // (C99 6.7.3p8).
4285 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4286 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004287
Chris Lattner7adf0762008-08-04 07:31:14 +00004288 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004289
4290 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004291 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004292}
4293
John McCall33ddac02011-01-19 10:06:00 +00004294QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4295 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004296}
4297
John McCall33ddac02011-01-19 10:06:00 +00004298QualType ASTContext::getBaseElementType(QualType type) const {
4299 Qualifiers qs;
4300 while (true) {
4301 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004302 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004303 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004304
John McCall33ddac02011-01-19 10:06:00 +00004305 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004306 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004307 }
Mike Stump11289f42009-09-09 15:08:12 +00004308
John McCall33ddac02011-01-19 10:06:00 +00004309 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004310}
4311
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004312/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004313uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004314ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4315 uint64_t ElementCount = 1;
4316 do {
4317 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004318 CA = dyn_cast_or_null<ConstantArrayType>(
4319 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004320 } while (CA);
4321 return ElementCount;
4322}
4323
Steve Naroff0af91202007-04-27 21:51:21 +00004324/// getFloatingRank - Return a relative rank for floating point types.
4325/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004326static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004327 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004328 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004329
John McCall9dd450b2009-09-21 23:43:11 +00004330 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4331 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004332 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004333 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004334 case BuiltinType::Float: return FloatRank;
4335 case BuiltinType::Double: return DoubleRank;
4336 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004337 }
4338}
4339
Mike Stump11289f42009-09-09 15:08:12 +00004340/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4341/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004342/// 'typeDomain' is a real floating point or complex type.
4343/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004344QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4345 QualType Domain) const {
4346 FloatingRank EltRank = getFloatingRank(Size);
4347 if (Domain->isComplexType()) {
4348 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004349 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004350 case FloatRank: return FloatComplexTy;
4351 case DoubleRank: return DoubleComplexTy;
4352 case LongDoubleRank: return LongDoubleComplexTy;
4353 }
Steve Naroff0af91202007-04-27 21:51:21 +00004354 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004355
4356 assert(Domain->isRealFloatingType() && "Unknown domain!");
4357 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004358 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004359 case FloatRank: return FloatTy;
4360 case DoubleRank: return DoubleTy;
4361 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004362 }
David Blaikief47fa302012-01-17 02:30:50 +00004363 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004364}
4365
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004366/// getFloatingTypeOrder - Compare the rank of the two specified floating
4367/// point types, ignoring the domain of the type (i.e. 'double' ==
4368/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004369/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004370int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004371 FloatingRank LHSR = getFloatingRank(LHS);
4372 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004373
Chris Lattnerb90739d2008-04-06 23:38:49 +00004374 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004375 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004376 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004377 return 1;
4378 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004379}
4380
Chris Lattner76a00cf2008-04-06 22:59:24 +00004381/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4382/// routine will assert if passed a built-in type that isn't an integer or enum,
4383/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004384unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004385 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004386
Chris Lattner76a00cf2008-04-06 22:59:24 +00004387 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004388 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004389 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004390 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004391 case BuiltinType::Char_S:
4392 case BuiltinType::Char_U:
4393 case BuiltinType::SChar:
4394 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004395 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004396 case BuiltinType::Short:
4397 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004398 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004399 case BuiltinType::Int:
4400 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004401 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004402 case BuiltinType::Long:
4403 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004404 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004405 case BuiltinType::LongLong:
4406 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004407 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004408 case BuiltinType::Int128:
4409 case BuiltinType::UInt128:
4410 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004411 }
4412}
4413
Eli Friedman629ffb92009-08-20 04:21:42 +00004414/// \brief Whether this is a promotable bitfield reference according
4415/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4416///
4417/// \returns the type this bit-field will promote to, or NULL if no
4418/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004419QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004420 if (E->isTypeDependent() || E->isValueDependent())
4421 return QualType();
4422
John McCalld25db7e2013-05-06 21:39:12 +00004423 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004424 if (!Field)
4425 return QualType();
4426
4427 QualType FT = Field->getType();
4428
Richard Smithcaf33902011-10-10 18:28:20 +00004429 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004430 uint64_t IntSize = getTypeSize(IntTy);
4431 // GCC extension compatibility: if the bit-field size is less than or equal
4432 // to the size of int, it gets promoted no matter what its type is.
4433 // For instance, unsigned long bf : 4 gets promoted to signed int.
4434 if (BitWidth < IntSize)
4435 return IntTy;
4436
4437 if (BitWidth == IntSize)
4438 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4439
4440 // Types bigger than int are not subject to promotions, and therefore act
4441 // like the base type.
4442 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4443 // is ridiculous.
4444 return QualType();
4445}
4446
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004447/// getPromotedIntegerType - Returns the type that Promotable will
4448/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4449/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004450QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004451 assert(!Promotable.isNull());
4452 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004453 if (const EnumType *ET = Promotable->getAs<EnumType>())
4454 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004455
4456 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4457 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4458 // (3.9.1) can be converted to a prvalue of the first of the following
4459 // types that can represent all the values of its underlying type:
4460 // int, unsigned int, long int, unsigned long int, long long int, or
4461 // unsigned long long int [...]
4462 // FIXME: Is there some better way to compute this?
4463 if (BT->getKind() == BuiltinType::WChar_S ||
4464 BT->getKind() == BuiltinType::WChar_U ||
4465 BT->getKind() == BuiltinType::Char16 ||
4466 BT->getKind() == BuiltinType::Char32) {
4467 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4468 uint64_t FromSize = getTypeSize(BT);
4469 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4470 LongLongTy, UnsignedLongLongTy };
4471 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4472 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4473 if (FromSize < ToSize ||
4474 (FromSize == ToSize &&
4475 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4476 return PromoteTypes[Idx];
4477 }
4478 llvm_unreachable("char type should fit into long long");
4479 }
4480 }
4481
4482 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004483 if (Promotable->isSignedIntegerType())
4484 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004485 uint64_t PromotableSize = getIntWidth(Promotable);
4486 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004487 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4488 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4489}
4490
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004491/// \brief Recurses in pointer/array types until it finds an objc retainable
4492/// type and returns its ownership.
4493Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4494 while (!T.isNull()) {
4495 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4496 return T.getObjCLifetime();
4497 if (T->isArrayType())
4498 T = getBaseElementType(T);
4499 else if (const PointerType *PT = T->getAs<PointerType>())
4500 T = PT->getPointeeType();
4501 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004502 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004503 else
4504 break;
4505 }
4506
4507 return Qualifiers::OCL_None;
4508}
4509
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004510static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4511 // Incomplete enum types are not treated as integer types.
4512 // FIXME: In C++, enum types are never integer types.
4513 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4514 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004515 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004516}
4517
Mike Stump11289f42009-09-09 15:08:12 +00004518/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004519/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004520/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004521int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004522 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4523 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004524
4525 // Unwrap enums to their underlying type.
4526 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4527 LHSC = getIntegerTypeForEnum(ET);
4528 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4529 RHSC = getIntegerTypeForEnum(ET);
4530
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004531 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004532
Chris Lattner76a00cf2008-04-06 22:59:24 +00004533 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4534 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004535
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004536 unsigned LHSRank = getIntegerRank(LHSC);
4537 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004538
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004539 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4540 if (LHSRank == RHSRank) return 0;
4541 return LHSRank > RHSRank ? 1 : -1;
4542 }
Mike Stump11289f42009-09-09 15:08:12 +00004543
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004544 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4545 if (LHSUnsigned) {
4546 // If the unsigned [LHS] type is larger, return it.
4547 if (LHSRank >= RHSRank)
4548 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004549
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004550 // If the signed type can represent all values of the unsigned type, it
4551 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004552 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004553 return -1;
4554 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004555
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004556 // If the unsigned [RHS] type is larger, return it.
4557 if (RHSRank >= LHSRank)
4558 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004559
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004560 // If the signed type can represent all values of the unsigned type, it
4561 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004562 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004563 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004564}
Anders Carlsson98f07902007-08-17 05:31:46 +00004565
Mike Stump11289f42009-09-09 15:08:12 +00004566// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004567QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004568 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004569 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004570 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004571
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004572 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004573
Anders Carlsson98f07902007-08-17 05:31:46 +00004574 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004575 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004576 // int flags;
4577 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004578 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004579 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004580 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004581 FieldTypes[3] = LongTy;
4582
Anders Carlsson98f07902007-08-17 05:31:46 +00004583 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004584 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004585 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004586 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004587 SourceLocation(), nullptr,
4588 FieldTypes[i], /*TInfo=*/nullptr,
4589 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004590 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004591 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004592 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004593 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004594 }
4595
Douglas Gregord5058122010-02-11 01:19:42 +00004596 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004597 }
Mike Stump11289f42009-09-09 15:08:12 +00004598
Anders Carlsson98f07902007-08-17 05:31:46 +00004599 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004600}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004601
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004602QualType ASTContext::getObjCSuperType() const {
4603 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004604 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004605 TUDecl->addDecl(ObjCSuperTypeDecl);
4606 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4607 }
4608 return ObjCSuperType;
4609}
4610
Douglas Gregor512b0772009-04-23 22:29:11 +00004611void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004612 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004613 assert(Rec && "Invalid CFConstantStringType");
4614 CFConstantStringTypeDecl = Rec->getDecl();
4615}
4616
Jay Foad39c79802011-01-12 09:06:06 +00004617QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004618 if (BlockDescriptorType)
4619 return getTagDeclType(BlockDescriptorType);
4620
Alp Toker2dea15b2013-12-17 01:22:38 +00004621 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004622 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004623 RD = buildImplicitRecord("__block_descriptor");
4624 RD->startDefinition();
4625
Mike Stumpd0153282009-10-20 02:12:22 +00004626 QualType FieldTypes[] = {
4627 UnsignedLongTy,
4628 UnsignedLongTy,
4629 };
4630
Craig Topperd6d31ac2013-07-15 08:24:27 +00004631 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004632 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004633 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004634 };
4635
4636 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004637 FieldDecl *Field = FieldDecl::Create(
4638 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004639 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4640 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004641 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004642 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004643 }
4644
Alp Toker2dea15b2013-12-17 01:22:38 +00004645 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004646
Alp Toker2dea15b2013-12-17 01:22:38 +00004647 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004648
4649 return getTagDeclType(BlockDescriptorType);
4650}
4651
Jay Foad39c79802011-01-12 09:06:06 +00004652QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004653 if (BlockDescriptorExtendedType)
4654 return getTagDeclType(BlockDescriptorExtendedType);
4655
Alp Toker2dea15b2013-12-17 01:22:38 +00004656 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004657 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004658 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4659 RD->startDefinition();
4660
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004661 QualType FieldTypes[] = {
4662 UnsignedLongTy,
4663 UnsignedLongTy,
4664 getPointerType(VoidPtrTy),
4665 getPointerType(VoidPtrTy)
4666 };
4667
Craig Topperd6d31ac2013-07-15 08:24:27 +00004668 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004669 "reserved",
4670 "Size",
4671 "CopyFuncPtr",
4672 "DestroyFuncPtr"
4673 };
4674
4675 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004676 FieldDecl *Field = FieldDecl::Create(
4677 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004678 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4679 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004680 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004681 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004682 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004683 }
4684
Alp Toker2dea15b2013-12-17 01:22:38 +00004685 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004686
Alp Toker2dea15b2013-12-17 01:22:38 +00004687 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004688 return getTagDeclType(BlockDescriptorExtendedType);
4689}
4690
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004691/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4692/// requires copy/dispose. Note that this must match the logic
4693/// in buildByrefHelpers.
4694bool ASTContext::BlockRequiresCopying(QualType Ty,
4695 const VarDecl *D) {
4696 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4697 const Expr *copyExpr = getBlockVarCopyInits(D);
4698 if (!copyExpr && record->hasTrivialDestructor()) return false;
4699
Mike Stump94967902009-10-21 18:16:27 +00004700 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004701 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004702
4703 if (!Ty->isObjCRetainableType()) return false;
4704
4705 Qualifiers qs = Ty.getQualifiers();
4706
4707 // If we have lifetime, that dominates.
4708 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4709 assert(getLangOpts().ObjCAutoRefCount);
4710
4711 switch (lifetime) {
4712 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4713
4714 // These are just bits as far as the runtime is concerned.
4715 case Qualifiers::OCL_ExplicitNone:
4716 case Qualifiers::OCL_Autoreleasing:
4717 return false;
4718
4719 // Tell the runtime that this is ARC __weak, called by the
4720 // byref routines.
4721 case Qualifiers::OCL_Weak:
4722 // ARC __strong __block variables need to be retained.
4723 case Qualifiers::OCL_Strong:
4724 return true;
4725 }
4726 llvm_unreachable("fell out of lifetime switch!");
4727 }
4728 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4729 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004730}
4731
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004732bool ASTContext::getByrefLifetime(QualType Ty,
4733 Qualifiers::ObjCLifetime &LifeTime,
4734 bool &HasByrefExtendedLayout) const {
4735
4736 if (!getLangOpts().ObjC1 ||
4737 getLangOpts().getGC() != LangOptions::NonGC)
4738 return false;
4739
4740 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004741 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004742 HasByrefExtendedLayout = true;
4743 LifeTime = Qualifiers::OCL_None;
4744 }
4745 else if (getLangOpts().ObjCAutoRefCount)
4746 LifeTime = Ty.getObjCLifetime();
4747 // MRR.
4748 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4749 LifeTime = Qualifiers::OCL_ExplicitNone;
4750 else
4751 LifeTime = Qualifiers::OCL_None;
4752 return true;
4753}
4754
Douglas Gregorbab8a962011-09-08 01:46:34 +00004755TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4756 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004757 ObjCInstanceTypeDecl =
4758 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004759 return ObjCInstanceTypeDecl;
4760}
4761
Anders Carlsson18acd442007-10-29 06:33:42 +00004762// This returns true if a type has been typedefed to BOOL:
4763// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004764static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004765 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004766 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4767 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004768
Anders Carlssond8499822007-10-29 05:01:08 +00004769 return false;
4770}
4771
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004772/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004773/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004774CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004775 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4776 return CharUnits::Zero();
4777
Ken Dyck40775002010-01-11 17:06:35 +00004778 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004779
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004780 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004781 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004782 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004783 // Treat arrays as pointers, since that's how they're passed in.
4784 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004785 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004786 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004787}
4788
Hans Wennborg56fc62b2014-07-17 20:25:23 +00004789bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4790 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4791 VD->getType()->isIntegralOrEnumerationType() &&
4792 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
4793}
4794
Ken Dyck40775002010-01-11 17:06:35 +00004795static inline
4796std::string charUnitsToString(const CharUnits &CU) {
4797 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004798}
4799
John McCall351762c2011-02-07 10:33:21 +00004800/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004801/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004802std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4803 std::string S;
4804
David Chisnall950a9512009-11-17 19:33:30 +00004805 const BlockDecl *Decl = Expr->getBlockDecl();
4806 QualType BlockTy =
4807 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4808 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004809 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004810 getObjCEncodingForMethodParameter(
4811 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4812 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004813 else
Alp Toker314cc812014-01-25 16:55:45 +00004814 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004815 // Compute size of all parameters.
4816 // Start with computing size of a pointer in number of bytes.
4817 // FIXME: There might(should) be a better way of doing this computation!
4818 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004819 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4820 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004821 for (auto PI : Decl->params()) {
4822 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004823 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004824 if (sz.isZero())
4825 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004826 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004827 ParmOffset += sz;
4828 }
4829 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004830 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004831 // Block pointer and offset.
4832 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004833
4834 // Argument types.
4835 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004836 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004837 QualType PType = PVDecl->getOriginalType();
4838 if (const ArrayType *AT =
4839 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4840 // Use array's original type only if it has known number of
4841 // elements.
4842 if (!isa<ConstantArrayType>(AT))
4843 PType = PVDecl->getType();
4844 } else if (PType->isFunctionType())
4845 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004846 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004847 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4848 S, true /*Extended*/);
4849 else
4850 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004851 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004852 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004853 }
John McCall351762c2011-02-07 10:33:21 +00004854
4855 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004856}
4857
Douglas Gregora9d84932011-05-27 01:19:52 +00004858bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004859 std::string& S) {
4860 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004861 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004862 CharUnits ParmOffset;
4863 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004864 for (auto PI : Decl->params()) {
4865 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004866 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004867 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004868 continue;
4869
David Chisnall50e4eba2010-12-30 14:05:53 +00004870 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004871 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004872 ParmOffset += sz;
4873 }
4874 S += charUnitsToString(ParmOffset);
4875 ParmOffset = CharUnits::Zero();
4876
4877 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004878 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004879 QualType PType = PVDecl->getOriginalType();
4880 if (const ArrayType *AT =
4881 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4882 // Use array's original type only if it has known number of
4883 // elements.
4884 if (!isa<ConstantArrayType>(AT))
4885 PType = PVDecl->getType();
4886 } else if (PType->isFunctionType())
4887 PType = PVDecl->getType();
4888 getObjCEncodingForType(PType, S);
4889 S += charUnitsToString(ParmOffset);
4890 ParmOffset += getObjCEncodingTypeSize(PType);
4891 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004892
4893 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004894}
4895
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004896/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4897/// method parameter or return type. If Extended, include class names and
4898/// block object types.
4899void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4900 QualType T, std::string& S,
4901 bool Extended) const {
4902 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4903 getObjCEncodingForTypeQualifier(QT, S);
4904 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00004905 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004906 true /*OutermostType*/,
4907 false /*EncodingProperty*/,
4908 false /*StructField*/,
4909 Extended /*EncodeBlockParameters*/,
4910 Extended /*EncodeClassNames*/);
4911}
4912
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004913/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004914/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004915bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004916 std::string& S,
4917 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004918 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004919 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004920 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4921 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004922 // Compute size of all parameters.
4923 // Start with computing size of a pointer in number of bytes.
4924 // FIXME: There might(should) be a better way of doing this computation!
4925 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004926 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004927 // The first two arguments (self and _cmd) are pointers; account for
4928 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004929 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004930 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004931 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004932 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004933 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004934 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004935 continue;
4936
Ken Dyck40775002010-01-11 17:06:35 +00004937 assert (sz.isPositive() &&
4938 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004939 ParmOffset += sz;
4940 }
Ken Dyck40775002010-01-11 17:06:35 +00004941 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004942 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004943 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004944
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004945 // Argument types.
4946 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004947 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004948 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004949 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004950 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004951 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004952 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4953 // Use array's original type only if it has known number of
4954 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004955 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004956 PType = PVDecl->getType();
4957 } else if (PType->isFunctionType())
4958 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004959 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4960 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004961 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004962 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004963 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004964
4965 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004966}
4967
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004968ObjCPropertyImplDecl *
4969ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4970 const ObjCPropertyDecl *PD,
4971 const Decl *Container) const {
4972 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00004973 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004974 if (const ObjCCategoryImplDecl *CID =
4975 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00004976 for (auto *PID : CID->property_impls())
4977 if (PID->getPropertyDecl() == PD)
4978 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00004979 } else {
4980 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4981 for (auto *PID : OID->property_impls())
4982 if (PID->getPropertyDecl() == PD)
4983 return PID;
4984 }
4985 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004986}
4987
Daniel Dunbar4932b362008-08-28 04:38:10 +00004988/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004989/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004990/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4991/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004992/// Property attributes are stored as a comma-delimited C string. The simple
4993/// attributes readonly and bycopy are encoded as single characters. The
4994/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4995/// encoded as single characters, followed by an identifier. Property types
4996/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004997/// these attributes are defined by the following enumeration:
4998/// @code
4999/// enum PropertyAttributes {
5000/// kPropertyReadOnly = 'R', // property is read-only.
5001/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5002/// kPropertyByref = '&', // property is a reference to the value last assigned
5003/// kPropertyDynamic = 'D', // property is dynamic
5004/// kPropertyGetter = 'G', // followed by getter selector name
5005/// kPropertySetter = 'S', // followed by setter selector name
5006/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005007/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005008/// kPropertyWeak = 'W' // 'weak' property
5009/// kPropertyStrong = 'P' // property GC'able
5010/// kPropertyNonAtomic = 'N' // property non-atomic
5011/// };
5012/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005013void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005014 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005015 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005016 // Collect information from the property implementation decl(s).
5017 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005018 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005019
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005020 if (ObjCPropertyImplDecl *PropertyImpDecl =
5021 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5022 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5023 Dynamic = true;
5024 else
5025 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005026 }
5027
5028 // FIXME: This is not very efficient.
5029 S = "T";
5030
5031 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005032 // GCC has some special rules regarding encoding of properties which
5033 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005034 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005035
5036 if (PD->isReadOnly()) {
5037 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005038 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5039 S += ",C";
5040 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5041 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005042 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5043 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005044 } else {
5045 switch (PD->getSetterKind()) {
5046 case ObjCPropertyDecl::Assign: break;
5047 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005048 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005049 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005050 }
5051 }
5052
5053 // It really isn't clear at all what this means, since properties
5054 // are "dynamic by default".
5055 if (Dynamic)
5056 S += ",D";
5057
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005058 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5059 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005060
Daniel Dunbar4932b362008-08-28 04:38:10 +00005061 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5062 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005063 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005064 }
5065
5066 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5067 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005068 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005069 }
5070
5071 if (SynthesizePID) {
5072 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5073 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005074 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005075 }
5076
5077 // FIXME: OBJCGC: weak & strong
5078}
5079
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005080/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005081/// Another legacy compatibility encoding: 32-bit longs are encoded as
5082/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005083/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5084///
5085void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005086 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005087 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005088 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005089 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005090 else
Jay Foad39c79802011-01-12 09:06:06 +00005091 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005092 PointeeTy = IntTy;
5093 }
5094 }
5095}
5096
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005097void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005098 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005099 // We follow the behavior of gcc, expanding structures which are
5100 // directly pointed to, and expanding embedded structures. Note that
5101 // these rules are sufficient to prevent recursive encoding of the
5102 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005103 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005104 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005105}
5106
Joe Groff98ac7d22014-07-07 22:25:15 +00005107void ASTContext::getObjCEncodingForPropertyType(QualType T,
5108 std::string& S) const {
5109 // Encode result type.
5110 // GCC has some special rules regarding encoding of properties which
5111 // closely resembles encoding of ivars.
5112 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5113 true /* outermost type */,
5114 true /* encoding property */);
5115}
5116
John McCall393a78d2012-12-20 02:45:14 +00005117static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5118 BuiltinType::Kind kind) {
5119 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005120 case BuiltinType::Void: return 'v';
5121 case BuiltinType::Bool: return 'B';
5122 case BuiltinType::Char_U:
5123 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005124 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005125 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005126 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005127 case BuiltinType::UInt: return 'I';
5128 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005129 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005130 case BuiltinType::UInt128: return 'T';
5131 case BuiltinType::ULongLong: return 'Q';
5132 case BuiltinType::Char_S:
5133 case BuiltinType::SChar: return 'c';
5134 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005135 case BuiltinType::WChar_S:
5136 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005137 case BuiltinType::Int: return 'i';
5138 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005139 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005140 case BuiltinType::LongLong: return 'q';
5141 case BuiltinType::Int128: return 't';
5142 case BuiltinType::Float: return 'f';
5143 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005144 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005145 case BuiltinType::NullPtr: return '*'; // like char*
5146
5147 case BuiltinType::Half:
5148 // FIXME: potentially need @encodes for these!
5149 return ' ';
5150
5151 case BuiltinType::ObjCId:
5152 case BuiltinType::ObjCClass:
5153 case BuiltinType::ObjCSel:
5154 llvm_unreachable("@encoding ObjC primitive type");
5155
5156 // OpenCL and placeholder types don't need @encodings.
5157 case BuiltinType::OCLImage1d:
5158 case BuiltinType::OCLImage1dArray:
5159 case BuiltinType::OCLImage1dBuffer:
5160 case BuiltinType::OCLImage2d:
5161 case BuiltinType::OCLImage2dArray:
5162 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005163 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005164 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005165 case BuiltinType::Dependent:
5166#define BUILTIN_TYPE(KIND, ID)
5167#define PLACEHOLDER_TYPE(KIND, ID) \
5168 case BuiltinType::KIND:
5169#include "clang/AST/BuiltinTypes.def"
5170 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005171 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005172 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005173}
5174
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005175static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5176 EnumDecl *Enum = ET->getDecl();
5177
5178 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5179 if (!Enum->isFixed())
5180 return 'i';
5181
5182 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005183 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5184 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005185}
5186
Jay Foad39c79802011-01-12 09:06:06 +00005187static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005188 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005189 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005190 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005191 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5192 // The GNU runtime requires more information; bitfields are encoded as b,
5193 // then the offset (in bits) of the first element, then the type of the
5194 // bitfield, then the size in bits. For example, in this structure:
5195 //
5196 // struct
5197 // {
5198 // int integer;
5199 // int flags:2;
5200 // };
5201 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5202 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5203 // information is not especially sensible, but we're stuck with it for
5204 // compatibility with GCC, although providing it breaks anything that
5205 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005206 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005207 const RecordDecl *RD = FD->getParent();
5208 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005209 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005210 if (const EnumType *ET = T->getAs<EnumType>())
5211 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005212 else {
5213 const BuiltinType *BT = T->castAs<BuiltinType>();
5214 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5215 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005216 }
Richard Smithcaf33902011-10-10 18:28:20 +00005217 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005218}
5219
Daniel Dunbar07d07852009-10-18 21:17:35 +00005220// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005221void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5222 bool ExpandPointedToStructures,
5223 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005224 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005225 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005226 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005227 bool StructField,
5228 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005229 bool EncodeClassNames,
5230 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005231 CanQualType CT = getCanonicalType(T);
5232 switch (CT->getTypeClass()) {
5233 case Type::Builtin:
5234 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005235 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005236 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005237 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5238 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5239 else
5240 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005241 return;
Mike Stump11289f42009-09-09 15:08:12 +00005242
John McCall393a78d2012-12-20 02:45:14 +00005243 case Type::Complex: {
5244 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005245 S += 'j';
Craig Topper36250ad2014-05-12 05:36:57 +00005246 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr,
5247 false, false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005248 return;
5249 }
John McCall393a78d2012-12-20 02:45:14 +00005250
5251 case Type::Atomic: {
5252 const AtomicType *AT = T->castAs<AtomicType>();
5253 S += 'A';
Craig Topper36250ad2014-05-12 05:36:57 +00005254 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr,
John McCall393a78d2012-12-20 02:45:14 +00005255 false, false);
5256 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005257 }
John McCall393a78d2012-12-20 02:45:14 +00005258
5259 // encoding for pointer or reference types.
5260 case Type::Pointer:
5261 case Type::LValueReference:
5262 case Type::RValueReference: {
5263 QualType PointeeTy;
5264 if (isa<PointerType>(CT)) {
5265 const PointerType *PT = T->castAs<PointerType>();
5266 if (PT->isObjCSelType()) {
5267 S += ':';
5268 return;
5269 }
5270 PointeeTy = PT->getPointeeType();
5271 } else {
5272 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5273 }
5274
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005275 bool isReadOnly = false;
5276 // For historical/compatibility reasons, the read-only qualifier of the
5277 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5278 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005279 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005280 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005281 if (OutermostType && T.isConstQualified()) {
5282 isReadOnly = true;
5283 S += 'r';
5284 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005285 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005286 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005287 while (P->getAs<PointerType>())
5288 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005289 if (P.isConstQualified()) {
5290 isReadOnly = true;
5291 S += 'r';
5292 }
5293 }
5294 if (isReadOnly) {
5295 // Another legacy compatibility encoding. Some ObjC qualifier and type
5296 // combinations need to be rearranged.
5297 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005298 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005299 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005300 }
Mike Stump11289f42009-09-09 15:08:12 +00005301
Anders Carlssond8499822007-10-29 05:01:08 +00005302 if (PointeeTy->isCharType()) {
5303 // char pointer types should be encoded as '*' unless it is a
5304 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005305 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005306 S += '*';
5307 return;
5308 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005309 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005310 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5311 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5312 S += '#';
5313 return;
5314 }
5315 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5316 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5317 S += '@';
5318 return;
5319 }
5320 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005321 }
Anders Carlssond8499822007-10-29 05:01:08 +00005322 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005323 getLegacyIntegralTypeEncoding(PointeeTy);
5324
Mike Stump11289f42009-09-09 15:08:12 +00005325 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005326 nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005327 return;
5328 }
John McCall393a78d2012-12-20 02:45:14 +00005329
5330 case Type::ConstantArray:
5331 case Type::IncompleteArray:
5332 case Type::VariableArray: {
5333 const ArrayType *AT = cast<ArrayType>(CT);
5334
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005335 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005336 // Incomplete arrays are encoded as a pointer to the array element.
5337 S += '^';
5338
Mike Stump11289f42009-09-09 15:08:12 +00005339 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005340 false, ExpandStructures, FD);
5341 } else {
5342 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005343
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005344 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5345 S += llvm::utostr(CAT->getSize().getZExtValue());
5346 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005347 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005348 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5349 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005350 S += '0';
5351 }
Mike Stump11289f42009-09-09 15:08:12 +00005352
5353 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005354 false, ExpandStructures, FD);
5355 S += ']';
5356 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005357 return;
5358 }
Mike Stump11289f42009-09-09 15:08:12 +00005359
John McCall393a78d2012-12-20 02:45:14 +00005360 case Type::FunctionNoProto:
5361 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005362 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005363 return;
Mike Stump11289f42009-09-09 15:08:12 +00005364
John McCall393a78d2012-12-20 02:45:14 +00005365 case Type::Record: {
5366 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005367 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005368 // Anonymous structures print as '?'
5369 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5370 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005371 if (ClassTemplateSpecializationDecl *Spec
5372 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5373 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005374 llvm::raw_string_ostream OS(S);
5375 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005376 TemplateArgs.data(),
5377 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005378 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005379 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005380 } else {
5381 S += '?';
5382 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005383 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005384 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005385 if (!RDecl->isUnion()) {
5386 getObjCEncodingForStructureImpl(RDecl, S, FD);
5387 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005388 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005389 if (FD) {
5390 S += '"';
5391 S += Field->getNameAsString();
5392 S += '"';
5393 }
Mike Stump11289f42009-09-09 15:08:12 +00005394
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005395 // Special case bit-fields.
5396 if (Field->isBitField()) {
5397 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005398 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005399 } else {
5400 QualType qt = Field->getType();
5401 getLegacyIntegralTypeEncoding(qt);
5402 getObjCEncodingForTypeImpl(qt, S, false, true,
5403 FD, /*OutermostType*/false,
5404 /*EncodingProperty*/false,
5405 /*StructField*/true);
5406 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005407 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005408 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005409 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005410 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005411 return;
5412 }
Mike Stump11289f42009-09-09 15:08:12 +00005413
John McCall393a78d2012-12-20 02:45:14 +00005414 case Type::BlockPointer: {
5415 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005416 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005417 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005418 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005419
5420 S += '<';
5421 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005422 getObjCEncodingForTypeImpl(
5423 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5424 FD, false /* OutermostType */, EncodingProperty,
5425 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005426 // Block self
5427 S += "@?";
5428 // Block parameters
5429 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005430 for (const auto &I : FPT->param_types())
5431 getObjCEncodingForTypeImpl(
5432 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5433 false /* OutermostType */, EncodingProperty,
5434 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005435 }
5436 S += '>';
5437 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005438 return;
5439 }
Mike Stump11289f42009-09-09 15:08:12 +00005440
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005441 case Type::ObjCObject: {
5442 // hack to match legacy encoding of *id and *Class
5443 QualType Ty = getObjCObjectPointerType(CT);
5444 if (Ty->isObjCIdType()) {
5445 S += "{objc_object=}";
5446 return;
5447 }
5448 else if (Ty->isObjCClassType()) {
5449 S += "{objc_class=}";
5450 return;
5451 }
5452 }
5453
John McCall393a78d2012-12-20 02:45:14 +00005454 case Type::ObjCInterface: {
5455 // Ignore protocol qualifiers when mangling at this level.
5456 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005457
John McCall393a78d2012-12-20 02:45:14 +00005458 // The assumption seems to be that this assert will succeed
5459 // because nested levels will have filtered out 'id' and 'Class'.
5460 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005461 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005462 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005463 S += '{';
5464 const IdentifierInfo *II = OI->getIdentifier();
5465 S += II->getName();
5466 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005467 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005468 DeepCollectObjCIvars(OI, true, Ivars);
5469 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005470 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005471 if (Field->isBitField())
5472 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005473 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005474 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5475 false, false, false, false, false,
5476 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005477 }
5478 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005479 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005480 }
Mike Stump11289f42009-09-09 15:08:12 +00005481
John McCall393a78d2012-12-20 02:45:14 +00005482 case Type::ObjCObjectPointer: {
5483 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005484 if (OPT->isObjCIdType()) {
5485 S += '@';
5486 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005487 }
Mike Stump11289f42009-09-09 15:08:12 +00005488
Steve Narofff0c86112009-10-28 22:03:49 +00005489 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5490 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5491 // Since this is a binary compatibility issue, need to consult with runtime
5492 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005493 S += '#';
5494 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005495 }
Mike Stump11289f42009-09-09 15:08:12 +00005496
Chris Lattnere7cabb92009-07-13 00:10:46 +00005497 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005498 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005499 ExpandPointedToStructures,
5500 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005501 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005502 // Note that we do extended encoding of protocol qualifer list
5503 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005504 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005505 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005506 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005507 S += I->getNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005508 S += '>';
5509 }
5510 S += '"';
5511 }
5512 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005513 }
Mike Stump11289f42009-09-09 15:08:12 +00005514
Chris Lattnere7cabb92009-07-13 00:10:46 +00005515 QualType PointeeTy = OPT->getPointeeType();
5516 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005517 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5518 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005519 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005520 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005521 // {...};
5522 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005523 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005524 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005525 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5526 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5527 DeepCollectObjCIvars(OI, true, Ivars);
5528 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5529 if (cast<FieldDecl>(Ivars[i]) == FD) {
5530 S += '{';
5531 S += OI->getIdentifier()->getName();
5532 S += '}';
5533 return;
5534 }
5535 }
5536 }
Mike Stump11289f42009-09-09 15:08:12 +00005537 getObjCEncodingForTypeImpl(PointeeTy, S,
5538 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005539 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005540 false, false, false, false, false,
5541 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005542 return;
5543 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005544
5545 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005546 if (OPT->getInterfaceDecl() &&
5547 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005548 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005549 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Aaron Ballman83731462014-03-17 16:14:00 +00005550 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005551 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005552 S += I->getNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005553 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005554 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005555 S += '"';
5556 }
5557 return;
5558 }
Mike Stump11289f42009-09-09 15:08:12 +00005559
John McCalla9e6e8d2010-05-17 23:56:34 +00005560 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005561 // FIXME: we shoul do better than that. 'M' is available.
5562 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005563 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005564
John McCall393a78d2012-12-20 02:45:14 +00005565 case Type::Vector:
5566 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005567 // This matches gcc's encoding, even though technically it is
5568 // insufficient.
5569 // FIXME. We should do a better job than gcc.
5570 return;
John McCall393a78d2012-12-20 02:45:14 +00005571
Richard Smith27d807c2013-04-30 13:56:41 +00005572 case Type::Auto:
5573 // We could see an undeduced auto type here during error recovery.
5574 // Just ignore it.
5575 return;
5576
John McCall393a78d2012-12-20 02:45:14 +00005577#define ABSTRACT_TYPE(KIND, BASE)
5578#define TYPE(KIND, BASE)
5579#define DEPENDENT_TYPE(KIND, BASE) \
5580 case Type::KIND:
5581#define NON_CANONICAL_TYPE(KIND, BASE) \
5582 case Type::KIND:
5583#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5584 case Type::KIND:
5585#include "clang/AST/TypeNodes.def"
5586 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005587 }
John McCall393a78d2012-12-20 02:45:14 +00005588 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005589}
5590
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005591void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5592 std::string &S,
5593 const FieldDecl *FD,
5594 bool includeVBases) const {
5595 assert(RDecl && "Expected non-null RecordDecl");
5596 assert(!RDecl->isUnion() && "Should not be called for unions");
5597 if (!RDecl->getDefinition())
5598 return;
5599
5600 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5601 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5602 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5603
5604 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005605 for (const auto &BI : CXXRec->bases()) {
5606 if (!BI.isVirtual()) {
5607 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005608 if (base->isEmpty())
5609 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005610 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005611 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5612 std::make_pair(offs, base));
5613 }
5614 }
5615 }
5616
5617 unsigned i = 0;
5618 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5619 FieldEnd = RDecl->field_end();
5620 Field != FieldEnd; ++Field, ++i) {
5621 uint64_t offs = layout.getFieldOffset(i);
5622 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005623 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005624 }
5625
5626 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005627 for (const auto &BI : CXXRec->vbases()) {
5628 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005629 if (base->isEmpty())
5630 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005631 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005632 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5633 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005634 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5635 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005636 }
5637 }
5638
5639 CharUnits size;
5640 if (CXXRec) {
5641 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5642 } else {
5643 size = layout.getSize();
5644 }
5645
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005646#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005647 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005648#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005649 std::multimap<uint64_t, NamedDecl *>::iterator
5650 CurLayObj = FieldOrBaseOffsets.begin();
5651
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005652 if (CXXRec && CXXRec->isDynamicClass() &&
5653 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005654 if (FD) {
5655 S += "\"_vptr$";
5656 std::string recname = CXXRec->getNameAsString();
5657 if (recname.empty()) recname = "?";
5658 S += recname;
5659 S += '"';
5660 }
5661 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005662#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005663 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005664#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005665 }
5666
5667 if (!RDecl->hasFlexibleArrayMember()) {
5668 // Mark the end of the structure.
5669 uint64_t offs = toBits(size);
5670 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005671 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005672 }
5673
5674 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005675#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005676 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005677 if (CurOffs < CurLayObj->first) {
5678 uint64_t padding = CurLayObj->first - CurOffs;
5679 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5680 // packing/alignment of members is different that normal, in which case
5681 // the encoding will be out-of-sync with the real layout.
5682 // If the runtime switches to just consider the size of types without
5683 // taking into account alignment, we could make padding explicit in the
5684 // encoding (e.g. using arrays of chars). The encoding strings would be
5685 // longer then though.
5686 CurOffs += padding;
5687 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005688#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005689
5690 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005691 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005692 break; // reached end of structure.
5693
5694 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5695 // We expand the bases without their virtual bases since those are going
5696 // in the initial structure. Note that this differs from gcc which
5697 // expands virtual bases each time one is encountered in the hierarchy,
5698 // making the encoding type bigger than it really is.
5699 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005700 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005701#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005702 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005703#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005704 } else {
5705 FieldDecl *field = cast<FieldDecl>(dcl);
5706 if (FD) {
5707 S += '"';
5708 S += field->getNameAsString();
5709 S += '"';
5710 }
5711
5712 if (field->isBitField()) {
5713 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005714#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005715 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005716#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005717 } else {
5718 QualType qt = field->getType();
5719 getLegacyIntegralTypeEncoding(qt);
5720 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5721 /*OutermostType*/false,
5722 /*EncodingProperty*/false,
5723 /*StructField*/true);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005724#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005725 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005726#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005727 }
5728 }
5729 }
5730}
5731
Mike Stump11289f42009-09-09 15:08:12 +00005732void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005733 std::string& S) const {
5734 if (QT & Decl::OBJC_TQ_In)
5735 S += 'n';
5736 if (QT & Decl::OBJC_TQ_Inout)
5737 S += 'N';
5738 if (QT & Decl::OBJC_TQ_Out)
5739 S += 'o';
5740 if (QT & Decl::OBJC_TQ_Bycopy)
5741 S += 'O';
5742 if (QT & Decl::OBJC_TQ_Byref)
5743 S += 'R';
5744 if (QT & Decl::OBJC_TQ_Oneway)
5745 S += 'V';
5746}
5747
Douglas Gregor3ea72692011-08-12 05:46:01 +00005748TypedefDecl *ASTContext::getObjCIdDecl() const {
5749 if (!ObjCIdDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005750 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0);
Douglas Gregor3ea72692011-08-12 05:46:01 +00005751 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005752 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005753 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005754 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005755}
5756
Douglas Gregor52e02802011-08-12 06:17:30 +00005757TypedefDecl *ASTContext::getObjCSelDecl() const {
5758 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005759 QualType T = getPointerType(ObjCBuiltinSelTy);
5760 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005761 }
5762 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005763}
5764
Douglas Gregor0a586182011-08-12 05:59:41 +00005765TypedefDecl *ASTContext::getObjCClassDecl() const {
5766 if (!ObjCClassDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005767 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0);
Douglas Gregor0a586182011-08-12 05:59:41 +00005768 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005769 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005770 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005771 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005772}
5773
Douglas Gregord53ae832012-01-17 18:09:05 +00005774ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5775 if (!ObjCProtocolClassDecl) {
5776 ObjCProtocolClassDecl
5777 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5778 SourceLocation(),
5779 &Idents.get("Protocol"),
Craig Topper36250ad2014-05-12 05:36:57 +00005780 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00005781 SourceLocation(), true);
5782 }
5783
5784 return ObjCProtocolClassDecl;
5785}
5786
Meador Inge5d3fb222012-06-16 03:34:49 +00005787//===----------------------------------------------------------------------===//
5788// __builtin_va_list Construction Functions
5789//===----------------------------------------------------------------------===//
5790
5791static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5792 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005793 QualType T = Context->getPointerType(Context->CharTy);
5794 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005795}
5796
5797static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5798 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005799 QualType T = Context->getPointerType(Context->VoidTy);
5800 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005801}
5802
Tim Northover9bb857a2013-01-31 12:13:10 +00005803static TypedefDecl *
5804CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005805 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005806 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005807 if (Context->getLangOpts().CPlusPlus) {
5808 // namespace std { struct __va_list {
5809 NamespaceDecl *NS;
5810 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5811 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00005812 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00005813 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00005814 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00005815 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005816 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005817 }
5818
5819 VaListTagDecl->startDefinition();
5820
5821 const size_t NumFields = 5;
5822 QualType FieldTypes[NumFields];
5823 const char *FieldNames[NumFields];
5824
5825 // void *__stack;
5826 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5827 FieldNames[0] = "__stack";
5828
5829 // void *__gr_top;
5830 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5831 FieldNames[1] = "__gr_top";
5832
5833 // void *__vr_top;
5834 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5835 FieldNames[2] = "__vr_top";
5836
5837 // int __gr_offs;
5838 FieldTypes[3] = Context->IntTy;
5839 FieldNames[3] = "__gr_offs";
5840
5841 // int __vr_offs;
5842 FieldTypes[4] = Context->IntTy;
5843 FieldNames[4] = "__vr_offs";
5844
5845 // Create fields
5846 for (unsigned i = 0; i < NumFields; ++i) {
5847 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5848 VaListTagDecl,
5849 SourceLocation(),
5850 SourceLocation(),
5851 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005852 FieldTypes[i], /*TInfo=*/nullptr,
5853 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00005854 /*Mutable=*/false,
5855 ICIS_NoInit);
5856 Field->setAccess(AS_public);
5857 VaListTagDecl->addDecl(Field);
5858 }
5859 VaListTagDecl->completeDefinition();
5860 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5861 Context->VaListTagTy = VaListTagType;
5862
5863 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005864 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005865}
5866
Meador Inge5d3fb222012-06-16 03:34:49 +00005867static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5868 // typedef struct __va_list_tag {
5869 RecordDecl *VaListTagDecl;
5870
Alp Toker2dea15b2013-12-17 01:22:38 +00005871 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005872 VaListTagDecl->startDefinition();
5873
5874 const size_t NumFields = 5;
5875 QualType FieldTypes[NumFields];
5876 const char *FieldNames[NumFields];
5877
5878 // unsigned char gpr;
5879 FieldTypes[0] = Context->UnsignedCharTy;
5880 FieldNames[0] = "gpr";
5881
5882 // unsigned char fpr;
5883 FieldTypes[1] = Context->UnsignedCharTy;
5884 FieldNames[1] = "fpr";
5885
5886 // unsigned short reserved;
5887 FieldTypes[2] = Context->UnsignedShortTy;
5888 FieldNames[2] = "reserved";
5889
5890 // void* overflow_arg_area;
5891 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5892 FieldNames[3] = "overflow_arg_area";
5893
5894 // void* reg_save_area;
5895 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5896 FieldNames[4] = "reg_save_area";
5897
5898 // Create fields
5899 for (unsigned i = 0; i < NumFields; ++i) {
5900 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5901 SourceLocation(),
5902 SourceLocation(),
5903 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005904 FieldTypes[i], /*TInfo=*/nullptr,
5905 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00005906 /*Mutable=*/false,
5907 ICIS_NoInit);
5908 Field->setAccess(AS_public);
5909 VaListTagDecl->addDecl(Field);
5910 }
5911 VaListTagDecl->completeDefinition();
5912 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005913 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005914
5915 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005916 TypedefDecl *VaListTagTypedefDecl =
5917 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5918
Meador Inge5d3fb222012-06-16 03:34:49 +00005919 QualType VaListTagTypedefType =
5920 Context->getTypedefType(VaListTagTypedefDecl);
5921
5922 // typedef __va_list_tag __builtin_va_list[1];
5923 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5924 QualType VaListTagArrayType
5925 = Context->getConstantArrayType(VaListTagTypedefType,
5926 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005927 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005928}
5929
5930static TypedefDecl *
5931CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5932 // typedef struct __va_list_tag {
5933 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005934 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005935 VaListTagDecl->startDefinition();
5936
5937 const size_t NumFields = 4;
5938 QualType FieldTypes[NumFields];
5939 const char *FieldNames[NumFields];
5940
5941 // unsigned gp_offset;
5942 FieldTypes[0] = Context->UnsignedIntTy;
5943 FieldNames[0] = "gp_offset";
5944
5945 // unsigned fp_offset;
5946 FieldTypes[1] = Context->UnsignedIntTy;
5947 FieldNames[1] = "fp_offset";
5948
5949 // void* overflow_arg_area;
5950 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5951 FieldNames[2] = "overflow_arg_area";
5952
5953 // void* reg_save_area;
5954 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5955 FieldNames[3] = "reg_save_area";
5956
5957 // Create fields
5958 for (unsigned i = 0; i < NumFields; ++i) {
5959 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5960 VaListTagDecl,
5961 SourceLocation(),
5962 SourceLocation(),
5963 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005964 FieldTypes[i], /*TInfo=*/nullptr,
5965 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00005966 /*Mutable=*/false,
5967 ICIS_NoInit);
5968 Field->setAccess(AS_public);
5969 VaListTagDecl->addDecl(Field);
5970 }
5971 VaListTagDecl->completeDefinition();
5972 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005973 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005974
5975 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005976 TypedefDecl *VaListTagTypedefDecl =
5977 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5978
Meador Inge5d3fb222012-06-16 03:34:49 +00005979 QualType VaListTagTypedefType =
5980 Context->getTypedefType(VaListTagTypedefDecl);
5981
5982 // typedef __va_list_tag __builtin_va_list[1];
5983 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5984 QualType VaListTagArrayType
5985 = Context->getConstantArrayType(VaListTagTypedefType,
5986 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005987 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005988}
5989
5990static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5991 // typedef int __builtin_va_list[4];
5992 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5993 QualType IntArrayType
5994 = Context->getConstantArrayType(Context->IntTy,
5995 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005996 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005997}
5998
Logan Chien57086ce2012-10-10 06:56:20 +00005999static TypedefDecl *
6000CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006001 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006002 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006003 if (Context->getLangOpts().CPlusPlus) {
6004 // namespace std { struct __va_list {
6005 NamespaceDecl *NS;
6006 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6007 Context->getTranslationUnitDecl(),
6008 /*Inline*/false, SourceLocation(),
6009 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006010 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006011 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006012 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006013 }
6014
6015 VaListDecl->startDefinition();
6016
6017 // void * __ap;
6018 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6019 VaListDecl,
6020 SourceLocation(),
6021 SourceLocation(),
6022 &Context->Idents.get("__ap"),
6023 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006024 /*TInfo=*/nullptr,
6025 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006026 /*Mutable=*/false,
6027 ICIS_NoInit);
6028 Field->setAccess(AS_public);
6029 VaListDecl->addDecl(Field);
6030
6031 // };
6032 VaListDecl->completeDefinition();
6033
6034 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006035 QualType T = Context->getRecordType(VaListDecl);
6036 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006037}
6038
Ulrich Weigand47445072013-05-06 16:26:41 +00006039static TypedefDecl *
6040CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6041 // typedef struct __va_list_tag {
6042 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006043 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006044 VaListTagDecl->startDefinition();
6045
6046 const size_t NumFields = 4;
6047 QualType FieldTypes[NumFields];
6048 const char *FieldNames[NumFields];
6049
6050 // long __gpr;
6051 FieldTypes[0] = Context->LongTy;
6052 FieldNames[0] = "__gpr";
6053
6054 // long __fpr;
6055 FieldTypes[1] = Context->LongTy;
6056 FieldNames[1] = "__fpr";
6057
6058 // void *__overflow_arg_area;
6059 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6060 FieldNames[2] = "__overflow_arg_area";
6061
6062 // void *__reg_save_area;
6063 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6064 FieldNames[3] = "__reg_save_area";
6065
6066 // Create fields
6067 for (unsigned i = 0; i < NumFields; ++i) {
6068 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6069 VaListTagDecl,
6070 SourceLocation(),
6071 SourceLocation(),
6072 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006073 FieldTypes[i], /*TInfo=*/nullptr,
6074 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006075 /*Mutable=*/false,
6076 ICIS_NoInit);
6077 Field->setAccess(AS_public);
6078 VaListTagDecl->addDecl(Field);
6079 }
6080 VaListTagDecl->completeDefinition();
6081 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6082 Context->VaListTagTy = VaListTagType;
6083
6084 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006085 TypedefDecl *VaListTagTypedefDecl =
6086 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006087 QualType VaListTagTypedefType =
6088 Context->getTypedefType(VaListTagTypedefDecl);
6089
6090 // typedef __va_list_tag __builtin_va_list[1];
6091 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6092 QualType VaListTagArrayType
6093 = Context->getConstantArrayType(VaListTagTypedefType,
6094 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006095
Alp Toker56b5cc92013-12-15 10:36:26 +00006096 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006097}
6098
Meador Inge5d3fb222012-06-16 03:34:49 +00006099static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6100 TargetInfo::BuiltinVaListKind Kind) {
6101 switch (Kind) {
6102 case TargetInfo::CharPtrBuiltinVaList:
6103 return CreateCharPtrBuiltinVaListDecl(Context);
6104 case TargetInfo::VoidPtrBuiltinVaList:
6105 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006106 case TargetInfo::AArch64ABIBuiltinVaList:
6107 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006108 case TargetInfo::PowerABIBuiltinVaList:
6109 return CreatePowerABIBuiltinVaListDecl(Context);
6110 case TargetInfo::X86_64ABIBuiltinVaList:
6111 return CreateX86_64ABIBuiltinVaListDecl(Context);
6112 case TargetInfo::PNaClABIBuiltinVaList:
6113 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006114 case TargetInfo::AAPCSABIBuiltinVaList:
6115 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006116 case TargetInfo::SystemZBuiltinVaList:
6117 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006118 }
6119
6120 llvm_unreachable("Unhandled __builtin_va_list type kind");
6121}
6122
6123TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006124 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006125 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006126 assert(BuiltinVaListDecl->isImplicit());
6127 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006128
6129 return BuiltinVaListDecl;
6130}
6131
Meador Ingecfb60902012-07-01 15:57:25 +00006132QualType ASTContext::getVaListTagType() const {
6133 // Force the creation of VaListTagTy by building the __builtin_va_list
6134 // declaration.
6135 if (VaListTagTy.isNull())
6136 (void) getBuiltinVaListDecl();
6137
6138 return VaListTagTy;
6139}
6140
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006141void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006142 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006143 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006144
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006145 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006146}
6147
John McCalld28ae272009-12-02 08:04:21 +00006148/// \brief Retrieve the template name that corresponds to a non-empty
6149/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006150TemplateName
6151ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6152 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006153 unsigned size = End - Begin;
6154 assert(size > 1 && "set is not overloaded!");
6155
6156 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6157 size * sizeof(FunctionTemplateDecl*));
6158 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6159
6160 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006161 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006162 NamedDecl *D = *I;
6163 assert(isa<FunctionTemplateDecl>(D) ||
6164 (isa<UsingShadowDecl>(D) &&
6165 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6166 *Storage++ = D;
6167 }
6168
6169 return TemplateName(OT);
6170}
6171
Douglas Gregordc572a32009-03-30 22:58:21 +00006172/// \brief Retrieve the template name that represents a qualified
6173/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006174TemplateName
6175ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6176 bool TemplateKeyword,
6177 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006178 assert(NNS && "Missing nested-name-specifier in qualified template name");
6179
Douglas Gregorc42075a2010-02-04 18:10:26 +00006180 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006181 llvm::FoldingSetNodeID ID;
6182 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6183
Craig Topper36250ad2014-05-12 05:36:57 +00006184 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006185 QualifiedTemplateName *QTN =
6186 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6187 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006188 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6189 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006190 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6191 }
6192
6193 return TemplateName(QTN);
6194}
6195
6196/// \brief Retrieve the template name that represents a dependent
6197/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006198TemplateName
6199ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6200 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006201 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006202 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006203
6204 llvm::FoldingSetNodeID ID;
6205 DependentTemplateName::Profile(ID, NNS, Name);
6206
Craig Topper36250ad2014-05-12 05:36:57 +00006207 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006208 DependentTemplateName *QTN =
6209 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6210
6211 if (QTN)
6212 return TemplateName(QTN);
6213
6214 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6215 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006216 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6217 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006218 } else {
6219 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006220 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6221 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006222 DependentTemplateName *CheckQTN =
6223 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6224 assert(!CheckQTN && "Dependent type name canonicalization broken");
6225 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006226 }
6227
6228 DependentTemplateNames.InsertNode(QTN, InsertPos);
6229 return TemplateName(QTN);
6230}
6231
Douglas Gregor71395fa2009-11-04 00:56:37 +00006232/// \brief Retrieve the template name that represents a dependent
6233/// template name such as \c MetaFun::template operator+.
6234TemplateName
6235ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006236 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006237 assert((!NNS || NNS->isDependent()) &&
6238 "Nested name specifier must be dependent");
6239
6240 llvm::FoldingSetNodeID ID;
6241 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006242
6243 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006244 DependentTemplateName *QTN
6245 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006246
6247 if (QTN)
6248 return TemplateName(QTN);
6249
6250 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6251 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006252 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6253 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006254 } else {
6255 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006256 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6257 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006258
6259 DependentTemplateName *CheckQTN
6260 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6261 assert(!CheckQTN && "Dependent template name canonicalization broken");
6262 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006263 }
6264
6265 DependentTemplateNames.InsertNode(QTN, InsertPos);
6266 return TemplateName(QTN);
6267}
6268
Douglas Gregor5590be02011-01-15 06:45:20 +00006269TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006270ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6271 TemplateName replacement) const {
6272 llvm::FoldingSetNodeID ID;
6273 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006274
6275 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006276 SubstTemplateTemplateParmStorage *subst
6277 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6278
6279 if (!subst) {
6280 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6281 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6282 }
6283
6284 return TemplateName(subst);
6285}
6286
6287TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006288ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6289 const TemplateArgument &ArgPack) const {
6290 ASTContext &Self = const_cast<ASTContext &>(*this);
6291 llvm::FoldingSetNodeID ID;
6292 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006293
6294 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006295 SubstTemplateTemplateParmPackStorage *Subst
6296 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6297
6298 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006299 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006300 ArgPack.pack_size(),
6301 ArgPack.pack_begin());
6302 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6303 }
6304
6305 return TemplateName(Subst);
6306}
6307
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006308/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006309/// TargetInfo, produce the corresponding type. The unsigned @p Type
6310/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006311CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006312 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006313 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006314 case TargetInfo::SignedChar: return SignedCharTy;
6315 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006316 case TargetInfo::SignedShort: return ShortTy;
6317 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6318 case TargetInfo::SignedInt: return IntTy;
6319 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6320 case TargetInfo::SignedLong: return LongTy;
6321 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6322 case TargetInfo::SignedLongLong: return LongLongTy;
6323 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6324 }
6325
David Blaikie83d382b2011-09-23 05:06:16 +00006326 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006327}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006328
6329//===----------------------------------------------------------------------===//
6330// Type Predicates.
6331//===----------------------------------------------------------------------===//
6332
Fariborz Jahanian96207692009-02-18 21:49:28 +00006333/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6334/// garbage collection attribute.
6335///
John McCall553d45a2011-01-12 00:34:59 +00006336Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006337 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006338 return Qualifiers::GCNone;
6339
David Blaikiebbafb8a2012-03-11 07:00:24 +00006340 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006341 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6342
6343 // Default behaviour under objective-C's gc is for ObjC pointers
6344 // (or pointers to them) be treated as though they were declared
6345 // as __strong.
6346 if (GCAttrs == Qualifiers::GCNone) {
6347 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6348 return Qualifiers::Strong;
6349 else if (Ty->isPointerType())
6350 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6351 } else {
6352 // It's not valid to set GC attributes on anything that isn't a
6353 // pointer.
6354#ifndef NDEBUG
6355 QualType CT = Ty->getCanonicalTypeInternal();
6356 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6357 CT = AT->getElementType();
6358 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6359#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006360 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006361 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006362}
6363
Chris Lattner49af6a42008-04-07 06:51:04 +00006364//===----------------------------------------------------------------------===//
6365// Type Compatibility Testing
6366//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006367
Mike Stump11289f42009-09-09 15:08:12 +00006368/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006369/// compatible.
6370static bool areCompatVectorTypes(const VectorType *LHS,
6371 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006372 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006373 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006374 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006375}
6376
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006377bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6378 QualType SecondVec) {
6379 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6380 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6381
6382 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6383 return true;
6384
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006385 // Treat Neon vector types and most AltiVec vector types as if they are the
6386 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006387 const VectorType *First = FirstVec->getAs<VectorType>();
6388 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006389 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006390 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006391 First->getVectorKind() != VectorType::AltiVecPixel &&
6392 First->getVectorKind() != VectorType::AltiVecBool &&
6393 Second->getVectorKind() != VectorType::AltiVecPixel &&
6394 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006395 return true;
6396
6397 return false;
6398}
6399
Steve Naroff8e6aee52009-07-23 01:01:38 +00006400//===----------------------------------------------------------------------===//
6401// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6402//===----------------------------------------------------------------------===//
6403
6404/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6405/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006406bool
6407ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6408 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006409 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006410 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006411 for (auto *PI : rProto->protocols())
6412 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006413 return true;
6414 return false;
6415}
6416
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006417/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6418/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006419bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6420 QualType rhs) {
6421 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6422 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6423 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6424
Aaron Ballman83731462014-03-17 16:14:00 +00006425 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006426 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006427 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006428 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6429 match = true;
6430 break;
6431 }
6432 }
6433 if (!match)
6434 return false;
6435 }
6436 return true;
6437}
6438
Steve Naroff8e6aee52009-07-23 01:01:38 +00006439/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6440/// ObjCQualifiedIDType.
6441bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6442 bool compare) {
6443 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006444 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006445 lhs->isObjCIdType() || lhs->isObjCClassType())
6446 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006447 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006448 rhs->isObjCIdType() || rhs->isObjCClassType())
6449 return true;
6450
6451 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006452 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006453
Steve Naroff8e6aee52009-07-23 01:01:38 +00006454 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006455
Steve Naroff8e6aee52009-07-23 01:01:38 +00006456 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006457 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006458 // make sure we check the class hierarchy.
6459 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006460 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006461 // when comparing an id<P> on lhs with a static type on rhs,
6462 // see if static class implements all of id's protocols, directly or
6463 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006464 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006465 return false;
6466 }
6467 }
6468 // If there are no qualifiers and no interface, we have an 'id'.
6469 return true;
6470 }
Mike Stump11289f42009-09-09 15:08:12 +00006471 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006472 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006473 bool match = false;
6474
6475 // when comparing an id<P> on lhs with a static type on rhs,
6476 // see if static class implements all of id's protocols, directly or
6477 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006478 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006479 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6480 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6481 match = true;
6482 break;
6483 }
6484 }
Mike Stump11289f42009-09-09 15:08:12 +00006485 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006486 // make sure we check the class hierarchy.
6487 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006488 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006489 // when comparing an id<P> on lhs with a static type on rhs,
6490 // see if static class implements all of id's protocols, directly or
6491 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006492 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006493 match = true;
6494 break;
6495 }
6496 }
6497 }
6498 if (!match)
6499 return false;
6500 }
Mike Stump11289f42009-09-09 15:08:12 +00006501
Steve Naroff8e6aee52009-07-23 01:01:38 +00006502 return true;
6503 }
Mike Stump11289f42009-09-09 15:08:12 +00006504
Steve Naroff8e6aee52009-07-23 01:01:38 +00006505 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6506 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6507
Mike Stump11289f42009-09-09 15:08:12 +00006508 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006509 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006510 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006511 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006512 bool match = false;
6513
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006514 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006515 // see if static class implements all of id's protocols, directly or
6516 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006517 // First, lhs protocols in the qualifier list must be found, direct
6518 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006519 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006520 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6521 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6522 match = true;
6523 break;
6524 }
6525 }
6526 if (!match)
6527 return false;
6528 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006529
6530 // Static class's protocols, or its super class or category protocols
6531 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6532 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6533 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6534 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6535 // This is rather dubious but matches gcc's behavior. If lhs has
6536 // no type qualifier and its class has no static protocol(s)
6537 // assume that it is mismatch.
6538 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6539 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006540 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006541 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006542 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006543 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6544 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6545 match = true;
6546 break;
6547 }
6548 }
6549 if (!match)
6550 return false;
6551 }
6552 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006553 return true;
6554 }
6555 return false;
6556}
6557
Eli Friedman47f77112008-08-22 00:56:42 +00006558/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006559/// compatible for assignment from RHS to LHS. This handles validation of any
6560/// protocol qualifiers on the LHS or RHS.
6561///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006562bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6563 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006564 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6565 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6566
Steve Naroff1329fa02009-07-15 18:40:39 +00006567 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006568 if (LHS->isObjCUnqualifiedIdOrClass() ||
6569 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006570 return true;
6571
John McCall8b07ec22010-05-15 11:32:37 +00006572 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006573 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6574 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006575 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006576
6577 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6578 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6579 QualType(RHSOPT,0));
6580
John McCall8b07ec22010-05-15 11:32:37 +00006581 // If we have 2 user-defined types, fall into that path.
6582 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006583 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006584
Steve Naroff8e6aee52009-07-23 01:01:38 +00006585 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006586}
6587
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006588/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006589/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006590/// arguments in block literals. When passed as arguments, passing 'A*' where
6591/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6592/// not OK. For the return type, the opposite is not OK.
6593bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6594 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006595 const ObjCObjectPointerType *RHSOPT,
6596 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006597 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006598 return true;
6599
6600 if (LHSOPT->isObjCBuiltinType()) {
6601 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6602 }
6603
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006604 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006605 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6606 QualType(RHSOPT,0),
6607 false);
6608
6609 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6610 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6611 if (LHS && RHS) { // We have 2 user-defined types.
6612 if (LHS != RHS) {
6613 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006614 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006615 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006616 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006617 }
6618 else
6619 return true;
6620 }
6621 return false;
6622}
6623
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006624/// getIntersectionOfProtocols - This routine finds the intersection of set
6625/// of protocols inherited from two distinct objective-c pointer objects.
6626/// It is used to build composite qualifier list of the composite type of
6627/// the conditional expression involving two objective-c pointer objects.
6628static
6629void getIntersectionOfProtocols(ASTContext &Context,
6630 const ObjCObjectPointerType *LHSOPT,
6631 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006632 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006633
John McCall8b07ec22010-05-15 11:32:37 +00006634 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6635 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6636 assert(LHS->getInterface() && "LHS must have an interface base");
6637 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006638
6639 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6640 unsigned LHSNumProtocols = LHS->getNumProtocols();
6641 if (LHSNumProtocols > 0)
6642 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6643 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006644 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006645 Context.CollectInheritedProtocols(LHS->getInterface(),
6646 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006647 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6648 LHSInheritedProtocols.end());
6649 }
6650
6651 unsigned RHSNumProtocols = RHS->getNumProtocols();
6652 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006653 ObjCProtocolDecl **RHSProtocols =
6654 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006655 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6656 if (InheritedProtocolSet.count(RHSProtocols[i]))
6657 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006658 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006659 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006660 Context.CollectInheritedProtocols(RHS->getInterface(),
6661 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006662 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6663 RHSInheritedProtocols.begin(),
6664 E = RHSInheritedProtocols.end(); I != E; ++I)
6665 if (InheritedProtocolSet.count((*I)))
6666 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006667 }
6668}
6669
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006670/// areCommonBaseCompatible - Returns common base class of the two classes if
6671/// one found. Note that this is O'2 algorithm. But it will be called as the
6672/// last type comparison in a ?-exp of ObjC pointer types before a
6673/// warning is issued. So, its invokation is extremely rare.
6674QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006675 const ObjCObjectPointerType *Lptr,
6676 const ObjCObjectPointerType *Rptr) {
6677 const ObjCObjectType *LHS = Lptr->getObjectType();
6678 const ObjCObjectType *RHS = Rptr->getObjectType();
6679 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6680 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006681 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006682 return QualType();
6683
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006684 do {
John McCall8b07ec22010-05-15 11:32:37 +00006685 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006686 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006687 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006688 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6689
6690 QualType Result = QualType(LHS, 0);
6691 if (!Protocols.empty())
6692 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6693 Result = getObjCObjectPointerType(Result);
6694 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006695 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006696 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006697
6698 return QualType();
6699}
6700
John McCall8b07ec22010-05-15 11:32:37 +00006701bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6702 const ObjCObjectType *RHS) {
6703 assert(LHS->getInterface() && "LHS is not an interface type");
6704 assert(RHS->getInterface() && "RHS is not an interface type");
6705
Chris Lattner49af6a42008-04-07 06:51:04 +00006706 // Verify that the base decls are compatible: the RHS must be a subclass of
6707 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006708 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006709 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006710
Chris Lattner49af6a42008-04-07 06:51:04 +00006711 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6712 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006713 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006714 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006715
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006716 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6717 // more detailed analysis is required.
6718 if (RHS->getNumProtocols() == 0) {
6719 // OK, if LHS is a superclass of RHS *and*
6720 // this superclass is assignment compatible with LHS.
6721 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006722 bool IsSuperClass =
6723 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6724 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006725 // OK if conversion of LHS to SuperClass results in narrowing of types
6726 // ; i.e., SuperClass may implement at least one of the protocols
6727 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6728 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6729 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006730 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006731 // If super class has no protocols, it is not a match.
6732 if (SuperClassInheritedProtocols.empty())
6733 return false;
6734
Aaron Ballman1683f7b2014-03-17 15:55:30 +00006735 for (const auto *LHSProto : LHS->quals()) {
6736 bool SuperImplementsProtocol = false;
6737 for (auto *SuperClassProto : SuperClassInheritedProtocols) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006738 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6739 SuperImplementsProtocol = true;
6740 break;
6741 }
6742 }
6743 if (!SuperImplementsProtocol)
6744 return false;
6745 }
6746 return true;
6747 }
6748 return false;
6749 }
Mike Stump11289f42009-09-09 15:08:12 +00006750
Aaron Ballman1683f7b2014-03-17 15:55:30 +00006751 for (const auto *LHSPI : LHS->quals()) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006752 bool RHSImplementsProtocol = false;
6753
6754 // If the RHS doesn't implement the protocol on the left, the types
6755 // are incompatible.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00006756 for (auto *RHSPI : RHS->quals()) {
6757 if (RHSPI->lookupProtocolNamed(LHSPI->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006758 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006759 break;
6760 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006761 }
6762 // FIXME: For better diagnostics, consider passing back the protocol name.
6763 if (!RHSImplementsProtocol)
6764 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006765 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006766 // The RHS implements all protocols listed on the LHS.
6767 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006768}
6769
Steve Naroffb7605152009-02-12 17:52:19 +00006770bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6771 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006772 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6773 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006774
Steve Naroff7cae42b2009-07-10 23:34:53 +00006775 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006776 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006777
6778 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6779 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006780}
6781
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006782bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6783 return canAssignObjCInterfaces(
6784 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6785 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6786}
6787
Mike Stump11289f42009-09-09 15:08:12 +00006788/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006789/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006790/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006791/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006792bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6793 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006794 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006795 return hasSameType(LHS, RHS);
6796
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006797 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006798}
6799
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006800bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006801 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006802}
6803
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006804bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6805 return !mergeTypes(LHS, RHS, true).isNull();
6806}
6807
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006808/// mergeTransparentUnionType - if T is a transparent union type and a member
6809/// of T is compatible with SubType, return the merged type, else return
6810/// QualType()
6811QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6812 bool OfBlockPointer,
6813 bool Unqualified) {
6814 if (const RecordType *UT = T->getAsUnionType()) {
6815 RecordDecl *UD = UT->getDecl();
6816 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006817 for (const auto *I : UD->fields()) {
6818 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006819 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6820 if (!MT.isNull())
6821 return MT;
6822 }
6823 }
6824 }
6825
6826 return QualType();
6827}
6828
Alp Toker9cacbab2014-01-20 20:26:09 +00006829/// mergeFunctionParameterTypes - merge two types which appear as function
6830/// parameter types
6831QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6832 bool OfBlockPointer,
6833 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006834 // GNU extension: two types are compatible if they appear as a function
6835 // argument, one of the types is a transparent union type and the other
6836 // type is compatible with a union member
6837 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6838 Unqualified);
6839 if (!lmerge.isNull())
6840 return lmerge;
6841
6842 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6843 Unqualified);
6844 if (!rmerge.isNull())
6845 return rmerge;
6846
6847 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6848}
6849
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006850QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006851 bool OfBlockPointer,
6852 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006853 const FunctionType *lbase = lhs->getAs<FunctionType>();
6854 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006855 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6856 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006857 bool allLTypes = true;
6858 bool allRTypes = true;
6859
6860 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006861 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006862 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006863 QualType RHS = rbase->getReturnType();
6864 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006865 bool UnqualifiedResult = Unqualified;
6866 if (!UnqualifiedResult)
6867 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006868 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006869 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006870 else
Alp Toker314cc812014-01-25 16:55:45 +00006871 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006872 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006873 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006874
6875 if (Unqualified)
6876 retType = retType.getUnqualifiedType();
6877
Alp Toker314cc812014-01-25 16:55:45 +00006878 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6879 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006880 if (Unqualified) {
6881 LRetType = LRetType.getUnqualifiedType();
6882 RRetType = RRetType.getUnqualifiedType();
6883 }
6884
6885 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006886 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006887 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006888 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006889
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006890 // FIXME: double check this
6891 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6892 // rbase->getRegParmAttr() != 0 &&
6893 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006894 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6895 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006896
Douglas Gregor8c940862010-01-18 17:14:39 +00006897 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006898 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006899 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006900
John McCall8c6b56f2010-12-15 01:06:38 +00006901 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006902 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6903 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006904 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6905 return QualType();
6906
John McCall31168b02011-06-15 23:02:42 +00006907 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6908 return QualType();
6909
John McCall8c6b56f2010-12-15 01:06:38 +00006910 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6911 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006912
Rafael Espindola8778c282012-11-29 16:09:03 +00006913 if (lbaseInfo.getNoReturn() != NoReturn)
6914 allLTypes = false;
6915 if (rbaseInfo.getNoReturn() != NoReturn)
6916 allRTypes = false;
6917
John McCall31168b02011-06-15 23:02:42 +00006918 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006919
Eli Friedman47f77112008-08-22 00:56:42 +00006920 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006921 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6922 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006923 // Compatible functions must have the same number of parameters
6924 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006925 return QualType();
6926
6927 // Variadic and non-variadic functions aren't compatible
6928 if (lproto->isVariadic() != rproto->isVariadic())
6929 return QualType();
6930
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006931 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6932 return QualType();
6933
Fariborz Jahanian97676972011-09-28 21:52:05 +00006934 if (LangOpts.ObjCAutoRefCount &&
6935 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6936 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006937
6938 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006939 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00006940 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6941 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6942 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6943 QualType paramType = mergeFunctionParameterTypes(
6944 lParamType, rParamType, OfBlockPointer, Unqualified);
6945 if (paramType.isNull())
6946 return QualType();
6947
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006948 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00006949 paramType = paramType.getUnqualifiedType();
6950
6951 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006952 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00006953 lParamType = lParamType.getUnqualifiedType();
6954 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006955 }
Alp Toker601b22c2014-01-21 23:35:24 +00006956
6957 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006958 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00006959 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006960 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006961 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006962
Eli Friedman47f77112008-08-22 00:56:42 +00006963 if (allLTypes) return lhs;
6964 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006965
6966 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6967 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006968 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006969 }
6970
6971 if (lproto) allRTypes = false;
6972 if (rproto) allLTypes = false;
6973
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006974 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006975 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006976 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006977 if (proto->isVariadic()) return QualType();
6978 // Check that the types are compatible with the types that
6979 // would result from default argument promotions (C99 6.7.5.3p15).
6980 // The only types actually affected are promotable integer
6981 // types and floats, which would be passed as a different
6982 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00006983 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
6984 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00006985
Eli Friedman448ce402012-08-30 00:44:15 +00006986 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006987 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00006988 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
6989 paramTy = Enum->getDecl()->getIntegerType();
6990 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00006991 return QualType();
6992 }
Alp Toker601b22c2014-01-21 23:35:24 +00006993
6994 if (paramTy->isPromotableIntegerType() ||
6995 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00006996 return QualType();
6997 }
6998
6999 if (allLTypes) return lhs;
7000 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007001
7002 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7003 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007004 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007005 }
7006
7007 if (allLTypes) return lhs;
7008 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007009 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007010}
7011
John McCall433c2e62013-03-21 00:10:07 +00007012/// Given that we have an enum type and a non-enum type, try to merge them.
7013static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7014 QualType other, bool isBlockReturnType) {
7015 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7016 // a signed integer type, or an unsigned integer type.
7017 // Compatibility is based on the underlying type, not the promotion
7018 // type.
7019 QualType underlyingType = ET->getDecl()->getIntegerType();
7020 if (underlyingType.isNull()) return QualType();
7021 if (Context.hasSameType(underlyingType, other))
7022 return other;
7023
7024 // In block return types, we're more permissive and accept any
7025 // integral type of the same size.
7026 if (isBlockReturnType && other->isIntegerType() &&
7027 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7028 return other;
7029
7030 return QualType();
7031}
7032
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007033QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007034 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007035 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007036 // C++ [expr]: If an expression initially has the type "reference to T", the
7037 // type is adjusted to "T" prior to any further analysis, the expression
7038 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007039 // expression is an lvalue unless the reference is an rvalue reference and
7040 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007041 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7042 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007043
7044 if (Unqualified) {
7045 LHS = LHS.getUnqualifiedType();
7046 RHS = RHS.getUnqualifiedType();
7047 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007048
Eli Friedman47f77112008-08-22 00:56:42 +00007049 QualType LHSCan = getCanonicalType(LHS),
7050 RHSCan = getCanonicalType(RHS);
7051
7052 // If two types are identical, they are compatible.
7053 if (LHSCan == RHSCan)
7054 return LHS;
7055
John McCall8ccfcb52009-09-24 19:53:00 +00007056 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007057 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7058 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007059 if (LQuals != RQuals) {
7060 // If any of these qualifiers are different, we have a type
7061 // mismatch.
7062 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007063 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7064 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007065 return QualType();
7066
7067 // Exactly one GC qualifier difference is allowed: __strong is
7068 // okay if the other type has no GC qualifier but is an Objective
7069 // C object pointer (i.e. implicitly strong by default). We fix
7070 // this by pretending that the unqualified type was actually
7071 // qualified __strong.
7072 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7073 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7074 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7075
7076 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7077 return QualType();
7078
7079 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7080 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7081 }
7082 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7083 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7084 }
Eli Friedman47f77112008-08-22 00:56:42 +00007085 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007086 }
7087
7088 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007089
Eli Friedmandcca6332009-06-01 01:22:52 +00007090 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7091 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007092
Chris Lattnerfd652912008-01-14 05:45:46 +00007093 // We want to consider the two function types to be the same for these
7094 // comparisons, just force one to the other.
7095 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7096 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007097
7098 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007099 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7100 LHSClass = Type::ConstantArray;
7101 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7102 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007103
John McCall8b07ec22010-05-15 11:32:37 +00007104 // ObjCInterfaces are just specialized ObjCObjects.
7105 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7106 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7107
Nate Begemance4d7fc2008-04-18 23:10:10 +00007108 // Canonicalize ExtVector -> Vector.
7109 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7110 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007111
Chris Lattner95554662008-04-07 05:43:21 +00007112 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007113 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007114 // Note that we only have special rules for turning block enum
7115 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007116 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007117 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007118 }
John McCall9dd450b2009-09-21 23:43:11 +00007119 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007120 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007121 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007122 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007123 if (OfBlockPointer && !BlockReturnType) {
7124 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7125 return LHS;
7126 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7127 return RHS;
7128 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007129
Eli Friedman47f77112008-08-22 00:56:42 +00007130 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007131 }
Eli Friedman47f77112008-08-22 00:56:42 +00007132
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007133 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007134 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007135#define TYPE(Class, Base)
7136#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007137#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007138#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7139#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7140#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007141 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007142
Richard Smith27d807c2013-04-30 13:56:41 +00007143 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007144 case Type::LValueReference:
7145 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007146 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007147 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007148
John McCall8b07ec22010-05-15 11:32:37 +00007149 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007150 case Type::IncompleteArray:
7151 case Type::VariableArray:
7152 case Type::FunctionProto:
7153 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007154 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007155
Chris Lattnerfd652912008-01-14 05:45:46 +00007156 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007157 {
7158 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007159 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7160 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007161 if (Unqualified) {
7162 LHSPointee = LHSPointee.getUnqualifiedType();
7163 RHSPointee = RHSPointee.getUnqualifiedType();
7164 }
7165 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7166 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007167 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007168 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007169 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007170 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007171 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007172 return getPointerType(ResultType);
7173 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007174 case Type::BlockPointer:
7175 {
7176 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007177 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7178 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007179 if (Unqualified) {
7180 LHSPointee = LHSPointee.getUnqualifiedType();
7181 RHSPointee = RHSPointee.getUnqualifiedType();
7182 }
7183 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7184 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007185 if (ResultType.isNull()) return QualType();
7186 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7187 return LHS;
7188 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7189 return RHS;
7190 return getBlockPointerType(ResultType);
7191 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007192 case Type::Atomic:
7193 {
7194 // Merge two pointer types, while trying to preserve typedef info
7195 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7196 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7197 if (Unqualified) {
7198 LHSValue = LHSValue.getUnqualifiedType();
7199 RHSValue = RHSValue.getUnqualifiedType();
7200 }
7201 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7202 Unqualified);
7203 if (ResultType.isNull()) return QualType();
7204 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7205 return LHS;
7206 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7207 return RHS;
7208 return getAtomicType(ResultType);
7209 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007210 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007211 {
7212 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7213 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7214 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7215 return QualType();
7216
7217 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7218 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007219 if (Unqualified) {
7220 LHSElem = LHSElem.getUnqualifiedType();
7221 RHSElem = RHSElem.getUnqualifiedType();
7222 }
7223
7224 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007225 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007226 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7227 return LHS;
7228 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7229 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007230 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7231 ArrayType::ArraySizeModifier(), 0);
7232 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7233 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007234 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7235 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007236 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7237 return LHS;
7238 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7239 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007240 if (LVAT) {
7241 // FIXME: This isn't correct! But tricky to implement because
7242 // the array's size has to be the size of LHS, but the type
7243 // has to be different.
7244 return LHS;
7245 }
7246 if (RVAT) {
7247 // FIXME: This isn't correct! But tricky to implement because
7248 // the array's size has to be the size of RHS, but the type
7249 // has to be different.
7250 return RHS;
7251 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007252 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7253 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007254 return getIncompleteArrayType(ResultType,
7255 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007256 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007257 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007258 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007259 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007260 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007261 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007262 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007263 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007264 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007265 case Type::Complex:
7266 // Distinct complex types are incompatible.
7267 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007268 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007269 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007270 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7271 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007272 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007273 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007274 case Type::ObjCObject: {
7275 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007276 // FIXME: This should be type compatibility, e.g. whether
7277 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007278 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7279 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7280 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007281 return LHS;
7282
Eli Friedman47f77112008-08-22 00:56:42 +00007283 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007284 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007285 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007286 if (OfBlockPointer) {
7287 if (canAssignObjCInterfacesInBlockPointer(
7288 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007289 RHS->getAs<ObjCObjectPointerType>(),
7290 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007291 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007292 return QualType();
7293 }
John McCall9dd450b2009-09-21 23:43:11 +00007294 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7295 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007296 return LHS;
7297
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007298 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007299 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007300 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007301
David Blaikie8a40f702012-01-17 06:56:22 +00007302 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007303}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007304
Fariborz Jahanian97676972011-09-28 21:52:05 +00007305bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7306 const FunctionProtoType *FromFunctionType,
7307 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007308 if (FromFunctionType->hasAnyConsumedParams() !=
7309 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007310 return false;
7311 FunctionProtoType::ExtProtoInfo FromEPI =
7312 FromFunctionType->getExtProtoInfo();
7313 FunctionProtoType::ExtProtoInfo ToEPI =
7314 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007315 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007316 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7317 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007318 return false;
7319 }
7320 return true;
7321}
7322
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007323/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7324/// 'RHS' attributes and returns the merged version; including for function
7325/// return types.
7326QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7327 QualType LHSCan = getCanonicalType(LHS),
7328 RHSCan = getCanonicalType(RHS);
7329 // If two types are identical, they are compatible.
7330 if (LHSCan == RHSCan)
7331 return LHS;
7332 if (RHSCan->isFunctionType()) {
7333 if (!LHSCan->isFunctionType())
7334 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007335 QualType OldReturnType =
7336 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007337 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007338 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007339 QualType ResReturnType =
7340 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7341 if (ResReturnType.isNull())
7342 return QualType();
7343 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7344 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7345 // In either case, use OldReturnType to build the new function type.
7346 const FunctionType *F = LHS->getAs<FunctionType>();
7347 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007348 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7349 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007350 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007351 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007352 return ResultType;
7353 }
7354 }
7355 return QualType();
7356 }
7357
7358 // If the qualifiers are different, the types can still be merged.
7359 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7360 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7361 if (LQuals != RQuals) {
7362 // If any of these qualifiers are different, we have a type mismatch.
7363 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7364 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7365 return QualType();
7366
7367 // Exactly one GC qualifier difference is allowed: __strong is
7368 // okay if the other type has no GC qualifier but is an Objective
7369 // C object pointer (i.e. implicitly strong by default). We fix
7370 // this by pretending that the unqualified type was actually
7371 // qualified __strong.
7372 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7373 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7374 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7375
7376 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7377 return QualType();
7378
7379 if (GC_L == Qualifiers::Strong)
7380 return LHS;
7381 if (GC_R == Qualifiers::Strong)
7382 return RHS;
7383 return QualType();
7384 }
7385
7386 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7387 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7388 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7389 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7390 if (ResQT == LHSBaseQT)
7391 return LHS;
7392 if (ResQT == RHSBaseQT)
7393 return RHS;
7394 }
7395 return QualType();
7396}
7397
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007398//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007399// Integer Predicates
7400//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007401
Jay Foad39c79802011-01-12 09:06:06 +00007402unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007403 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007404 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007405 if (T->isBooleanType())
7406 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007407 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007408 return (unsigned)getTypeSize(T);
7409}
7410
Abramo Bagnara13640492012-09-09 10:21:24 +00007411QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007412 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007413
7414 // Turn <4 x signed int> -> <4 x unsigned int>
7415 if (const VectorType *VTy = T->getAs<VectorType>())
7416 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007417 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007418
7419 // For enums, we return the unsigned version of the base type.
7420 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007421 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007422
7423 const BuiltinType *BTy = T->getAs<BuiltinType>();
7424 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007425 switch (BTy->getKind()) {
7426 case BuiltinType::Char_S:
7427 case BuiltinType::SChar:
7428 return UnsignedCharTy;
7429 case BuiltinType::Short:
7430 return UnsignedShortTy;
7431 case BuiltinType::Int:
7432 return UnsignedIntTy;
7433 case BuiltinType::Long:
7434 return UnsignedLongTy;
7435 case BuiltinType::LongLong:
7436 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007437 case BuiltinType::Int128:
7438 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007439 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007440 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007441 }
7442}
7443
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007444ASTMutationListener::~ASTMutationListener() { }
7445
Richard Smith1fa5d642013-05-11 05:45:24 +00007446void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7447 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007448
7449//===----------------------------------------------------------------------===//
7450// Builtin Type Computation
7451//===----------------------------------------------------------------------===//
7452
7453/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007454/// pointer over the consumed characters. This returns the resultant type. If
7455/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7456/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7457/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007458///
7459/// RequiresICE is filled in on return to indicate whether the value is required
7460/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007461static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007462 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007463 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007464 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007465 // Modifiers.
7466 int HowLong = 0;
7467 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007468 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007469
Chris Lattnerdc226c22010-10-01 22:42:38 +00007470 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007471 bool Done = false;
7472 while (!Done) {
7473 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007474 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007475 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007476 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007477 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007478 case 'S':
7479 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7480 assert(!Signed && "Can't use 'S' modifier multiple times!");
7481 Signed = true;
7482 break;
7483 case 'U':
7484 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7485 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7486 Unsigned = true;
7487 break;
7488 case 'L':
7489 assert(HowLong <= 2 && "Can't have LLLL modifier");
7490 ++HowLong;
7491 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007492 case 'W':
7493 // This modifier represents int64 type.
7494 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7495 switch (Context.getTargetInfo().getInt64Type()) {
7496 default:
7497 llvm_unreachable("Unexpected integer type");
7498 case TargetInfo::SignedLong:
7499 HowLong = 1;
7500 break;
7501 case TargetInfo::SignedLongLong:
7502 HowLong = 2;
7503 break;
7504 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007505 }
7506 }
7507
7508 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007509
Chris Lattnerecd79c62009-06-14 00:45:47 +00007510 // Read the base type.
7511 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007512 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007513 case 'v':
7514 assert(HowLong == 0 && !Signed && !Unsigned &&
7515 "Bad modifiers used with 'v'!");
7516 Type = Context.VoidTy;
7517 break;
Jack Carter24bef982013-08-15 15:16:57 +00007518 case 'h':
7519 assert(HowLong == 0 && !Signed && !Unsigned &&
7520 "Bad modifiers used with 'f'!");
7521 Type = Context.HalfTy;
7522 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007523 case 'f':
7524 assert(HowLong == 0 && !Signed && !Unsigned &&
7525 "Bad modifiers used with 'f'!");
7526 Type = Context.FloatTy;
7527 break;
7528 case 'd':
7529 assert(HowLong < 2 && !Signed && !Unsigned &&
7530 "Bad modifiers used with 'd'!");
7531 if (HowLong)
7532 Type = Context.LongDoubleTy;
7533 else
7534 Type = Context.DoubleTy;
7535 break;
7536 case 's':
7537 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7538 if (Unsigned)
7539 Type = Context.UnsignedShortTy;
7540 else
7541 Type = Context.ShortTy;
7542 break;
7543 case 'i':
7544 if (HowLong == 3)
7545 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7546 else if (HowLong == 2)
7547 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7548 else if (HowLong == 1)
7549 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7550 else
7551 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7552 break;
7553 case 'c':
7554 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7555 if (Signed)
7556 Type = Context.SignedCharTy;
7557 else if (Unsigned)
7558 Type = Context.UnsignedCharTy;
7559 else
7560 Type = Context.CharTy;
7561 break;
7562 case 'b': // boolean
7563 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7564 Type = Context.BoolTy;
7565 break;
7566 case 'z': // size_t.
7567 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7568 Type = Context.getSizeType();
7569 break;
7570 case 'F':
7571 Type = Context.getCFConstantStringType();
7572 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007573 case 'G':
7574 Type = Context.getObjCIdType();
7575 break;
7576 case 'H':
7577 Type = Context.getObjCSelType();
7578 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007579 case 'M':
7580 Type = Context.getObjCSuperType();
7581 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007582 case 'a':
7583 Type = Context.getBuiltinVaListType();
7584 assert(!Type.isNull() && "builtin va list type not initialized!");
7585 break;
7586 case 'A':
7587 // This is a "reference" to a va_list; however, what exactly
7588 // this means depends on how va_list is defined. There are two
7589 // different kinds of va_list: ones passed by value, and ones
7590 // passed by reference. An example of a by-value va_list is
7591 // x86, where va_list is a char*. An example of by-ref va_list
7592 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7593 // we want this argument to be a char*&; for x86-64, we want
7594 // it to be a __va_list_tag*.
7595 Type = Context.getBuiltinVaListType();
7596 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007597 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007598 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007599 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007600 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007601 break;
7602 case 'V': {
7603 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007604 unsigned NumElements = strtoul(Str, &End, 10);
7605 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007606 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007607
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007608 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7609 RequiresICE, false);
7610 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007611
7612 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007613 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007614 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007615 break;
7616 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007617 case 'E': {
7618 char *End;
7619
7620 unsigned NumElements = strtoul(Str, &End, 10);
7621 assert(End != Str && "Missing vector size");
7622
7623 Str = End;
7624
7625 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7626 false);
7627 Type = Context.getExtVectorType(ElementType, NumElements);
7628 break;
7629 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007630 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007631 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7632 false);
7633 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007634 Type = Context.getComplexType(ElementType);
7635 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007636 }
7637 case 'Y' : {
7638 Type = Context.getPointerDiffType();
7639 break;
7640 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007641 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007642 Type = Context.getFILEType();
7643 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007644 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007645 return QualType();
7646 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007647 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007648 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007649 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007650 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007651 else
7652 Type = Context.getjmp_bufType();
7653
Mike Stump2adb4da2009-07-28 23:47:15 +00007654 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007655 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007656 return QualType();
7657 }
7658 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007659 case 'K':
7660 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7661 Type = Context.getucontext_tType();
7662
7663 if (Type.isNull()) {
7664 Error = ASTContext::GE_Missing_ucontext;
7665 return QualType();
7666 }
7667 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007668 case 'p':
7669 Type = Context.getProcessIDType();
7670 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007671 }
Mike Stump11289f42009-09-09 15:08:12 +00007672
Chris Lattnerdc226c22010-10-01 22:42:38 +00007673 // If there are modifiers and if we're allowed to parse them, go for it.
7674 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007675 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007676 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007677 default: Done = true; --Str; break;
7678 case '*':
7679 case '&': {
7680 // Both pointers and references can have their pointee types
7681 // qualified with an address space.
7682 char *End;
7683 unsigned AddrSpace = strtoul(Str, &End, 10);
7684 if (End != Str && AddrSpace != 0) {
7685 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7686 Str = End;
7687 }
7688 if (c == '*')
7689 Type = Context.getPointerType(Type);
7690 else
7691 Type = Context.getLValueReferenceType(Type);
7692 break;
7693 }
7694 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7695 case 'C':
7696 Type = Type.withConst();
7697 break;
7698 case 'D':
7699 Type = Context.getVolatileType(Type);
7700 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007701 case 'R':
7702 Type = Type.withRestrict();
7703 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007704 }
7705 }
Chris Lattner84733392010-10-01 07:13:18 +00007706
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007707 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007708 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007709
Chris Lattnerecd79c62009-06-14 00:45:47 +00007710 return Type;
7711}
7712
7713/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007714QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007715 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007716 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007717 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007718
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007719 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007720
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007721 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007722 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007723 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7724 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007725 if (Error != GE_None)
7726 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007727
7728 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7729
Chris Lattnerecd79c62009-06-14 00:45:47 +00007730 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007731 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007732 if (Error != GE_None)
7733 return QualType();
7734
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007735 // If this argument is required to be an IntegerConstantExpression and the
7736 // caller cares, fill in the bitmask we return.
7737 if (RequiresICE && IntegerConstantArgs)
7738 *IntegerConstantArgs |= 1 << ArgTypes.size();
7739
Chris Lattnerecd79c62009-06-14 00:45:47 +00007740 // Do array -> pointer decay. The builtin should use the decayed type.
7741 if (Ty->isArrayType())
7742 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007743
Chris Lattnerecd79c62009-06-14 00:45:47 +00007744 ArgTypes.push_back(Ty);
7745 }
7746
7747 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7748 "'.' should only occur at end of builtin type list!");
7749
Reid Kleckner78af0702013-08-27 23:08:25 +00007750 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007751 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7752
7753 bool Variadic = (TypeStr[0] == '.');
7754
7755 // We really shouldn't be making a no-proto type here, especially in C++.
7756 if (ArgTypes.empty() && Variadic)
7757 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007758
John McCalldb40c7f2010-12-14 08:05:40 +00007759 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007760 EPI.ExtInfo = EI;
7761 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007762
Jordan Rose5c382722013-03-08 21:51:21 +00007763 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007764}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007765
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007766static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
7767 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007768 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007769 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007770
Rafael Espindola3ae00052013-05-13 00:12:11 +00007771 GVALinkage External = GVA_StrongExternal;
7772 switch (FD->getTemplateSpecializationKind()) {
7773 case TSK_Undeclared:
7774 case TSK_ExplicitSpecialization:
7775 External = GVA_StrongExternal;
7776 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007777
Rafael Espindola3ae00052013-05-13 00:12:11 +00007778 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007779 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007780
David Majnemerc3d07332014-05-15 06:25:57 +00007781 // C++11 [temp.explicit]p10:
7782 // [ Note: The intent is that an inline function that is the subject of
7783 // an explicit instantiation declaration will still be implicitly
7784 // instantiated when used so that the body can be considered for
7785 // inlining, but that no out-of-line copy of the inline function would be
7786 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00007787 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00007788 return GVA_AvailableExternally;
7789
Rafael Espindola3ae00052013-05-13 00:12:11 +00007790 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007791 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007792 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007793 }
7794
7795 if (!FD->isInlined())
7796 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007797
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007798 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
7799 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007800 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007801 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
7802
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007803 // GNU or C99 inline semantics. Determine whether this symbol should be
7804 // externally visible.
7805 if (FD->isInlineDefinitionExternallyVisible())
7806 return External;
7807
7808 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00007809 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007810 }
7811
David Majnemer54e3ba52014-04-02 23:17:29 +00007812 // Functions specified with extern and inline in -fms-compatibility mode
7813 // forcibly get emitted. While the body of the function cannot be later
7814 // replaced, the function definition cannot be discarded.
7815 if (FD->getMostRecentDecl()->isMSExternInline())
7816 return GVA_StrongODR;
7817
David Majnemer27d69db2014-04-28 22:17:59 +00007818 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007819}
7820
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007821static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
7822 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
7823 // dllexport/dllimport on inline functions.
7824 if (D->hasAttr<DLLImportAttr>()) {
7825 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
7826 return GVA_AvailableExternally;
7827 } else if (D->hasAttr<DLLExportAttr>()) {
7828 if (L == GVA_DiscardableODR)
7829 return GVA_StrongODR;
7830 }
7831 return L;
7832}
7833
7834GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
7835 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
7836 FD);
7837}
7838
7839static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
7840 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007841 if (!VD->isExternallyVisible())
7842 return GVA_Internal;
7843
David Majnemer27d69db2014-04-28 22:17:59 +00007844 if (VD->isStaticLocal()) {
7845 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
7846 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
7847 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
7848 LexicalContext = LexicalContext->getLexicalParent();
7849
7850 // Let the static local variable inherit it's linkage from the nearest
7851 // enclosing function.
7852 if (LexicalContext)
7853 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007854 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00007855
7856 // GVA_StrongODR function linkage is stronger than what we need,
7857 // downgrade to GVA_DiscardableODR.
7858 // This allows us to discard the variable if we never end up needing it.
7859 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
7860 : StaticLocalLinkage;
7861 }
7862
Hans Wennborg56fc62b2014-07-17 20:25:23 +00007863 // MSVC treats in-class initialized static data members as definitions.
7864 // By giving them non-strong linkage, out-of-line definitions won't
7865 // cause link errors.
7866 if (Context.isMSStaticDataMemberInlineDefinition(VD))
7867 return GVA_DiscardableODR;
7868
Richard Smith8809a0c2013-09-27 20:14:12 +00007869 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007870 case TSK_Undeclared:
7871 case TSK_ExplicitSpecialization:
7872 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007873
Rafael Espindola3ae00052013-05-13 00:12:11 +00007874 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007875 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007876
David Majnemer27d69db2014-04-28 22:17:59 +00007877 case TSK_ExplicitInstantiationDeclaration:
7878 return GVA_AvailableExternally;
7879
Rafael Espindola3ae00052013-05-13 00:12:11 +00007880 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007881 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007882 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007883
7884 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007885}
7886
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007887GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7888 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
7889 VD);
7890}
7891
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007892bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007893 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7894 if (!VD->isFileVarDecl())
7895 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00007896 // Global named register variables (GNU extension) are never emitted.
7897 if (VD->getStorageClass() == SC_Register)
7898 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007899 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7900 // We never need to emit an uninstantiated function template.
7901 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7902 return false;
7903 } else
7904 return false;
7905
7906 // If this is a member of a class template, we do not need to emit it.
7907 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007908 return false;
7909
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007910 // Weak references don't produce any output by themselves.
7911 if (D->hasAttr<WeakRefAttr>())
7912 return false;
7913
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007914 // Aliases and used decls are required.
7915 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7916 return true;
7917
7918 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7919 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007920 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007921 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007922
7923 // Constructors and destructors are required.
7924 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7925 return true;
7926
John McCall6bd2a892013-01-25 22:31:03 +00007927 // The key function for a class is required. This rule only comes
7928 // into play when inline functions can be key functions, though.
7929 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7930 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7931 const CXXRecordDecl *RD = MD->getParent();
7932 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7933 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7934 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7935 return true;
7936 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007937 }
7938 }
7939
7940 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7941
7942 // static, static inline, always_inline, and extern inline functions can
7943 // always be deferred. Normal inline functions can be deferred in C99/C++.
7944 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00007945 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
7946 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007947 return false;
7948 return true;
7949 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007950
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007951 const VarDecl *VD = cast<VarDecl>(D);
7952 assert(VD->isFileVarDecl() && "Expected file scoped var");
7953
Hans Wennborg56fc62b2014-07-17 20:25:23 +00007954 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
7955 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007956 return false;
7957
Richard Smitha0e5e542012-11-12 21:38:00 +00007958 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007959 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00007960 if (L != GVA_Internal && L != GVA_AvailableExternally &&
7961 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00007962 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007963
Richard Smitha0e5e542012-11-12 21:38:00 +00007964 // Variables that have destruction with side-effects are required.
7965 if (VD->getType().isDestructedType())
7966 return true;
7967
7968 // Variables that have initialization with side-effects are required.
7969 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7970 return true;
7971
7972 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007973}
Charles Davis53c59df2010-08-16 03:33:14 +00007974
Reid Kleckner78af0702013-08-27 23:08:25 +00007975CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7976 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007977 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007978 if (IsCXXMethod)
7979 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007980
Reid Kleckner78af0702013-08-27 23:08:25 +00007981 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007982}
7983
Jay Foad39c79802011-01-12 09:06:06 +00007984bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007985 // Pass through to the C++ ABI object
7986 return ABI->isNearlyEmpty(RD);
7987}
7988
Reid Kleckner96f8f932014-02-05 17:27:08 +00007989VTableContextBase *ASTContext::getVTableContext() {
7990 if (!VTContext.get()) {
7991 if (Target->getCXXABI().isMicrosoft())
7992 VTContext.reset(new MicrosoftVTableContext(*this));
7993 else
7994 VTContext.reset(new ItaniumVTableContext(*this));
7995 }
7996 return VTContext.get();
7997}
7998
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007999MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008000 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008001 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008002 case TargetCXXABI::GenericItanium:
8003 case TargetCXXABI::GenericARM:
8004 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008005 case TargetCXXABI::iOS64:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008006 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008007 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008008 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008009 }
David Blaikie83d382b2011-09-23 05:06:16 +00008010 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008011}
8012
Charles Davis53c59df2010-08-16 03:33:14 +00008013CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008014
8015size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008016 return ASTRecordLayouts.getMemorySize() +
8017 llvm::capacity_in_bytes(ObjCLayouts) +
8018 llvm::capacity_in_bytes(KeyFunctions) +
8019 llvm::capacity_in_bytes(ObjCImpls) +
8020 llvm::capacity_in_bytes(BlockVarCopyInits) +
8021 llvm::capacity_in_bytes(DeclAttrs) +
8022 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8023 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8024 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8025 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8026 llvm::capacity_in_bytes(OverriddenMethods) +
8027 llvm::capacity_in_bytes(Types) +
8028 llvm::capacity_in_bytes(VariableArrayTypes) +
8029 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008030}
Ted Kremenek540017e2011-10-06 05:00:56 +00008031
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008032/// getIntTypeForBitwidth -
8033/// sets integer QualTy according to specified details:
8034/// bitwidth, signed/unsigned.
8035/// Returns empty type if there is no appropriate target types.
8036QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8037 unsigned Signed) const {
8038 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8039 CanQualType QualTy = getFromTargetType(Ty);
8040 if (!QualTy && DestWidth == 128)
8041 return Signed ? Int128Ty : UnsignedInt128Ty;
8042 return QualTy;
8043}
8044
8045/// getRealTypeForBitwidth -
8046/// sets floating point QualTy according to specified bitwidth.
8047/// Returns empty type if there is no appropriate target types.
8048QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8049 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8050 switch (Ty) {
8051 case TargetInfo::Float:
8052 return FloatTy;
8053 case TargetInfo::Double:
8054 return DoubleTy;
8055 case TargetInfo::LongDouble:
8056 return LongDoubleTy;
8057 case TargetInfo::NoFloat:
8058 return QualType();
8059 }
8060
8061 llvm_unreachable("Unhandled TargetInfo::RealType value");
8062}
8063
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008064void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8065 if (Number > 1)
8066 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008067}
8068
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008069unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8070 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8071 MangleNumbers.find(ND);
8072 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008073}
8074
David Majnemer2206bf52014-03-05 08:57:59 +00008075void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8076 if (Number > 1)
8077 StaticLocalNumbers[VD] = Number;
8078}
8079
8080unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8081 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8082 StaticLocalNumbers.find(VD);
8083 return I != StaticLocalNumbers.end() ? I->second : 1;
8084}
8085
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008086MangleNumberingContext &
8087ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008088 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8089 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8090 if (!MCtx)
8091 MCtx = createMangleNumberingContext();
8092 return *MCtx;
8093}
8094
8095MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8096 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008097}
8098
Ted Kremenek540017e2011-10-06 05:00:56 +00008099void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8100 ParamIndices[D] = index;
8101}
8102
8103unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8104 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8105 assert(I != ParamIndices.end() &&
8106 "ParmIndices lacks entry set by ParmVarDecl");
8107 return I->second;
8108}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008109
Richard Smithe6c01442013-06-05 00:46:14 +00008110APValue *
8111ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8112 bool MayCreate) {
8113 assert(E && E->getStorageDuration() == SD_Static &&
8114 "don't need to cache the computed value for this temporary");
8115 if (MayCreate)
8116 return &MaterializedTemporaryValues[E];
8117
8118 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8119 MaterializedTemporaryValues.find(E);
Craig Topper36250ad2014-05-12 05:36:57 +00008120 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
Richard Smithe6c01442013-06-05 00:46:14 +00008121}
8122
Fariborz Jahanian615de762013-05-28 17:37:39 +00008123bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8124 const llvm::Triple &T = getTargetInfo().getTriple();
8125 if (!T.isOSDarwin())
8126 return false;
8127
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008128 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8129 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8130 return false;
8131
Fariborz Jahanian615de762013-05-28 17:37:39 +00008132 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8133 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8134 uint64_t Size = sizeChars.getQuantity();
8135 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8136 unsigned Align = alignChars.getQuantity();
8137 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8138 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8139}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008140
8141namespace {
8142
8143 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8144 /// parents as defined by the \c RecursiveASTVisitor.
8145 ///
8146 /// Note that the relationship described here is purely in terms of AST
8147 /// traversal - there are other relationships (for example declaration context)
8148 /// in the AST that are better modeled by special matchers.
8149 ///
8150 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8151 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8152
8153 public:
8154 /// \brief Builds and returns the translation unit's parent map.
8155 ///
8156 /// The caller takes ownership of the returned \c ParentMap.
8157 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8158 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8159 Visitor.TraverseDecl(&TU);
8160 return Visitor.Parents;
8161 }
8162
8163 private:
8164 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8165
8166 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8167 }
8168
8169 bool shouldVisitTemplateInstantiations() const {
8170 return true;
8171 }
8172 bool shouldVisitImplicitCode() const {
8173 return true;
8174 }
8175 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8176 // are not triggered during data recursion.
8177 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8178 return false;
8179 }
8180
8181 template <typename T>
8182 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008183 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008184 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008185 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008186 // FIXME: Currently we add the same parent multiple times, but only
8187 // when no memoization data is available for the type.
8188 // For example when we visit all subexpressions of template
8189 // instantiations; this is suboptimal, but benign: the only way to
8190 // visit those is with hasAncestor / hasParent, and those do not create
8191 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008192 // The plan is to enable DynTypedNode to be storable in a map or hash
8193 // map. The main problem there is to implement hash functions /
8194 // comparison operators for all types that DynTypedNode supports that
8195 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008196 auto &NodeOrVector = (*Parents)[Node];
8197 if (NodeOrVector.isNull()) {
8198 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008199 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008200 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8201 auto *Node =
8202 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8203 auto *Vector = new ASTContext::ParentVector(1, *Node);
8204 NodeOrVector = Vector;
8205 delete Node;
8206 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008207 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008208
8209 auto *Vector =
8210 NodeOrVector.template get<ASTContext::ParentVector *>();
8211 // Skip duplicates for types that have memoization data.
8212 // We must check that the type has memoization data before calling
8213 // std::find() because DynTypedNode::operator== can't compare all
8214 // types.
8215 bool Found = ParentStack.back().getMemoizationData() &&
8216 std::find(Vector->begin(), Vector->end(),
8217 ParentStack.back()) != Vector->end();
8218 if (!Found)
8219 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008220 }
8221 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008222 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8223 bool Result = (this ->* traverse) (Node);
8224 ParentStack.pop_back();
8225 return Result;
8226 }
8227
8228 bool TraverseDecl(Decl *DeclNode) {
8229 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8230 }
8231
8232 bool TraverseStmt(Stmt *StmtNode) {
8233 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8234 }
8235
8236 ASTContext::ParentMap *Parents;
8237 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8238
8239 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8240 };
8241
8242} // end namespace
8243
8244ASTContext::ParentVector
8245ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8246 assert(Node.getMemoizationData() &&
8247 "Invariant broken: only nodes that support memoization may be "
8248 "used in the parent map.");
8249 if (!AllParents) {
8250 // We always need to run over the whole translation unit, as
8251 // hasAncestor can escape any subtree.
8252 AllParents.reset(
8253 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8254 }
8255 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8256 if (I == AllParents->end()) {
8257 return ParentVector();
8258 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008259 if (I->second.is<ast_type_traits::DynTypedNode *>()) {
8260 return ParentVector(1, *I->second.get<ast_type_traits::DynTypedNode *>());
8261 }
8262 const auto &Parents = *I->second.get<ParentVector *>();
8263 return ParentVector(Parents.begin(), Parents.end());
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008264}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008265
8266bool
8267ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8268 const ObjCMethodDecl *MethodImpl) {
8269 // No point trying to match an unavailable/deprecated mothod.
8270 if (MethodDecl->hasAttr<UnavailableAttr>()
8271 || MethodDecl->hasAttr<DeprecatedAttr>())
8272 return false;
8273 if (MethodDecl->getObjCDeclQualifier() !=
8274 MethodImpl->getObjCDeclQualifier())
8275 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008276 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008277 return false;
8278
8279 if (MethodDecl->param_size() != MethodImpl->param_size())
8280 return false;
8281
8282 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8283 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8284 EF = MethodDecl->param_end();
8285 IM != EM && IF != EF; ++IM, ++IF) {
8286 const ParmVarDecl *DeclVar = (*IF);
8287 const ParmVarDecl *ImplVar = (*IM);
8288 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8289 return false;
8290 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8291 return false;
8292 }
8293 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8294
8295}
Richard Smith053f6c62014-05-16 23:01:30 +00008296
8297// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8298// doesn't include ASTContext.h
8299template
8300clang::LazyGenerationalUpdatePtr<
8301 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8302clang::LazyGenerationalUpdatePtr<
8303 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8304 const clang::ASTContext &Ctx, Decl *Value);