blob: 1804c00647600100eeff738612a9ee4444854aaf [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
Alexey Samsonov0b15e342014-10-15 22:17:27 +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)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000728 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
729 DependentTemplateSpecializationTypes(this_()),
730 SubstTemplateTemplateParmPacks(this_()),
731 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
732 UInt128Decl(nullptr), Float128StubDecl(nullptr),
733 BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
734 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
735 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
736 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
737 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
738 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
739 NullTypeSourceInfo(QualType()), FirstLocalImport(), LastLocalImport(),
740 SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova0416102014-11-11 01:26:14 +0000741 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFile, SM)),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000742 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
743 Idents(idents), Selectors(sels), BuiltinInfo(builtins),
744 DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
745 Comments(SM), CommentsLoaded(false),
746 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000747 TUDecl = TranslationUnitDecl::Create(*this);
748}
749
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000750ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000751 ReleaseParentMapEntries();
752
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000753 // Release the DenseMaps associated with DeclContext objects.
754 // FIXME: Is this the ideal solution?
755 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000756
Manuel Klimeka7328992013-06-03 13:51:33 +0000757 // Call all of the deallocation functions on all of their targets.
758 for (DeallocationMap::const_iterator I = Deallocations.begin(),
759 E = Deallocations.end(); I != E; ++I)
760 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
761 (I->first)((I->second)[J]);
762
Ted Kremenek076baeb2010-06-08 23:00:58 +0000763 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000764 // because they can contain DenseMaps.
765 for (llvm::DenseMap<const ObjCContainerDecl*,
766 const ASTRecordLayout*>::iterator
767 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
768 // Increment in loop to prevent using deallocated memory.
769 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
770 R->Destroy(*this);
771
Ted Kremenek076baeb2010-06-08 23:00:58 +0000772 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
773 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
774 // Increment in loop to prevent using deallocated memory.
775 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
776 R->Destroy(*this);
777 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000778
779 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
780 AEnd = DeclAttrs.end();
781 A != AEnd; ++A)
782 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000783
Reid Kleckner588c9372014-02-19 23:44:52 +0000784 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000785}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000786
Manuel Klimek95403e62014-05-21 13:28:59 +0000787void ASTContext::ReleaseParentMapEntries() {
788 if (!AllParents) return;
789 for (const auto &Entry : *AllParents) {
790 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
791 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
792 } else {
793 assert(Entry.second.is<ParentVector *>());
794 delete Entry.second.get<ParentVector *>();
795 }
796 }
797}
798
Douglas Gregor1a809332010-05-23 18:26:36 +0000799void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000800 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000801}
802
Mike Stump11289f42009-09-09 15:08:12 +0000803void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000804ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
805 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000806}
807
Chris Lattner4eb445d2007-01-26 01:27:23 +0000808void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000809 llvm::errs() << "\n*** AST Context Stats:\n";
810 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000811
Douglas Gregora30d0462009-05-26 14:40:08 +0000812 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000813#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000814#define ABSTRACT_TYPE(Name, Parent)
815#include "clang/AST/TypeNodes.def"
816 0 // Extra
817 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000818
Chris Lattner4eb445d2007-01-26 01:27:23 +0000819 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
820 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000821 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000822 }
823
Douglas Gregora30d0462009-05-26 14:40:08 +0000824 unsigned Idx = 0;
825 unsigned TotalBytes = 0;
826#define TYPE(Name, Parent) \
827 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000828 llvm::errs() << " " << counts[Idx] << " " << #Name \
829 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000830 TotalBytes += counts[Idx] * sizeof(Name##Type); \
831 ++Idx;
832#define ABSTRACT_TYPE(Name, Parent)
833#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000834
Chandler Carruth3c147a72011-07-04 05:32:14 +0000835 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
836
Douglas Gregor7454c562010-07-02 20:37:36 +0000837 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000838 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
839 << NumImplicitDefaultConstructors
840 << " implicit default constructors created\n";
841 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
842 << NumImplicitCopyConstructors
843 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000844 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000845 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
846 << NumImplicitMoveConstructors
847 << " implicit move constructors created\n";
848 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
849 << NumImplicitCopyAssignmentOperators
850 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000851 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000852 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
853 << NumImplicitMoveAssignmentOperators
854 << " implicit move assignment operators created\n";
855 llvm::errs() << NumImplicitDestructorsDeclared << "/"
856 << NumImplicitDestructors
857 << " implicit destructors created\n";
858
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000859 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000860 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000861 ExternalSource->PrintStats();
862 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000863
Douglas Gregor5b11d492010-07-25 17:53:33 +0000864 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000865}
866
Alp Toker2dea15b2013-12-17 01:22:38 +0000867RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
868 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000869 SourceLocation Loc;
870 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000871 if (getLangOpts().CPlusPlus)
872 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
873 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000874 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000875 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
876 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000877 NewDecl->setImplicit();
878 return NewDecl;
879}
880
881TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
882 StringRef Name) const {
883 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
884 TypedefDecl *NewDecl = TypedefDecl::Create(
885 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
886 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
887 NewDecl->setImplicit();
888 return NewDecl;
889}
890
Douglas Gregor801c99d2011-08-12 06:49:56 +0000891TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000892 if (!Int128Decl)
893 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000894 return Int128Decl;
895}
896
897TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000898 if (!UInt128Decl)
899 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000900 return UInt128Decl;
901}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000902
Nico Webere1687c52013-06-20 21:44:55 +0000903TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000904 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000905 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000906 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000907
Nico Webere1687c52013-06-20 21:44:55 +0000908 return Float128StubDecl;
909}
910
John McCall48f2d582009-10-23 23:03:21 +0000911void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000912 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000913 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000914 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000915}
916
Douglas Gregore8bbc122011-09-02 00:18:52 +0000917void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
918 assert((!this->Target || this->Target == &Target) &&
919 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000920 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000921
Douglas Gregore8bbc122011-09-02 00:18:52 +0000922 this->Target = &Target;
923
924 ABI.reset(createCXXABI(Target));
925 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000926 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000927
Chris Lattner970e54e2006-11-12 00:37:36 +0000928 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000929 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000930
Chris Lattner970e54e2006-11-12 00:37:36 +0000931 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000932 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000933 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000934 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000935 InitBuiltinType(CharTy, BuiltinType::Char_S);
936 else
937 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000938 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000939 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
940 InitBuiltinType(ShortTy, BuiltinType::Short);
941 InitBuiltinType(IntTy, BuiltinType::Int);
942 InitBuiltinType(LongTy, BuiltinType::Long);
943 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000944
Chris Lattner970e54e2006-11-12 00:37:36 +0000945 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000946 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
947 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
948 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
949 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
950 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000951
Chris Lattner970e54e2006-11-12 00:37:36 +0000952 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000953 InitBuiltinType(FloatTy, BuiltinType::Float);
954 InitBuiltinType(DoubleTy, BuiltinType::Double);
955 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000956
Chris Lattnerf122cef2009-04-30 02:43:43 +0000957 // GNU extension, 128-bit integers.
958 InitBuiltinType(Int128Ty, BuiltinType::Int128);
959 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
960
Hans Wennborg0d81e012013-05-10 10:08:40 +0000961 // C++ 3.9.1p5
962 if (TargetInfo::isTypeSigned(Target.getWCharType()))
963 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
964 else // -fshort-wchar makes wchar_t be unsigned.
965 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
966 if (LangOpts.CPlusPlus && LangOpts.WChar)
967 WideCharTy = WCharTy;
968 else {
969 // C99 (or C++ using -fno-wchar).
970 WideCharTy = getFromTargetType(Target.getWCharType());
971 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000972
James Molloy36365542012-05-04 10:55:22 +0000973 WIntTy = getFromTargetType(Target.getWIntType());
974
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000975 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
976 InitBuiltinType(Char16Ty, BuiltinType::Char16);
977 else // C99
978 Char16Ty = getFromTargetType(Target.getChar16Type());
979
980 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
981 InitBuiltinType(Char32Ty, BuiltinType::Char32);
982 else // C99
983 Char32Ty = getFromTargetType(Target.getChar32Type());
984
Douglas Gregor4619e432008-12-05 23:32:09 +0000985 // Placeholder type for type-dependent expressions whose type is
986 // completely unknown. No code should ever check a type against
987 // DependentTy and users should never see it; however, it is here to
988 // help diagnose failures to properly check for type-dependent
989 // expressions.
990 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000991
John McCall36e7fe32010-10-12 00:20:44 +0000992 // Placeholder type for functions.
993 InitBuiltinType(OverloadTy, BuiltinType::Overload);
994
John McCall0009fcc2011-04-26 20:42:42 +0000995 // Placeholder type for bound members.
996 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
997
John McCall526ab472011-10-25 17:37:35 +0000998 // Placeholder type for pseudo-objects.
999 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1000
John McCall31996342011-04-07 08:22:57 +00001001 // "any" type; useful for debugger-like clients.
1002 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1003
John McCall8a6b59a2011-10-17 18:09:15 +00001004 // Placeholder type for unbridged ARC casts.
1005 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1006
Eli Friedman34866c72012-08-31 00:14:07 +00001007 // Placeholder type for builtin functions.
1008 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1009
Chris Lattner970e54e2006-11-12 00:37:36 +00001010 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001011 FloatComplexTy = getComplexType(FloatTy);
1012 DoubleComplexTy = getComplexType(DoubleTy);
1013 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001014
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001015 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001016 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1017 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001018 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001019
1020 if (LangOpts.OpenCL) {
1021 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1022 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1023 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1024 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1025 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1026 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001027
Guy Benyei61054192013-02-07 10:55:47 +00001028 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001029 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001030 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001031
1032 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001033 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1034 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001035
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001036 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001037
1038 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001039
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001040 // void * type
1041 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001042
1043 // nullptr type (C++0x 2.14.7)
1044 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001045
1046 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1047 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001048
1049 // Builtin type used to help define __builtin_va_list.
1050 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001051}
1052
David Blaikie9c902b52011-09-25 23:23:43 +00001053DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001054 return SourceMgr.getDiagnostics();
1055}
1056
Douglas Gregor561eceb2010-08-30 16:49:28 +00001057AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1058 AttrVec *&Result = DeclAttrs[D];
1059 if (!Result) {
1060 void *Mem = Allocate(sizeof(AttrVec));
1061 Result = new (Mem) AttrVec;
1062 }
1063
1064 return *Result;
1065}
1066
1067/// \brief Erase the attributes corresponding to the given declaration.
1068void ASTContext::eraseDeclAttrs(const Decl *D) {
1069 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1070 if (Pos != DeclAttrs.end()) {
1071 Pos->second->~AttrVec();
1072 DeclAttrs.erase(Pos);
1073 }
1074}
1075
Larisse Voufo39a1e502013-08-06 01:03:05 +00001076// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001077MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001078ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001079 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001080 return getTemplateOrSpecializationInfo(Var)
1081 .dyn_cast<MemberSpecializationInfo *>();
1082}
1083
1084ASTContext::TemplateOrSpecializationInfo
1085ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1086 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1087 TemplateOrInstantiation.find(Var);
1088 if (Pos == TemplateOrInstantiation.end())
1089 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001090
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001091 return Pos->second;
1092}
1093
Mike Stump11289f42009-09-09 15:08:12 +00001094void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001095ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001096 TemplateSpecializationKind TSK,
1097 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001098 assert(Inst->isStaticDataMember() && "Not a static data member");
1099 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001100 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1101 Tmpl, TSK, PointOfInstantiation));
1102}
1103
1104void
1105ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1106 TemplateOrSpecializationInfo TSI) {
1107 assert(!TemplateOrInstantiation[Inst] &&
1108 "Already noted what the variable was instantiated from");
1109 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001110}
1111
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001112FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1113 const FunctionDecl *FD){
1114 assert(FD && "Specialization is 0");
1115 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001116 = ClassScopeSpecializationPattern.find(FD);
1117 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001118 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001119
1120 return Pos->second;
1121}
1122
1123void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1124 FunctionDecl *Pattern) {
1125 assert(FD && "Specialization is 0");
1126 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001127 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001128}
1129
John McCalle61f2ba2009-11-18 02:36:19 +00001130NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001131ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001132 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001133 = InstantiatedFromUsingDecl.find(UUD);
1134 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001135 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001136
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001137 return Pos->second;
1138}
1139
1140void
John McCallb96ec562009-12-04 22:46:56 +00001141ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1142 assert((isa<UsingDecl>(Pattern) ||
1143 isa<UnresolvedUsingValueDecl>(Pattern) ||
1144 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1145 "pattern decl is not a using decl");
1146 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1147 InstantiatedFromUsingDecl[Inst] = Pattern;
1148}
1149
1150UsingShadowDecl *
1151ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1152 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1153 = InstantiatedFromUsingShadowDecl.find(Inst);
1154 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001155 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001156
1157 return Pos->second;
1158}
1159
1160void
1161ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1162 UsingShadowDecl *Pattern) {
1163 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1164 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001165}
1166
Anders Carlsson5da84842009-09-01 04:26:58 +00001167FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1168 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1169 = InstantiatedFromUnnamedFieldDecl.find(Field);
1170 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001171 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001172
Anders Carlsson5da84842009-09-01 04:26:58 +00001173 return Pos->second;
1174}
1175
1176void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1177 FieldDecl *Tmpl) {
1178 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1179 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1180 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1181 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001182
Anders Carlsson5da84842009-09-01 04:26:58 +00001183 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1184}
1185
Douglas Gregor832940b2010-03-02 23:58:15 +00001186ASTContext::overridden_cxx_method_iterator
1187ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1188 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001189 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001190 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001191 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001192
1193 return Pos->second.begin();
1194}
1195
1196ASTContext::overridden_cxx_method_iterator
1197ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1198 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001199 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001200 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001201 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001202
1203 return Pos->second.end();
1204}
1205
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001206unsigned
1207ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1208 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001209 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001210 if (Pos == OverriddenMethods.end())
1211 return 0;
1212
1213 return Pos->second.size();
1214}
1215
Douglas Gregor832940b2010-03-02 23:58:15 +00001216void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1217 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001218 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001219 OverriddenMethods[Method].push_back(Overridden);
1220}
1221
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001222void ASTContext::getOverriddenMethods(
1223 const NamedDecl *D,
1224 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001225 assert(D);
1226
1227 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001228 Overridden.append(overridden_methods_begin(CXXMethod),
1229 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001230 return;
1231 }
1232
1233 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1234 if (!Method)
1235 return;
1236
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001237 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1238 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001239 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001240}
1241
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001242void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1243 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1244 assert(!Import->isFromASTFile() && "Non-local import declaration");
1245 if (!FirstLocalImport) {
1246 FirstLocalImport = Import;
1247 LastLocalImport = Import;
1248 return;
1249 }
1250
1251 LastLocalImport->NextLocalImport = Import;
1252 LastLocalImport = Import;
1253}
1254
Chris Lattner53cfe802007-07-18 17:52:12 +00001255//===----------------------------------------------------------------------===//
1256// Type Sizing and Analysis
1257//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001258
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001259/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1260/// scalar floating point type.
1261const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001262 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001263 assert(BT && "Not a floating point type!");
1264 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001265 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001266 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001267 case BuiltinType::Float: return Target->getFloatFormat();
1268 case BuiltinType::Double: return Target->getDoubleFormat();
1269 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001270 }
1271}
1272
Rafael Espindola71eccb32013-08-08 19:53:46 +00001273CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001274 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001275
John McCall94268702010-10-08 18:24:19 +00001276 bool UseAlignAttrOnly = false;
1277 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1278 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001279
John McCall94268702010-10-08 18:24:19 +00001280 // __attribute__((aligned)) can increase or decrease alignment
1281 // *except* on a struct or struct member, where it only increases
1282 // alignment unless 'packed' is also specified.
1283 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001284 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001285 // ignore that possibility; Sema should diagnose it.
1286 if (isa<FieldDecl>(D)) {
1287 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1288 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1289 } else {
1290 UseAlignAttrOnly = true;
1291 }
1292 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001293 else if (isa<FieldDecl>(D))
1294 UseAlignAttrOnly =
1295 D->hasAttr<PackedAttr>() ||
1296 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001297
John McCall4e819612011-01-20 07:57:12 +00001298 // If we're using the align attribute only, just ignore everything
1299 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001300 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001301 // do nothing
1302
John McCall94268702010-10-08 18:24:19 +00001303 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001304 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001305 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001306 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001307 T = RT->getPointeeType();
1308 else
1309 T = getPointerType(RT->getPointeeType());
1310 }
Richard Smithf6d70302014-06-10 23:34:28 +00001311 QualType BaseT = getBaseElementType(T);
1312 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001313 // Adjust alignments of declarations with array type by the
1314 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001315 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001316 unsigned MinWidth = Target->getLargeArrayMinWidth();
1317 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001318 if (isa<VariableArrayType>(arrayType))
1319 Align = std::max(Align, Target->getLargeArrayAlign());
1320 else if (isa<ConstantArrayType>(arrayType) &&
1321 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1322 Align = std::max(Align, Target->getLargeArrayAlign());
1323 }
John McCall33ddac02011-01-19 10:06:00 +00001324 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001325 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001326 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1327 if (VD->hasGlobalStorage())
1328 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1329 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001330 }
John McCall4e819612011-01-20 07:57:12 +00001331
1332 // Fields can be subject to extra alignment constraints, like if
1333 // the field is packed, the struct is packed, or the struct has a
1334 // a max-field-alignment constraint (#pragma pack). So calculate
1335 // the actual alignment of the field within the struct, and then
1336 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001337 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1338 const RecordDecl *Parent = Field->getParent();
1339 // We can only produce a sensible answer if the record is valid.
1340 if (!Parent->isInvalidDecl()) {
1341 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001342
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001343 // Start with the record's overall alignment.
1344 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001345
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001346 // Use the GCD of that and the offset within the record.
1347 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1348 if (Offset > 0) {
1349 // Alignment is always a power of 2, so the GCD will be a power of 2,
1350 // which means we get to do this crazy thing instead of Euclid's.
1351 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1352 if (LowBitOfOffset < FieldAlign)
1353 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1354 }
1355
1356 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001357 }
Charles Davis3fc51072010-02-23 04:52:00 +00001358 }
Chris Lattner68061312009-01-24 21:53:27 +00001359 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001360
Ken Dyckcc56c542011-01-15 18:38:59 +00001361 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001362}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001363
John McCallf1249922012-08-21 04:10:00 +00001364// getTypeInfoDataSizeInChars - Return the size of a type, in
1365// chars. If the type is a record, its data size is returned. This is
1366// the size of the memcpy that's performed when assigning this type
1367// using a trivial copy/move assignment operator.
1368std::pair<CharUnits, CharUnits>
1369ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1370 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1371
1372 // In C++, objects can sometimes be allocated into the tail padding
1373 // of a base-class subobject. We decide whether that's possible
1374 // during class layout, so here we can just trust the layout results.
1375 if (getLangOpts().CPlusPlus) {
1376 if (const RecordType *RT = T->getAs<RecordType>()) {
1377 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1378 sizeAndAlign.first = layout.getDataSize();
1379 }
1380 }
1381
1382 return sizeAndAlign;
1383}
1384
Richard Trieu04d2d942013-05-14 21:59:17 +00001385/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1386/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1387std::pair<CharUnits, CharUnits>
1388static getConstantArrayInfoInChars(const ASTContext &Context,
1389 const ConstantArrayType *CAT) {
1390 std::pair<CharUnits, CharUnits> EltInfo =
1391 Context.getTypeInfoInChars(CAT->getElementType());
1392 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001393 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1394 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001395 "Overflow in array type char size evaluation");
1396 uint64_t Width = EltInfo.first.getQuantity() * Size;
1397 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001398 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1399 Context.getTargetInfo().getPointerWidth(0) == 64)
1400 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001401 return std::make_pair(CharUnits::fromQuantity(Width),
1402 CharUnits::fromQuantity(Align));
1403}
1404
John McCall87fe5d52010-05-20 01:18:31 +00001405std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001406ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001407 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1408 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001409 TypeInfo Info = getTypeInfo(T);
1410 return std::make_pair(toCharUnitsFromBits(Info.Width),
1411 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001412}
1413
1414std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001415ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001416 return getTypeInfoInChars(T.getTypePtr());
1417}
1418
David Majnemer34b57492014-07-30 01:30:47 +00001419bool ASTContext::isAlignmentRequired(const Type *T) const {
1420 return getTypeInfo(T).AlignIsRequired;
1421}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001422
David Majnemer34b57492014-07-30 01:30:47 +00001423bool ASTContext::isAlignmentRequired(QualType T) const {
1424 return isAlignmentRequired(T.getTypePtr());
1425}
1426
1427TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001428 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1429 if (I != MemoizedTypeInfo.end())
1430 return I->second;
1431
1432 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1433 TypeInfo TI = getTypeInfoImpl(T);
1434 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001435 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001436}
1437
1438/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1439/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001440///
1441/// FIXME: Pointers into different addr spaces could have different sizes and
1442/// alignment requirements: getPointerInfo should take an AddrSpace, this
1443/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001444TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1445 uint64_t Width = 0;
1446 unsigned Align = 8;
1447 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001448 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001449#define TYPE(Class, Base)
1450#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001451#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001452#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001453#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1454 case Type::Class: \
1455 assert(!T->isDependentType() && "should not see dependent types here"); \
1456 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001457#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001458 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001459
Chris Lattner355332d2007-07-13 22:27:08 +00001460 case Type::FunctionNoProto:
1461 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001462 // GCC extension: alignof(function) = 32 bits
1463 Width = 0;
1464 Align = 32;
1465 break;
1466
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001467 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001468 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001469 Width = 0;
1470 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1471 break;
1472
Steve Naroff5c131802007-08-30 01:06:46 +00001473 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001474 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001475
David Majnemer34b57492014-07-30 01:30:47 +00001476 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001477 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001478 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001479 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001480 Width = EltInfo.Width * Size;
1481 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001482 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1483 getTargetInfo().getPointerWidth(0) == 64)
1484 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001485 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001486 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001487 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001488 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001489 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001490 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1491 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001492 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001493 // If the alignment is not a power of 2, round up to the next power of 2.
1494 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001495 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001496 Align = llvm::NextPowerOf2(Align);
1497 Width = llvm::RoundUpToAlignment(Width, Align);
1498 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001499 // Adjust the alignment based on the target max.
1500 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1501 if (TargetVectorAlign && TargetVectorAlign < Align)
1502 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001503 break;
1504 }
Chris Lattner647fb222007-07-18 18:26:58 +00001505
Chris Lattner7570e9c2008-03-08 08:52:55 +00001506 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001507 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001508 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001509 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001510 // GCC extension: alignof(void) = 8 bits.
1511 Width = 0;
1512 Align = 8;
1513 break;
1514
Chris Lattner6a4f7452007-12-19 19:23:28 +00001515 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001516 Width = Target->getBoolWidth();
1517 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001518 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001519 case BuiltinType::Char_S:
1520 case BuiltinType::Char_U:
1521 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001522 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001523 Width = Target->getCharWidth();
1524 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001525 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001526 case BuiltinType::WChar_S:
1527 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001528 Width = Target->getWCharWidth();
1529 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001530 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001531 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001532 Width = Target->getChar16Width();
1533 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001534 break;
1535 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001536 Width = Target->getChar32Width();
1537 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001538 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001539 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001540 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001541 Width = Target->getShortWidth();
1542 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001543 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001544 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001545 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001546 Width = Target->getIntWidth();
1547 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001548 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001549 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001550 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001551 Width = Target->getLongWidth();
1552 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001553 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001554 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001555 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001556 Width = Target->getLongLongWidth();
1557 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001558 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001559 case BuiltinType::Int128:
1560 case BuiltinType::UInt128:
1561 Width = 128;
1562 Align = 128; // int128_t is 128-bit aligned on all targets.
1563 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001564 case BuiltinType::Half:
1565 Width = Target->getHalfWidth();
1566 Align = Target->getHalfAlign();
1567 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001568 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001569 Width = Target->getFloatWidth();
1570 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001571 break;
1572 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001573 Width = Target->getDoubleWidth();
1574 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001575 break;
1576 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001577 Width = Target->getLongDoubleWidth();
1578 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001579 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001580 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001581 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1582 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001583 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001584 case BuiltinType::ObjCId:
1585 case BuiltinType::ObjCClass:
1586 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001587 Width = Target->getPointerWidth(0);
1588 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001589 break;
Guy Benyei61054192013-02-07 10:55:47 +00001590 case BuiltinType::OCLSampler:
1591 // Samplers are modeled as integers.
1592 Width = Target->getIntWidth();
1593 Align = Target->getIntAlign();
1594 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001595 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001596 case BuiltinType::OCLImage1d:
1597 case BuiltinType::OCLImage1dArray:
1598 case BuiltinType::OCLImage1dBuffer:
1599 case BuiltinType::OCLImage2d:
1600 case BuiltinType::OCLImage2dArray:
1601 case BuiltinType::OCLImage3d:
1602 // Currently these types are pointers to opaque types.
1603 Width = Target->getPointerWidth(0);
1604 Align = Target->getPointerAlign(0);
1605 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001606 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001607 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001608 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001609 Width = Target->getPointerWidth(0);
1610 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001611 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001612 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001613 unsigned AS = getTargetAddressSpace(
1614 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001615 Width = Target->getPointerWidth(AS);
1616 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001617 break;
1618 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001619 case Type::LValueReference:
1620 case Type::RValueReference: {
1621 // alignof and sizeof should never enter this code path here, so we go
1622 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001623 unsigned AS = getTargetAddressSpace(
1624 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001625 Width = Target->getPointerWidth(AS);
1626 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001627 break;
1628 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001629 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001630 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001631 Width = Target->getPointerWidth(AS);
1632 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001633 break;
1634 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001635 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001636 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001637 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001638 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001639 }
Chris Lattner647fb222007-07-18 18:26:58 +00001640 case Type::Complex: {
1641 // Complex types have the same alignment as their elements, but twice the
1642 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001643 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1644 Width = EltInfo.Width * 2;
1645 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001646 break;
1647 }
John McCall8b07ec22010-05-15 11:32:37 +00001648 case Type::ObjCObject:
1649 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001650 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001651 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001652 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001653 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001654 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001655 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001656 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001657 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001658 break;
1659 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001660 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001661 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001662 const TagType *TT = cast<TagType>(T);
1663
1664 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001665 Width = 8;
1666 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001667 break;
1668 }
Mike Stump11289f42009-09-09 15:08:12 +00001669
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001670 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001671 return getTypeInfo(ET->getDecl()->getIntegerType());
1672
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001673 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001674 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001675 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001676 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001677 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001678 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001679
Chris Lattner63d2b362009-10-22 05:17:15 +00001680 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001681 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1682 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001683
Richard Smith30482bc2011-02-20 03:19:35 +00001684 case Type::Auto: {
1685 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001686 assert(!A->getDeducedType().isNull() &&
1687 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001688 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001689 }
1690
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001691 case Type::Paren:
1692 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1693
Douglas Gregoref462e62009-04-30 17:32:17 +00001694 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001695 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001696 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001697 // If the typedef has an aligned attribute on it, it overrides any computed
1698 // alignment we have. This violates the GCC documentation (which says that
1699 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001700 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001701 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001702 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001703 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001704 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001705 AlignIsRequired = Info.AlignIsRequired;
1706 }
David Majnemer34b57492014-07-30 01:30:47 +00001707 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001708 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001709 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001710
Abramo Bagnara6150c882010-05-11 21:36:43 +00001711 case Type::Elaborated:
1712 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001713
John McCall81904512011-01-06 01:58:22 +00001714 case Type::Attributed:
1715 return getTypeInfo(
1716 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1717
Eli Friedman0dfb8892011-10-06 23:00:33 +00001718 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001719 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001720 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1721 Width = Info.Width;
1722 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001723
1724 // If the size of the type doesn't exceed the platform's max
1725 // atomic promotion width, make the size and alignment more
1726 // favorable to atomic operations:
1727 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1728 // Round the size up to a power of 2.
1729 if (!llvm::isPowerOf2_64(Width))
1730 Width = llvm::NextPowerOf2(Width);
1731
1732 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001733 Align = static_cast<unsigned>(Width);
1734 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001735 }
1736
Douglas Gregoref462e62009-04-30 17:32:17 +00001737 }
Mike Stump11289f42009-09-09 15:08:12 +00001738
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001739 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001740 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001741}
1742
Ken Dyckcc56c542011-01-15 18:38:59 +00001743/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1744CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1745 return CharUnits::fromQuantity(BitSize / getCharWidth());
1746}
1747
Ken Dyckb0fcc592011-02-11 01:54:29 +00001748/// toBits - Convert a size in characters to a size in characters.
1749int64_t ASTContext::toBits(CharUnits CharSize) const {
1750 return CharSize.getQuantity() * getCharWidth();
1751}
1752
Ken Dyck8c89d592009-12-22 14:23:30 +00001753/// getTypeSizeInChars - Return the size of the specified type, in characters.
1754/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001755CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001756 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001757}
Jay Foad39c79802011-01-12 09:06:06 +00001758CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001759 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001760}
1761
Ken Dycka6046ab2010-01-26 17:25:18 +00001762/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001763/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001764CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001765 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001766}
Jay Foad39c79802011-01-12 09:06:06 +00001767CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001768 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001769}
1770
Chris Lattnera3402cd2009-01-27 18:08:34 +00001771/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1772/// type for the current target in bits. This can be different than the ABI
1773/// alignment in cases where it is beneficial for performance to overalign
1774/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001775unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001776 TypeInfo TI = getTypeInfo(T);
1777 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001778
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001779 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1780 return ABIAlign; // Never overalign on XCore.
1781
Eli Friedman7ab09572009-05-25 21:27:19 +00001782 // Double and long long should be naturally aligned if possible.
Richard Smithd7e1fe42014-06-10 23:43:44 +00001783 T = T->getBaseElementTypeUnsafe();
David Majnemer1d4db8f2014-02-24 23:43:27 +00001784 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001785 T = CT->getElementType().getTypePtr();
1786 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001787 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1788 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001789 // Don't increase the alignment if an alignment attribute was specified on a
1790 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001791 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001792 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001793
Chris Lattnera3402cd2009-01-27 18:08:34 +00001794 return ABIAlign;
1795}
1796
Ulrich Weigandfa806422013-05-06 16:23:57 +00001797/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1798/// to a global variable of the specified type.
1799unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1800 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1801}
1802
1803/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1804/// should be given to a global variable of the specified type.
1805CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1806 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1807}
1808
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001809/// DeepCollectObjCIvars -
1810/// This routine first collects all declared, but not synthesized, ivars in
1811/// super class and then collects all ivars, including those synthesized for
1812/// current class. This routine is used for implementation of current class
1813/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001814///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001815void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1816 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001817 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001818 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1819 DeepCollectObjCIvars(SuperClass, false, Ivars);
1820 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001821 for (const auto *I : OI->ivars())
1822 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001823 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001824 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001825 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001826 Iv= Iv->getNextIvar())
1827 Ivars.push_back(Iv);
1828 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001829}
1830
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001831/// CollectInheritedProtocols - Collect all protocols in current class and
1832/// those inherited by it.
1833void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001834 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001835 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001836 // We can use protocol_iterator here instead of
1837 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001838 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001839 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001840 for (auto *P : Proto->protocols()) {
1841 Protocols.insert(P->getCanonicalDecl());
1842 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001843 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001844 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001845
1846 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001847 for (const auto *Cat : OI->visible_categories())
1848 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001849
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001850 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1851 while (SD) {
1852 CollectInheritedProtocols(SD, Protocols);
1853 SD = SD->getSuperClass();
1854 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001855 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001856 for (auto *Proto : OC->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001857 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001858 for (const auto *P : Proto->protocols())
1859 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001860 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001861 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001862 for (auto *Proto : OP->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001863 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001864 for (const auto *P : Proto->protocols())
1865 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001866 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001867 }
1868}
1869
Jay Foad39c79802011-01-12 09:06:06 +00001870unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001871 unsigned count = 0;
1872 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001873 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001874 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001875
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001876 // Count ivar defined in this class's implementation. This
1877 // includes synthesized ivars.
1878 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001879 count += ImplDecl->ivar_size();
1880
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001881 return count;
1882}
1883
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001884bool ASTContext::isSentinelNullExpr(const Expr *E) {
1885 if (!E)
1886 return false;
1887
1888 // nullptr_t is always treated as null.
1889 if (E->getType()->isNullPtrType()) return true;
1890
1891 if (E->getType()->isAnyPointerType() &&
1892 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1893 Expr::NPC_ValueDependentIsNull))
1894 return true;
1895
1896 // Unfortunately, __null has type 'int'.
1897 if (isa<GNUNullExpr>(E)) return true;
1898
1899 return false;
1900}
1901
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001902/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1903ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1904 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1905 I = ObjCImpls.find(D);
1906 if (I != ObjCImpls.end())
1907 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001908 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001909}
1910/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1911ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1912 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1913 I = ObjCImpls.find(D);
1914 if (I != ObjCImpls.end())
1915 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001916 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001917}
1918
1919/// \brief Set the implementation of ObjCInterfaceDecl.
1920void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1921 ObjCImplementationDecl *ImplD) {
1922 assert(IFaceD && ImplD && "Passed null params");
1923 ObjCImpls[IFaceD] = ImplD;
1924}
1925/// \brief Set the implementation of ObjCCategoryDecl.
1926void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1927 ObjCCategoryImplDecl *ImplD) {
1928 assert(CatD && ImplD && "Passed null params");
1929 ObjCImpls[CatD] = ImplD;
1930}
1931
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001932const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1933 const NamedDecl *ND) const {
1934 if (const ObjCInterfaceDecl *ID =
1935 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001936 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001937 if (const ObjCCategoryDecl *CD =
1938 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001939 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001940 if (const ObjCImplDecl *IMD =
1941 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001942 return IMD->getClassInterface();
1943
Craig Topper36250ad2014-05-12 05:36:57 +00001944 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001945}
1946
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001947/// \brief Get the copy initialization expression of VarDecl,or NULL if
1948/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001949Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001950 assert(VD && "Passed null params");
1951 assert(VD->hasAttr<BlocksAttr>() &&
1952 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001953 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001954 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00001955 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001956}
1957
1958/// \brief Set the copy inialization expression of a block var decl.
1959void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1960 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001961 assert(VD->hasAttr<BlocksAttr>() &&
1962 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001963 BlockVarCopyInits[VD] = Init;
1964}
1965
John McCallbcd03502009-12-07 02:54:59 +00001966TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001967 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001968 if (!DataSize)
1969 DataSize = TypeLoc::getFullDataSizeForType(T);
1970 else
1971 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001972 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001973
John McCallbcd03502009-12-07 02:54:59 +00001974 TypeSourceInfo *TInfo =
1975 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1976 new (TInfo) TypeSourceInfo(T);
1977 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001978}
1979
John McCallbcd03502009-12-07 02:54:59 +00001980TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001981 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001982 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001983 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001984 return DI;
1985}
1986
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001987const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001988ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00001989 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001990}
1991
1992const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001993ASTContext::getASTObjCImplementationLayout(
1994 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001995 return getObjCLayout(D->getClassInterface(), D);
1996}
1997
Chris Lattner983a8bb2007-07-13 22:13:22 +00001998//===----------------------------------------------------------------------===//
1999// Type creation/memoization methods
2000//===----------------------------------------------------------------------===//
2001
Jay Foad39c79802011-01-12 09:06:06 +00002002QualType
John McCall33ddac02011-01-19 10:06:00 +00002003ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2004 unsigned fastQuals = quals.getFastQualifiers();
2005 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002006
2007 // Check if we've already instantiated this type.
2008 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002009 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002010 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002011 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2012 assert(eq->getQualifiers() == quals);
2013 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002014 }
2015
John McCall33ddac02011-01-19 10:06:00 +00002016 // If the base type is not canonical, make the appropriate canonical type.
2017 QualType canon;
2018 if (!baseType->isCanonicalUnqualified()) {
2019 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002020 canonSplit.Quals.addConsistentQualifiers(quals);
2021 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002022
2023 // Re-find the insert position.
2024 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2025 }
2026
2027 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2028 ExtQualNodes.InsertNode(eq, insertPos);
2029 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002030}
2031
Jay Foad39c79802011-01-12 09:06:06 +00002032QualType
2033ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002034 QualType CanT = getCanonicalType(T);
2035 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002036 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002037
John McCall8ccfcb52009-09-24 19:53:00 +00002038 // If we are composing extended qualifiers together, merge together
2039 // into one ExtQuals node.
2040 QualifierCollector Quals;
2041 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002042
John McCall8ccfcb52009-09-24 19:53:00 +00002043 // If this type already has an address space specified, it cannot get
2044 // another one.
2045 assert(!Quals.hasAddressSpace() &&
2046 "Type cannot be in multiple addr spaces!");
2047 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002048
John McCall8ccfcb52009-09-24 19:53:00 +00002049 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002050}
2051
Chris Lattnerd60183d2009-02-18 22:53:11 +00002052QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002053 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002054 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002055 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002056 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002057
John McCall53fa7142010-12-24 02:08:15 +00002058 if (const PointerType *ptr = T->getAs<PointerType>()) {
2059 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002060 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002061 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2062 return getPointerType(ResultType);
2063 }
2064 }
Mike Stump11289f42009-09-09 15:08:12 +00002065
John McCall8ccfcb52009-09-24 19:53:00 +00002066 // If we are composing extended qualifiers together, merge together
2067 // into one ExtQuals node.
2068 QualifierCollector Quals;
2069 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002070
John McCall8ccfcb52009-09-24 19:53:00 +00002071 // If this type already has an ObjCGC specified, it cannot get
2072 // another one.
2073 assert(!Quals.hasObjCGCAttr() &&
2074 "Type cannot have multiple ObjCGCs!");
2075 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002076
John McCall8ccfcb52009-09-24 19:53:00 +00002077 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002078}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002079
John McCall4f5019e2010-12-19 02:44:49 +00002080const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2081 FunctionType::ExtInfo Info) {
2082 if (T->getExtInfo() == Info)
2083 return T;
2084
2085 QualType Result;
2086 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002087 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002088 } else {
2089 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2090 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2091 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002092 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002093 }
2094
2095 return cast<FunctionType>(Result.getTypePtr());
2096}
2097
Richard Smith2a7d4812013-05-04 07:00:32 +00002098void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2099 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002100 FD = FD->getMostRecentDecl();
2101 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002102 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2103 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002104 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002105 if (FunctionDecl *Next = FD->getPreviousDecl())
2106 FD = Next;
2107 else
2108 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002109 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002110 if (ASTMutationListener *L = getASTMutationListener())
2111 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002112}
2113
Richard Smith0b3a4622014-11-13 20:01:57 +00002114/// Get a function type and produce the equivalent function type with the
2115/// specified exception specification. Type sugar that can be present on a
2116/// declaration of a function with an exception specification is permitted
2117/// and preserved. Other type sugar (for instance, typedefs) is not.
2118static QualType getFunctionTypeWithExceptionSpec(
2119 ASTContext &Context, QualType Orig,
2120 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2121 // Might have some parens.
2122 if (auto *PT = dyn_cast<ParenType>(Orig))
2123 return Context.getParenType(
2124 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2125
2126 // Might have a calling-convention attribute.
2127 if (auto *AT = dyn_cast<AttributedType>(Orig))
2128 return Context.getAttributedType(
2129 AT->getAttrKind(),
2130 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2131 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2132 ESI));
2133
2134 // Anything else must be a function type. Rebuild it with the new exception
2135 // specification.
2136 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2137 return Context.getFunctionType(
2138 Proto->getReturnType(), Proto->getParamTypes(),
2139 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2140}
2141
2142void ASTContext::adjustExceptionSpec(
2143 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2144 bool AsWritten) {
2145 // Update the type.
2146 QualType Updated =
2147 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2148 FD->setType(Updated);
2149
2150 if (!AsWritten)
2151 return;
2152
2153 // Update the type in the type source information too.
2154 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2155 // If the type and the type-as-written differ, we may need to update
2156 // the type-as-written too.
2157 if (TSInfo->getType() != FD->getType())
2158 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2159
2160 // FIXME: When we get proper type location information for exceptions,
2161 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2162 // up the TypeSourceInfo;
2163 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2164 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2165 "TypeLoc size mismatch from updating exception specification");
2166 TSInfo->overrideType(Updated);
2167 }
2168}
2169
Chris Lattnerc6395932007-06-22 20:56:16 +00002170/// getComplexType - Return the uniqued reference to the type for a complex
2171/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002172QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002173 // Unique pointers, to guarantee there is only one pointer of a particular
2174 // structure.
2175 llvm::FoldingSetNodeID ID;
2176 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002177
Craig Topper36250ad2014-05-12 05:36:57 +00002178 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002179 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2180 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002181
Chris Lattnerc6395932007-06-22 20:56:16 +00002182 // If the pointee type isn't canonical, this won't be a canonical type either,
2183 // so fill in the canonical type field.
2184 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002185 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002186 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002187
Chris Lattnerc6395932007-06-22 20:56:16 +00002188 // Get the new insert position for the node we care about.
2189 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002190 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002191 }
John McCall90d1c2d2009-09-24 23:30:46 +00002192 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002193 Types.push_back(New);
2194 ComplexTypes.InsertNode(New, InsertPos);
2195 return QualType(New, 0);
2196}
2197
Chris Lattner970e54e2006-11-12 00:37:36 +00002198/// getPointerType - Return the uniqued reference to the type for a pointer to
2199/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002200QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002201 // Unique pointers, to guarantee there is only one pointer of a particular
2202 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002203 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002204 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002205
Craig Topper36250ad2014-05-12 05:36:57 +00002206 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002207 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002208 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002209
Chris Lattner7ccecb92006-11-12 08:50:50 +00002210 // If the pointee type isn't canonical, this won't be a canonical type either,
2211 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002212 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002213 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002214 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002215
Bob Wilsonc8541f22013-03-15 17:12:43 +00002216 // Get the new insert position for the node we care about.
2217 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002218 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002219 }
John McCall90d1c2d2009-09-24 23:30:46 +00002220 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002221 Types.push_back(New);
2222 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002223 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002224}
2225
Reid Kleckner0503a872013-12-05 01:23:43 +00002226QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2227 llvm::FoldingSetNodeID ID;
2228 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002229 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002230 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2231 if (AT)
2232 return QualType(AT, 0);
2233
2234 QualType Canonical = getCanonicalType(New);
2235
2236 // Get the new insert position for the node we care about.
2237 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002238 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002239
2240 AT = new (*this, TypeAlignment)
2241 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2242 Types.push_back(AT);
2243 AdjustedTypes.InsertNode(AT, InsertPos);
2244 return QualType(AT, 0);
2245}
2246
Reid Kleckner8a365022013-06-24 17:51:48 +00002247QualType ASTContext::getDecayedType(QualType T) const {
2248 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2249
Reid Kleckner8a365022013-06-24 17:51:48 +00002250 QualType Decayed;
2251
2252 // C99 6.7.5.3p7:
2253 // A declaration of a parameter as "array of type" shall be
2254 // adjusted to "qualified pointer to type", where the type
2255 // qualifiers (if any) are those specified within the [ and ] of
2256 // the array type derivation.
2257 if (T->isArrayType())
2258 Decayed = getArrayDecayedType(T);
2259
2260 // C99 6.7.5.3p8:
2261 // A declaration of a parameter as "function returning type"
2262 // shall be adjusted to "pointer to function returning type", as
2263 // in 6.3.2.1.
2264 if (T->isFunctionType())
2265 Decayed = getPointerType(T);
2266
Reid Kleckner0503a872013-12-05 01:23:43 +00002267 llvm::FoldingSetNodeID ID;
2268 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002269 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002270 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2271 if (AT)
2272 return QualType(AT, 0);
2273
Reid Kleckner8a365022013-06-24 17:51:48 +00002274 QualType Canonical = getCanonicalType(Decayed);
2275
2276 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002277 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002278 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002279
Reid Kleckner0503a872013-12-05 01:23:43 +00002280 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2281 Types.push_back(AT);
2282 AdjustedTypes.InsertNode(AT, InsertPos);
2283 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002284}
2285
Mike Stump11289f42009-09-09 15:08:12 +00002286/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002287/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002288QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002289 assert(T->isFunctionType() && "block of function types only");
2290 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002291 // structure.
2292 llvm::FoldingSetNodeID ID;
2293 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002294
Craig Topper36250ad2014-05-12 05:36:57 +00002295 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002296 if (BlockPointerType *PT =
2297 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2298 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002299
2300 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002301 // type either so fill in the canonical type field.
2302 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002303 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002304 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002305
Steve Naroffec33ed92008-08-27 16:04:49 +00002306 // Get the new insert position for the node we care about.
2307 BlockPointerType *NewIP =
2308 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002309 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002310 }
John McCall90d1c2d2009-09-24 23:30:46 +00002311 BlockPointerType *New
2312 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002313 Types.push_back(New);
2314 BlockPointerTypes.InsertNode(New, InsertPos);
2315 return QualType(New, 0);
2316}
2317
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002318/// getLValueReferenceType - Return the uniqued reference to the type for an
2319/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002320QualType
2321ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002322 assert(getCanonicalType(T) != OverloadTy &&
2323 "Unresolved overloaded function type");
2324
Bill Wendling3708c182007-05-27 10:15:43 +00002325 // Unique pointers, to guarantee there is only one pointer of a particular
2326 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002327 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002328 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002329
Craig Topper36250ad2014-05-12 05:36:57 +00002330 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002331 if (LValueReferenceType *RT =
2332 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002333 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002334
John McCallfc93cf92009-10-22 22:37:11 +00002335 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2336
Bill Wendling3708c182007-05-27 10:15:43 +00002337 // If the referencee type isn't canonical, this won't be a canonical type
2338 // either, so fill in the canonical type field.
2339 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002340 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2341 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2342 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002343
Bill Wendling3708c182007-05-27 10:15:43 +00002344 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002345 LValueReferenceType *NewIP =
2346 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002347 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002348 }
2349
John McCall90d1c2d2009-09-24 23:30:46 +00002350 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002351 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2352 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002353 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002354 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002355
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002356 return QualType(New, 0);
2357}
2358
2359/// getRValueReferenceType - Return the uniqued reference to the type for an
2360/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002361QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002362 // Unique pointers, to guarantee there is only one pointer of a particular
2363 // structure.
2364 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002365 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002366
Craig Topper36250ad2014-05-12 05:36:57 +00002367 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002368 if (RValueReferenceType *RT =
2369 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2370 return QualType(RT, 0);
2371
John McCallfc93cf92009-10-22 22:37:11 +00002372 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2373
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002374 // If the referencee type isn't canonical, this won't be a canonical type
2375 // either, so fill in the canonical type field.
2376 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002377 if (InnerRef || !T.isCanonical()) {
2378 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2379 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002380
2381 // Get the new insert position for the node we care about.
2382 RValueReferenceType *NewIP =
2383 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002384 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002385 }
2386
John McCall90d1c2d2009-09-24 23:30:46 +00002387 RValueReferenceType *New
2388 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002389 Types.push_back(New);
2390 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002391 return QualType(New, 0);
2392}
2393
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002394/// getMemberPointerType - Return the uniqued reference to the type for a
2395/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002396QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002397 // Unique pointers, to guarantee there is only one pointer of a particular
2398 // structure.
2399 llvm::FoldingSetNodeID ID;
2400 MemberPointerType::Profile(ID, T, Cls);
2401
Craig Topper36250ad2014-05-12 05:36:57 +00002402 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002403 if (MemberPointerType *PT =
2404 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2405 return QualType(PT, 0);
2406
2407 // If the pointee or class type isn't canonical, this won't be a canonical
2408 // type either, so fill in the canonical type field.
2409 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002410 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002411 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2412
2413 // Get the new insert position for the node we care about.
2414 MemberPointerType *NewIP =
2415 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002416 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002417 }
John McCall90d1c2d2009-09-24 23:30:46 +00002418 MemberPointerType *New
2419 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002420 Types.push_back(New);
2421 MemberPointerTypes.InsertNode(New, InsertPos);
2422 return QualType(New, 0);
2423}
2424
Mike Stump11289f42009-09-09 15:08:12 +00002425/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002426/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002427QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002428 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002429 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002430 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002431 assert((EltTy->isDependentType() ||
2432 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002433 "Constant array of VLAs is illegal!");
2434
Chris Lattnere2df3f92009-05-13 04:12:56 +00002435 // Convert the array size into a canonical width matching the pointer size for
2436 // the target.
2437 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002438 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002439 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002440
Chris Lattner23b7eb62007-06-15 23:05:46 +00002441 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002442 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002443
Craig Topper36250ad2014-05-12 05:36:57 +00002444 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002445 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002446 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002447 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002448
John McCall33ddac02011-01-19 10:06:00 +00002449 // If the element type isn't canonical or has qualifiers, this won't
2450 // be a canonical type either, so fill in the canonical type field.
2451 QualType Canon;
2452 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2453 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002454 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002455 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002456 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002457
Chris Lattner36f8e652007-01-27 08:31:04 +00002458 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002459 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002460 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002461 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002462 }
Mike Stump11289f42009-09-09 15:08:12 +00002463
John McCall90d1c2d2009-09-24 23:30:46 +00002464 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002465 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002466 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002467 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002468 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002469}
2470
John McCall06549462011-01-18 08:40:38 +00002471/// getVariableArrayDecayedType - Turns the given type, which may be
2472/// variably-modified, into the corresponding type with all the known
2473/// sizes replaced with [*].
2474QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2475 // Vastly most common case.
2476 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002477
John McCall06549462011-01-18 08:40:38 +00002478 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002479
John McCall06549462011-01-18 08:40:38 +00002480 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002481 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002482 switch (ty->getTypeClass()) {
2483#define TYPE(Class, Base)
2484#define ABSTRACT_TYPE(Class, Base)
2485#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2486#include "clang/AST/TypeNodes.def"
2487 llvm_unreachable("didn't desugar past all non-canonical types?");
2488
2489 // These types should never be variably-modified.
2490 case Type::Builtin:
2491 case Type::Complex:
2492 case Type::Vector:
2493 case Type::ExtVector:
2494 case Type::DependentSizedExtVector:
2495 case Type::ObjCObject:
2496 case Type::ObjCInterface:
2497 case Type::ObjCObjectPointer:
2498 case Type::Record:
2499 case Type::Enum:
2500 case Type::UnresolvedUsing:
2501 case Type::TypeOfExpr:
2502 case Type::TypeOf:
2503 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002504 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002505 case Type::DependentName:
2506 case Type::InjectedClassName:
2507 case Type::TemplateSpecialization:
2508 case Type::DependentTemplateSpecialization:
2509 case Type::TemplateTypeParm:
2510 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002511 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002512 case Type::PackExpansion:
2513 llvm_unreachable("type should never be variably-modified");
2514
2515 // These types can be variably-modified but should never need to
2516 // further decay.
2517 case Type::FunctionNoProto:
2518 case Type::FunctionProto:
2519 case Type::BlockPointer:
2520 case Type::MemberPointer:
2521 return type;
2522
2523 // These types can be variably-modified. All these modifications
2524 // preserve structure except as noted by comments.
2525 // TODO: if we ever care about optimizing VLAs, there are no-op
2526 // optimizations available here.
2527 case Type::Pointer:
2528 result = getPointerType(getVariableArrayDecayedType(
2529 cast<PointerType>(ty)->getPointeeType()));
2530 break;
2531
2532 case Type::LValueReference: {
2533 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2534 result = getLValueReferenceType(
2535 getVariableArrayDecayedType(lv->getPointeeType()),
2536 lv->isSpelledAsLValue());
2537 break;
2538 }
2539
2540 case Type::RValueReference: {
2541 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2542 result = getRValueReferenceType(
2543 getVariableArrayDecayedType(lv->getPointeeType()));
2544 break;
2545 }
2546
Eli Friedman0dfb8892011-10-06 23:00:33 +00002547 case Type::Atomic: {
2548 const AtomicType *at = cast<AtomicType>(ty);
2549 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2550 break;
2551 }
2552
John McCall06549462011-01-18 08:40:38 +00002553 case Type::ConstantArray: {
2554 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2555 result = getConstantArrayType(
2556 getVariableArrayDecayedType(cat->getElementType()),
2557 cat->getSize(),
2558 cat->getSizeModifier(),
2559 cat->getIndexTypeCVRQualifiers());
2560 break;
2561 }
2562
2563 case Type::DependentSizedArray: {
2564 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2565 result = getDependentSizedArrayType(
2566 getVariableArrayDecayedType(dat->getElementType()),
2567 dat->getSizeExpr(),
2568 dat->getSizeModifier(),
2569 dat->getIndexTypeCVRQualifiers(),
2570 dat->getBracketsRange());
2571 break;
2572 }
2573
2574 // Turn incomplete types into [*] types.
2575 case Type::IncompleteArray: {
2576 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2577 result = getVariableArrayType(
2578 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002579 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002580 ArrayType::Normal,
2581 iat->getIndexTypeCVRQualifiers(),
2582 SourceRange());
2583 break;
2584 }
2585
2586 // Turn VLA types into [*] types.
2587 case Type::VariableArray: {
2588 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2589 result = getVariableArrayType(
2590 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002591 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002592 ArrayType::Star,
2593 vat->getIndexTypeCVRQualifiers(),
2594 vat->getBracketsRange());
2595 break;
2596 }
2597 }
2598
2599 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002600 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002601}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002602
Steve Naroffcadebd02007-08-30 18:14:25 +00002603/// getVariableArrayType - Returns a non-unique reference to the type for a
2604/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002605QualType ASTContext::getVariableArrayType(QualType EltTy,
2606 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002607 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002608 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002609 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002610 // Since we don't unique expressions, it isn't possible to unique VLA's
2611 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002612 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002613
John McCall33ddac02011-01-19 10:06:00 +00002614 // Be sure to pull qualifiers off the element type.
2615 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2616 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002617 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002618 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002619 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002620 }
2621
John McCall90d1c2d2009-09-24 23:30:46 +00002622 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002623 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002624
2625 VariableArrayTypes.push_back(New);
2626 Types.push_back(New);
2627 return QualType(New, 0);
2628}
2629
Douglas Gregor4619e432008-12-05 23:32:09 +00002630/// getDependentSizedArrayType - Returns a non-unique reference to
2631/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002632/// type.
John McCall33ddac02011-01-19 10:06:00 +00002633QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2634 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002635 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002636 unsigned elementTypeQuals,
2637 SourceRange brackets) const {
2638 assert((!numElements || numElements->isTypeDependent() ||
2639 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002640 "Size must be type- or value-dependent!");
2641
John McCall33ddac02011-01-19 10:06:00 +00002642 // Dependently-sized array types that do not have a specified number
2643 // of elements will have their sizes deduced from a dependent
2644 // initializer. We do no canonicalization here at all, which is okay
2645 // because they can't be used in most locations.
2646 if (!numElements) {
2647 DependentSizedArrayType *newType
2648 = new (*this, TypeAlignment)
2649 DependentSizedArrayType(*this, elementType, QualType(),
2650 numElements, ASM, elementTypeQuals,
2651 brackets);
2652 Types.push_back(newType);
2653 return QualType(newType, 0);
2654 }
2655
2656 // Otherwise, we actually build a new type every time, but we
2657 // also build a canonical type.
2658
2659 SplitQualType canonElementType = getCanonicalType(elementType).split();
2660
Craig Topper36250ad2014-05-12 05:36:57 +00002661 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002662 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002663 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002664 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002665 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002666
John McCall33ddac02011-01-19 10:06:00 +00002667 // Look for an existing type with these properties.
2668 DependentSizedArrayType *canonTy =
2669 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002670
John McCall33ddac02011-01-19 10:06:00 +00002671 // If we don't have one, build one.
2672 if (!canonTy) {
2673 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002674 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002675 QualType(), numElements, ASM, elementTypeQuals,
2676 brackets);
2677 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2678 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002679 }
2680
John McCall33ddac02011-01-19 10:06:00 +00002681 // Apply qualifiers from the element type to the array.
2682 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002683 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002684
John McCall33ddac02011-01-19 10:06:00 +00002685 // If we didn't need extra canonicalization for the element type,
2686 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002687 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002688 return canon;
2689
2690 // Otherwise, we need to build a type which follows the spelling
2691 // of the element type.
2692 DependentSizedArrayType *sugaredType
2693 = new (*this, TypeAlignment)
2694 DependentSizedArrayType(*this, elementType, canon, numElements,
2695 ASM, elementTypeQuals, brackets);
2696 Types.push_back(sugaredType);
2697 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002698}
2699
John McCall33ddac02011-01-19 10:06:00 +00002700QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002701 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002702 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002703 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002704 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002705
Craig Topper36250ad2014-05-12 05:36:57 +00002706 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002707 if (IncompleteArrayType *iat =
2708 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2709 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002710
2711 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002712 // either, so fill in the canonical type field. We also have to pull
2713 // qualifiers off the element type.
2714 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002715
John McCall33ddac02011-01-19 10:06:00 +00002716 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2717 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002718 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002719 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002720 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002721
2722 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002723 IncompleteArrayType *existing =
2724 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2725 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002726 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002727
John McCall33ddac02011-01-19 10:06:00 +00002728 IncompleteArrayType *newType = new (*this, TypeAlignment)
2729 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002730
John McCall33ddac02011-01-19 10:06:00 +00002731 IncompleteArrayTypes.InsertNode(newType, insertPos);
2732 Types.push_back(newType);
2733 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002734}
2735
Steve Naroff91fcddb2007-07-18 18:00:27 +00002736/// getVectorType - Return the unique reference to a vector type of
2737/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002738QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002739 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002740 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002741
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002742 // Check if we've already instantiated a vector of this type.
2743 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002744 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002745
Craig Topper36250ad2014-05-12 05:36:57 +00002746 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002747 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2748 return QualType(VTP, 0);
2749
2750 // If the element type isn't canonical, this won't be a canonical type either,
2751 // so fill in the canonical type field.
2752 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002753 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002754 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002755
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002756 // Get the new insert position for the node we care about.
2757 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002758 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002759 }
John McCall90d1c2d2009-09-24 23:30:46 +00002760 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002761 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002762 VectorTypes.InsertNode(New, InsertPos);
2763 Types.push_back(New);
2764 return QualType(New, 0);
2765}
2766
Nate Begemance4d7fc2008-04-18 23:10:10 +00002767/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002768/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002769QualType
2770ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002771 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002772
Steve Naroff91fcddb2007-07-18 18:00:27 +00002773 // Check if we've already instantiated a vector of this type.
2774 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002775 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002776 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002777 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002778 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2779 return QualType(VTP, 0);
2780
2781 // If the element type isn't canonical, this won't be a canonical type either,
2782 // so fill in the canonical type field.
2783 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002784 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002785 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002786
Steve Naroff91fcddb2007-07-18 18:00:27 +00002787 // Get the new insert position for the node we care about.
2788 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002789 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002790 }
John McCall90d1c2d2009-09-24 23:30:46 +00002791 ExtVectorType *New = new (*this, TypeAlignment)
2792 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002793 VectorTypes.InsertNode(New, InsertPos);
2794 Types.push_back(New);
2795 return QualType(New, 0);
2796}
2797
Jay Foad39c79802011-01-12 09:06:06 +00002798QualType
2799ASTContext::getDependentSizedExtVectorType(QualType vecType,
2800 Expr *SizeExpr,
2801 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002802 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002803 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002804 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002805
Craig Topper36250ad2014-05-12 05:36:57 +00002806 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002807 DependentSizedExtVectorType *Canon
2808 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2809 DependentSizedExtVectorType *New;
2810 if (Canon) {
2811 // We already have a canonical version of this array type; use it as
2812 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002813 New = new (*this, TypeAlignment)
2814 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2815 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002816 } else {
2817 QualType CanonVecTy = getCanonicalType(vecType);
2818 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002819 New = new (*this, TypeAlignment)
2820 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2821 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002822
2823 DependentSizedExtVectorType *CanonCheck
2824 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2825 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2826 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002827 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2828 } else {
2829 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2830 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002831 New = new (*this, TypeAlignment)
2832 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002833 }
2834 }
Mike Stump11289f42009-09-09 15:08:12 +00002835
Douglas Gregor758a8692009-06-17 21:51:59 +00002836 Types.push_back(New);
2837 return QualType(New, 0);
2838}
2839
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002840/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002841///
Jay Foad39c79802011-01-12 09:06:06 +00002842QualType
2843ASTContext::getFunctionNoProtoType(QualType ResultTy,
2844 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002845 const CallingConv CallConv = Info.getCC();
2846
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002847 // Unique functions, to guarantee there is only one function of a particular
2848 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002849 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002850 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002851
Craig Topper36250ad2014-05-12 05:36:57 +00002852 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002853 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002854 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002855 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002856
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002857 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002858 if (!ResultTy.isCanonical()) {
2859 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002860
Chris Lattner47955de2007-01-27 08:37:20 +00002861 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002862 FunctionNoProtoType *NewIP =
2863 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002864 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002865 }
Mike Stump11289f42009-09-09 15:08:12 +00002866
Roman Divacky65b88cd2011-03-01 17:40:53 +00002867 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002868 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002869 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002870 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002871 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002872 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002873}
2874
Douglas Gregorcd780372013-01-17 23:36:45 +00002875/// \brief Determine whether \p T is canonical as the result type of a function.
2876static bool isCanonicalResultType(QualType T) {
2877 return T.isCanonical() &&
2878 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2879 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2880}
2881
Jay Foad39c79802011-01-12 09:06:06 +00002882QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002883ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002884 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002885 size_t NumArgs = ArgArray.size();
2886
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002887 // Unique functions, to guarantee there is only one function of a particular
2888 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002889 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002890 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2891 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002892
Craig Topper36250ad2014-05-12 05:36:57 +00002893 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002894 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002895 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002896 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002897
2898 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002899 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00002900 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002901 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002902 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002903 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002904 isCanonical = false;
2905
2906 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002907 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002908 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002909 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002910 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002911 CanonicalArgs.reserve(NumArgs);
2912 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002913 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002914
John McCalldb40c7f2010-12-14 08:05:40 +00002915 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002916 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00002917 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00002918
Douglas Gregorcd780372013-01-17 23:36:45 +00002919 // Result types do not have ARC lifetime qualifiers.
2920 QualType CanResultTy = getCanonicalType(ResultTy);
2921 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2922 Qualifiers Qs = CanResultTy.getQualifiers();
2923 Qs.removeObjCLifetime();
2924 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2925 }
2926
Jordan Rose5c382722013-03-08 21:51:21 +00002927 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002928
Chris Lattnerfd4de792007-01-27 01:15:32 +00002929 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002930 FunctionProtoType *NewIP =
2931 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002932 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002933 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002934
John McCall31168b02011-06-15 23:02:42 +00002935 // FunctionProtoType objects are allocated with extra bytes after
2936 // them for three variable size arrays at the end:
2937 // - parameter types
2938 // - exception types
2939 // - consumed-arguments flags
2940 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002941 // expression, or information used to resolve the exception
2942 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002943 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002944 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00002945 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
2946 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
2947 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002948 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00002949 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002950 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00002951 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00002952 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002953 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002954 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002955 Size += NumArgs * sizeof(bool);
2956
John McCalldb40c7f2010-12-14 08:05:40 +00002957 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002958 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002959 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002960 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002961 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002962 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002963}
Chris Lattneref51c202006-11-10 07:17:23 +00002964
John McCalle78aac42010-03-10 03:28:59 +00002965#ifndef NDEBUG
2966static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2967 if (!isa<CXXRecordDecl>(D)) return false;
2968 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2969 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2970 return true;
2971 if (RD->getDescribedClassTemplate() &&
2972 !isa<ClassTemplateSpecializationDecl>(RD))
2973 return true;
2974 return false;
2975}
2976#endif
2977
2978/// getInjectedClassNameType - Return the unique reference to the
2979/// injected class name type for the specified templated declaration.
2980QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002981 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002982 assert(NeedsInjectedClassNameType(Decl));
2983 if (Decl->TypeForDecl) {
2984 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002985 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002986 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2987 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2988 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2989 } else {
John McCall424cec92011-01-19 06:33:43 +00002990 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002991 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002992 Decl->TypeForDecl = newType;
2993 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002994 }
2995 return QualType(Decl->TypeForDecl, 0);
2996}
2997
Douglas Gregor83a586e2008-04-13 21:07:44 +00002998/// getTypeDeclType - Return the unique reference to the type for the
2999/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003000QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003001 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003002 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003003
Richard Smithdda56e42011-04-15 14:24:37 +00003004 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003005 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003006
John McCall96f0b5f2010-03-10 06:48:02 +00003007 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3008 "Template type parameter types are always available.");
3009
John McCall81e38502010-02-16 03:57:14 +00003010 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003011 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003012 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003013 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003014 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003015 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003016 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003017 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003018 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003019 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3020 Decl->TypeForDecl = newType;
3021 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003022 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003023 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003024
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003025 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003026}
3027
Chris Lattner32d920b2007-01-26 02:01:53 +00003028/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003029/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003030QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003031ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3032 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003033 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003034
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003035 if (Canonical.isNull())
3036 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003037 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003038 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003039 Decl->TypeForDecl = newType;
3040 Types.push_back(newType);
3041 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003042}
3043
Jay Foad39c79802011-01-12 09:06:06 +00003044QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003045 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3046
Douglas Gregorec9fd132012-01-14 16:38:05 +00003047 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003048 if (PrevDecl->TypeForDecl)
3049 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3050
John McCall424cec92011-01-19 06:33:43 +00003051 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3052 Decl->TypeForDecl = newType;
3053 Types.push_back(newType);
3054 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003055}
3056
Jay Foad39c79802011-01-12 09:06:06 +00003057QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003058 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3059
Douglas Gregorec9fd132012-01-14 16:38:05 +00003060 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003061 if (PrevDecl->TypeForDecl)
3062 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3063
John McCall424cec92011-01-19 06:33:43 +00003064 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3065 Decl->TypeForDecl = newType;
3066 Types.push_back(newType);
3067 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003068}
3069
John McCall81904512011-01-06 01:58:22 +00003070QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3071 QualType modifiedType,
3072 QualType equivalentType) {
3073 llvm::FoldingSetNodeID id;
3074 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3075
Craig Topper36250ad2014-05-12 05:36:57 +00003076 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003077 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3078 if (type) return QualType(type, 0);
3079
3080 QualType canon = getCanonicalType(equivalentType);
3081 type = new (*this, TypeAlignment)
3082 AttributedType(canon, attrKind, modifiedType, equivalentType);
3083
3084 Types.push_back(type);
3085 AttributedTypes.InsertNode(type, insertPos);
3086
3087 return QualType(type, 0);
3088}
3089
3090
John McCallcebee162009-10-18 09:09:24 +00003091/// \brief Retrieve a substitution-result type.
3092QualType
3093ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003094 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003095 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003096 && "replacement types must always be canonical");
3097
3098 llvm::FoldingSetNodeID ID;
3099 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003100 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003101 SubstTemplateTypeParmType *SubstParm
3102 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3103
3104 if (!SubstParm) {
3105 SubstParm = new (*this, TypeAlignment)
3106 SubstTemplateTypeParmType(Parm, Replacement);
3107 Types.push_back(SubstParm);
3108 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3109 }
3110
3111 return QualType(SubstParm, 0);
3112}
3113
Douglas Gregorada4b792011-01-14 02:55:32 +00003114/// \brief Retrieve a
3115QualType ASTContext::getSubstTemplateTypeParmPackType(
3116 const TemplateTypeParmType *Parm,
3117 const TemplateArgument &ArgPack) {
3118#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003119 for (const auto &P : ArgPack.pack_elements()) {
3120 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3121 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003122 }
3123#endif
3124
3125 llvm::FoldingSetNodeID ID;
3126 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003127 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003128 if (SubstTemplateTypeParmPackType *SubstParm
3129 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3130 return QualType(SubstParm, 0);
3131
3132 QualType Canon;
3133 if (!Parm->isCanonicalUnqualified()) {
3134 Canon = getCanonicalType(QualType(Parm, 0));
3135 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3136 ArgPack);
3137 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3138 }
3139
3140 SubstTemplateTypeParmPackType *SubstParm
3141 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3142 ArgPack);
3143 Types.push_back(SubstParm);
3144 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3145 return QualType(SubstParm, 0);
3146}
3147
Douglas Gregoreff93e02009-02-05 23:33:38 +00003148/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003149/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003150/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003151QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003152 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003153 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003154 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003155 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003156 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003157 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003158 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3159
3160 if (TypeParm)
3161 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003162
Chandler Carruth08836322011-05-01 00:51:33 +00003163 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003164 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003165 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003166
3167 TemplateTypeParmType *TypeCheck
3168 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3169 assert(!TypeCheck && "Template type parameter canonical type broken");
3170 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003171 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003172 TypeParm = new (*this, TypeAlignment)
3173 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003174
3175 Types.push_back(TypeParm);
3176 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3177
3178 return QualType(TypeParm, 0);
3179}
3180
John McCalle78aac42010-03-10 03:28:59 +00003181TypeSourceInfo *
3182ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3183 SourceLocation NameLoc,
3184 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003185 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003186 assert(!Name.getAsDependentTemplateName() &&
3187 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003188 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003189
3190 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003191 TemplateSpecializationTypeLoc TL =
3192 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003193 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003194 TL.setTemplateNameLoc(NameLoc);
3195 TL.setLAngleLoc(Args.getLAngleLoc());
3196 TL.setRAngleLoc(Args.getRAngleLoc());
3197 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3198 TL.setArgLocInfo(i, Args[i].getLocInfo());
3199 return DI;
3200}
3201
Mike Stump11289f42009-09-09 15:08:12 +00003202QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003203ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003204 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003205 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003206 assert(!Template.getAsDependentTemplateName() &&
3207 "No dependent template names here!");
3208
John McCall6b51f282009-11-23 01:53:49 +00003209 unsigned NumArgs = Args.size();
3210
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003211 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003212 ArgVec.reserve(NumArgs);
3213 for (unsigned i = 0; i != NumArgs; ++i)
3214 ArgVec.push_back(Args[i].getArgument());
3215
John McCall2408e322010-04-27 00:57:59 +00003216 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003217 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003218}
3219
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003220#ifndef NDEBUG
3221static bool hasAnyPackExpansions(const TemplateArgument *Args,
3222 unsigned NumArgs) {
3223 for (unsigned I = 0; I != NumArgs; ++I)
3224 if (Args[I].isPackExpansion())
3225 return true;
3226
3227 return true;
3228}
3229#endif
3230
John McCall0ad16662009-10-29 08:12:44 +00003231QualType
3232ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003233 const TemplateArgument *Args,
3234 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003235 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003236 assert(!Template.getAsDependentTemplateName() &&
3237 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003238 // Look through qualified template names.
3239 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3240 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003241
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003242 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003243 Template.getAsTemplateDecl() &&
3244 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003245 QualType CanonType;
3246 if (!Underlying.isNull())
3247 CanonType = getCanonicalType(Underlying);
3248 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003249 // We can get here with an alias template when the specialization contains
3250 // a pack expansion that does not match up with a parameter pack.
3251 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3252 "Caller must compute aliased type");
3253 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003254 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3255 NumArgs);
3256 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003257
Douglas Gregora8e02e72009-07-28 23:00:59 +00003258 // Allocate the (non-canonical) template specialization type, but don't
3259 // try to unique it: these types typically have location information that
3260 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003261 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3262 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003263 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003264 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003265 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003266 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3267 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003268
Douglas Gregor8bf42052009-02-09 18:46:07 +00003269 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003270 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003271}
3272
Mike Stump11289f42009-09-09 15:08:12 +00003273QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003274ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3275 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003276 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003277 assert(!Template.getAsDependentTemplateName() &&
3278 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003279
Douglas Gregore29139c2011-03-03 17:04:51 +00003280 // Look through qualified template names.
3281 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3282 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003283
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003284 // Build the canonical template specialization type.
3285 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003286 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003287 CanonArgs.reserve(NumArgs);
3288 for (unsigned I = 0; I != NumArgs; ++I)
3289 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3290
3291 // Determine whether this canonical template specialization type already
3292 // exists.
3293 llvm::FoldingSetNodeID ID;
3294 TemplateSpecializationType::Profile(ID, CanonTemplate,
3295 CanonArgs.data(), NumArgs, *this);
3296
Craig Topper36250ad2014-05-12 05:36:57 +00003297 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003298 TemplateSpecializationType *Spec
3299 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3300
3301 if (!Spec) {
3302 // Allocate a new canonical template specialization type.
3303 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3304 sizeof(TemplateArgument) * NumArgs),
3305 TypeAlignment);
3306 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3307 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003308 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003309 Types.push_back(Spec);
3310 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3311 }
3312
3313 assert(Spec->isDependentType() &&
3314 "Non-dependent template-id type must have a canonical type");
3315 return QualType(Spec, 0);
3316}
3317
3318QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003319ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3320 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003321 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003322 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003323 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003324
Craig Topper36250ad2014-05-12 05:36:57 +00003325 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003326 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003327 if (T)
3328 return QualType(T, 0);
3329
Douglas Gregorc42075a2010-02-04 18:10:26 +00003330 QualType Canon = NamedType;
3331 if (!Canon.isCanonical()) {
3332 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003333 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3334 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003335 (void)CheckT;
3336 }
3337
Abramo Bagnara6150c882010-05-11 21:36:43 +00003338 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003339 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003340 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003341 return QualType(T, 0);
3342}
3343
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003344QualType
Jay Foad39c79802011-01-12 09:06:06 +00003345ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003346 llvm::FoldingSetNodeID ID;
3347 ParenType::Profile(ID, InnerType);
3348
Craig Topper36250ad2014-05-12 05:36:57 +00003349 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003350 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3351 if (T)
3352 return QualType(T, 0);
3353
3354 QualType Canon = InnerType;
3355 if (!Canon.isCanonical()) {
3356 Canon = getCanonicalType(InnerType);
3357 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3358 assert(!CheckT && "Paren canonical type broken");
3359 (void)CheckT;
3360 }
3361
3362 T = new (*this) ParenType(InnerType, Canon);
3363 Types.push_back(T);
3364 ParenTypes.InsertNode(T, InsertPos);
3365 return QualType(T, 0);
3366}
3367
Douglas Gregor02085352010-03-31 20:19:30 +00003368QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3369 NestedNameSpecifier *NNS,
3370 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003371 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003372 if (Canon.isNull()) {
3373 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003374 ElaboratedTypeKeyword CanonKeyword = Keyword;
3375 if (Keyword == ETK_None)
3376 CanonKeyword = ETK_Typename;
3377
3378 if (CanonNNS != NNS || CanonKeyword != Keyword)
3379 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003380 }
3381
3382 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003383 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003384
Craig Topper36250ad2014-05-12 05:36:57 +00003385 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003386 DependentNameType *T
3387 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003388 if (T)
3389 return QualType(T, 0);
3390
Douglas Gregor02085352010-03-31 20:19:30 +00003391 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003392 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003393 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003394 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003395}
3396
Mike Stump11289f42009-09-09 15:08:12 +00003397QualType
John McCallc392f372010-06-11 00:33:02 +00003398ASTContext::getDependentTemplateSpecializationType(
3399 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003400 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003401 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003402 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003403 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003404 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003405 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3406 ArgCopy.push_back(Args[I].getArgument());
3407 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3408 ArgCopy.size(),
3409 ArgCopy.data());
3410}
3411
3412QualType
3413ASTContext::getDependentTemplateSpecializationType(
3414 ElaboratedTypeKeyword Keyword,
3415 NestedNameSpecifier *NNS,
3416 const IdentifierInfo *Name,
3417 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003418 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003419 assert((!NNS || NNS->isDependent()) &&
3420 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003421
Douglas Gregorc42075a2010-02-04 18:10:26 +00003422 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003423 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3424 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003425
Craig Topper36250ad2014-05-12 05:36:57 +00003426 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003427 DependentTemplateSpecializationType *T
3428 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003429 if (T)
3430 return QualType(T, 0);
3431
John McCallc392f372010-06-11 00:33:02 +00003432 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003433
John McCallc392f372010-06-11 00:33:02 +00003434 ElaboratedTypeKeyword CanonKeyword = Keyword;
3435 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3436
3437 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003438 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003439 for (unsigned I = 0; I != NumArgs; ++I) {
3440 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3441 if (!CanonArgs[I].structurallyEquals(Args[I]))
3442 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003443 }
3444
John McCallc392f372010-06-11 00:33:02 +00003445 QualType Canon;
3446 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3447 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3448 Name, NumArgs,
3449 CanonArgs.data());
3450
3451 // Find the insert position again.
3452 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3453 }
3454
3455 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3456 sizeof(TemplateArgument) * NumArgs),
3457 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003458 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003459 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003460 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003461 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003462 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003463}
3464
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003465QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003466 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003467 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003468 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003469
3470 assert(Pattern->containsUnexpandedParameterPack() &&
3471 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003472 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003473 PackExpansionType *T
3474 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3475 if (T)
3476 return QualType(T, 0);
3477
3478 QualType Canon;
3479 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003480 Canon = getCanonicalType(Pattern);
3481 // The canonical type might not contain an unexpanded parameter pack, if it
3482 // contains an alias template specialization which ignores one of its
3483 // parameters.
3484 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003485 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003486
Richard Smith68eea502012-07-16 00:20:35 +00003487 // Find the insert position again, in case we inserted an element into
3488 // PackExpansionTypes and invalidated our insert position.
3489 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3490 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003491 }
3492
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003493 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003494 Types.push_back(T);
3495 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003496 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003497}
3498
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003499/// CmpProtocolNames - Comparison predicate for sorting protocols
3500/// alphabetically.
3501static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3502 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003503 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003504}
3505
John McCall8b07ec22010-05-15 11:32:37 +00003506static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003507 unsigned NumProtocols) {
3508 if (NumProtocols == 0) return true;
3509
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003510 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3511 return false;
3512
John McCallfc93cf92009-10-22 22:37:11 +00003513 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003514 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3515 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003516 return false;
3517 return true;
3518}
3519
3520static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003521 unsigned &NumProtocols) {
3522 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003523
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003524 // Sort protocols, keyed by name.
3525 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3526
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003527 // Canonicalize.
3528 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3529 Protocols[I] = Protocols[I]->getCanonicalDecl();
3530
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003531 // Remove duplicates.
3532 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3533 NumProtocols = ProtocolsEnd-Protocols;
3534}
3535
John McCall8b07ec22010-05-15 11:32:37 +00003536QualType ASTContext::getObjCObjectType(QualType BaseType,
3537 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003538 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003539 // If the base type is an interface and there aren't any protocols
3540 // to add, then the interface type will do just fine.
3541 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3542 return BaseType;
3543
3544 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003545 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003546 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Craig Topper36250ad2014-05-12 05:36:57 +00003547 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003548 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3549 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003550
John McCall8b07ec22010-05-15 11:32:37 +00003551 // Build the canonical type, which has the canonical base type and
3552 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003553 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003554 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3555 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3556 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003557 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003558 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003559 unsigned UniqueCount = NumProtocols;
3560
John McCallfc93cf92009-10-22 22:37:11 +00003561 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003562 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3563 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003564 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003565 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3566 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003567 }
3568
3569 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003570 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3571 }
3572
3573 unsigned Size = sizeof(ObjCObjectTypeImpl);
3574 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3575 void *Mem = Allocate(Size, TypeAlignment);
3576 ObjCObjectTypeImpl *T =
3577 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3578
3579 Types.push_back(T);
3580 ObjCObjectTypes.InsertNode(T, InsertPos);
3581 return QualType(T, 0);
3582}
3583
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003584/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3585/// protocol list adopt all protocols in QT's qualified-id protocol
3586/// list.
3587bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3588 ObjCInterfaceDecl *IC) {
3589 if (!QT->isObjCQualifiedIdType())
3590 return false;
3591
3592 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3593 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003594 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003595 if (!IC->ClassImplementsProtocol(Proto, false))
3596 return false;
3597 }
3598 return true;
3599 }
3600 return false;
3601}
3602
3603/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3604/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3605/// of protocols.
3606bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3607 ObjCInterfaceDecl *IDecl) {
3608 if (!QT->isObjCQualifiedIdType())
3609 return false;
3610 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3611 if (!OPT)
3612 return false;
3613 if (!IDecl->hasDefinition())
3614 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003615 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3616 CollectInheritedProtocols(IDecl, InheritedProtocols);
3617 if (InheritedProtocols.empty())
3618 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003619 // Check that if every protocol in list of id<plist> conforms to a protcol
3620 // of IDecl's, then bridge casting is ok.
3621 bool Conforms = false;
3622 for (auto *Proto : OPT->quals()) {
3623 Conforms = false;
3624 for (auto *PI : InheritedProtocols) {
3625 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3626 Conforms = true;
3627 break;
3628 }
3629 }
3630 if (!Conforms)
3631 break;
3632 }
3633 if (Conforms)
3634 return true;
3635
Aaron Ballman83731462014-03-17 16:14:00 +00003636 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003637 // If both the right and left sides have qualifiers.
3638 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003639 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003640 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003641 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003642 break;
3643 }
3644 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003645 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003646 }
3647 return true;
3648}
3649
John McCall8b07ec22010-05-15 11:32:37 +00003650/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3651/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003652QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003653 llvm::FoldingSetNodeID ID;
3654 ObjCObjectPointerType::Profile(ID, ObjectT);
3655
Craig Topper36250ad2014-05-12 05:36:57 +00003656 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003657 if (ObjCObjectPointerType *QT =
3658 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3659 return QualType(QT, 0);
3660
3661 // Find the canonical object type.
3662 QualType Canonical;
3663 if (!ObjectT.isCanonical()) {
3664 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3665
3666 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003667 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3668 }
3669
Douglas Gregorf85bee62010-02-08 22:59:26 +00003670 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003671 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3672 ObjCObjectPointerType *QType =
3673 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003674
Steve Narofffb4330f2009-06-17 22:40:22 +00003675 Types.push_back(QType);
3676 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003677 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003678}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003679
Douglas Gregor1c283312010-08-11 12:19:30 +00003680/// getObjCInterfaceType - Return the unique reference to the type for the
3681/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003682QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3683 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003684 if (Decl->TypeForDecl)
3685 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003686
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003687 if (PrevDecl) {
3688 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3689 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3690 return QualType(PrevDecl->TypeForDecl, 0);
3691 }
3692
Douglas Gregor7671e532011-12-16 16:34:57 +00003693 // Prefer the definition, if there is one.
3694 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3695 Decl = Def;
3696
Douglas Gregor1c283312010-08-11 12:19:30 +00003697 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3698 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3699 Decl->TypeForDecl = T;
3700 Types.push_back(T);
3701 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003702}
3703
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003704/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3705/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003706/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003707/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003708/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003709QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003710 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003711 if (tofExpr->isTypeDependent()) {
3712 llvm::FoldingSetNodeID ID;
3713 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003714
Craig Topper36250ad2014-05-12 05:36:57 +00003715 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003716 DependentTypeOfExprType *Canon
3717 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3718 if (Canon) {
3719 // We already have a "canonical" version of an identical, dependent
3720 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003721 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003722 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003723 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003724 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003725 Canon
3726 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003727 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3728 toe = Canon;
3729 }
3730 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003731 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003732 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003733 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003734 Types.push_back(toe);
3735 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003736}
3737
Steve Naroffa773cd52007-08-01 18:02:17 +00003738/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003739/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003740/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003741/// an issue. This doesn't affect the type checker, since it operates
3742/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003743QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003744 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003745 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003746 Types.push_back(tot);
3747 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003748}
3749
Anders Carlssonad6bd352009-06-24 21:24:56 +00003750
Richard Smith8eb1d322014-06-05 20:13:13 +00003751/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3752/// nodes. This would never be helpful, since each such type has its own
3753/// expression, and would not give a significant memory saving, since there
3754/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003755QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003756 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003757
3758 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003759 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003760 // unique dependent type. Two such decltype-specifiers refer to the same
3761 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003762 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003763 llvm::FoldingSetNodeID ID;
3764 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003765
Craig Topper36250ad2014-05-12 05:36:57 +00003766 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003767 DependentDecltypeType *Canon
3768 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003769 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003770 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003771 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003772 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003773 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003774 dt = new (*this, TypeAlignment)
3775 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003776 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003777 dt = new (*this, TypeAlignment)
3778 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003779 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003780 Types.push_back(dt);
3781 return QualType(dt, 0);
3782}
3783
Alexis Hunte852b102011-05-24 22:41:36 +00003784/// getUnaryTransformationType - We don't unique these, since the memory
3785/// savings are minimal and these are rare.
3786QualType ASTContext::getUnaryTransformType(QualType BaseType,
3787 QualType UnderlyingType,
3788 UnaryTransformType::UTTKind Kind)
3789 const {
3790 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003791 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3792 Kind,
3793 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003794 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003795 Types.push_back(Ty);
3796 return QualType(Ty, 0);
3797}
3798
Richard Smith2a7d4812013-05-04 07:00:32 +00003799/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3800/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3801/// canonical deduced-but-dependent 'auto' type.
3802QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003803 bool IsDependent) const {
3804 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003805 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003806
Richard Smith2a7d4812013-05-04 07:00:32 +00003807 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003808 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003809 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003810 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003811 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3812 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003813
Richard Smith74aeef52013-04-26 16:15:35 +00003814 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003815 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003816 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003817 Types.push_back(AT);
3818 if (InsertPos)
3819 AutoTypes.InsertNode(AT, InsertPos);
3820 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003821}
3822
Eli Friedman0dfb8892011-10-06 23:00:33 +00003823/// getAtomicType - Return the uniqued reference to the atomic type for
3824/// the given value type.
3825QualType ASTContext::getAtomicType(QualType T) const {
3826 // Unique pointers, to guarantee there is only one pointer of a particular
3827 // structure.
3828 llvm::FoldingSetNodeID ID;
3829 AtomicType::Profile(ID, T);
3830
Craig Topper36250ad2014-05-12 05:36:57 +00003831 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003832 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3833 return QualType(AT, 0);
3834
3835 // If the atomic value type isn't canonical, this won't be a canonical type
3836 // either, so fill in the canonical type field.
3837 QualType Canonical;
3838 if (!T.isCanonical()) {
3839 Canonical = getAtomicType(getCanonicalType(T));
3840
3841 // Get the new insert position for the node we care about.
3842 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003843 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003844 }
3845 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3846 Types.push_back(New);
3847 AtomicTypes.InsertNode(New, InsertPos);
3848 return QualType(New, 0);
3849}
3850
Richard Smith02e85f32011-04-14 22:09:26 +00003851/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3852QualType ASTContext::getAutoDeductType() const {
3853 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003854 AutoDeductTy = QualType(
3855 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003856 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003857 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003858 return AutoDeductTy;
3859}
3860
3861/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3862QualType ASTContext::getAutoRRefDeductType() const {
3863 if (AutoRRefDeductTy.isNull())
3864 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3865 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3866 return AutoRRefDeductTy;
3867}
3868
Chris Lattnerfb072462007-01-23 05:45:31 +00003869/// getTagDeclType - Return the unique reference to the type for the
3870/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003871QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003872 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003873 // FIXME: What is the design on getTagDeclType when it requires casting
3874 // away const? mutable?
3875 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003876}
3877
Mike Stump11289f42009-09-09 15:08:12 +00003878/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3879/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3880/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003881CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003882 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003883}
Chris Lattnerfb072462007-01-23 05:45:31 +00003884
Hans Wennborg27541db2011-10-27 08:29:09 +00003885/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3886CanQualType ASTContext::getIntMaxType() const {
3887 return getFromTargetType(Target->getIntMaxType());
3888}
3889
3890/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3891CanQualType ASTContext::getUIntMaxType() const {
3892 return getFromTargetType(Target->getUIntMaxType());
3893}
3894
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003895/// getSignedWCharType - Return the type of "signed wchar_t".
3896/// Used when in C++, as a GCC extension.
3897QualType ASTContext::getSignedWCharType() const {
3898 // FIXME: derive from "Target" ?
3899 return WCharTy;
3900}
3901
3902/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3903/// Used when in C++, as a GCC extension.
3904QualType ASTContext::getUnsignedWCharType() const {
3905 // FIXME: derive from "Target" ?
3906 return UnsignedIntTy;
3907}
3908
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003909QualType ASTContext::getIntPtrType() const {
3910 return getFromTargetType(Target->getIntPtrType());
3911}
3912
3913QualType ASTContext::getUIntPtrType() const {
3914 return getCorrespondingUnsignedType(getIntPtrType());
3915}
3916
Hans Wennborg27541db2011-10-27 08:29:09 +00003917/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003918/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3919QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003920 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003921}
3922
Eli Friedman4e91899e2012-11-27 02:58:24 +00003923/// \brief Return the unique type for "pid_t" defined in
3924/// <sys/types.h>. We need this to compute the correct type for vfork().
3925QualType ASTContext::getProcessIDType() const {
3926 return getFromTargetType(Target->getProcessIDType());
3927}
3928
Chris Lattnera21ad802008-04-02 05:18:44 +00003929//===----------------------------------------------------------------------===//
3930// Type Operators
3931//===----------------------------------------------------------------------===//
3932
Jay Foad39c79802011-01-12 09:06:06 +00003933CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003934 // Push qualifiers into arrays, and then discard any remaining
3935 // qualifiers.
3936 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003937 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003938 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003939 QualType Result;
3940 if (isa<ArrayType>(Ty)) {
3941 Result = getArrayDecayedType(QualType(Ty,0));
3942 } else if (isa<FunctionType>(Ty)) {
3943 Result = getPointerType(QualType(Ty, 0));
3944 } else {
3945 Result = QualType(Ty, 0);
3946 }
3947
3948 return CanQualType::CreateUnsafe(Result);
3949}
3950
John McCall6c9dd522011-01-18 07:41:22 +00003951QualType ASTContext::getUnqualifiedArrayType(QualType type,
3952 Qualifiers &quals) {
3953 SplitQualType splitType = type.getSplitUnqualifiedType();
3954
3955 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3956 // the unqualified desugared type and then drops it on the floor.
3957 // We then have to strip that sugar back off with
3958 // getUnqualifiedDesugaredType(), which is silly.
3959 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003960 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003961
3962 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003963 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003964 quals = splitType.Quals;
3965 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003966 }
3967
John McCall6c9dd522011-01-18 07:41:22 +00003968 // Otherwise, recurse on the array's element type.
3969 QualType elementType = AT->getElementType();
3970 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3971
3972 // If that didn't change the element type, AT has no qualifiers, so we
3973 // can just use the results in splitType.
3974 if (elementType == unqualElementType) {
3975 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003976 quals = splitType.Quals;
3977 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003978 }
3979
3980 // Otherwise, add in the qualifiers from the outermost type, then
3981 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003982 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003983
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003984 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003985 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003986 CAT->getSizeModifier(), 0);
3987 }
3988
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003989 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003990 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003991 }
3992
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003993 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003994 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003995 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003996 VAT->getSizeModifier(),
3997 VAT->getIndexTypeCVRQualifiers(),
3998 VAT->getBracketsRange());
3999 }
4000
4001 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004002 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004003 DSAT->getSizeModifier(), 0,
4004 SourceRange());
4005}
4006
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004007/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4008/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4009/// they point to and return true. If T1 and T2 aren't pointer types
4010/// or pointer-to-member types, or if they are not similar at this
4011/// level, returns false and leaves T1 and T2 unchanged. Top-level
4012/// qualifiers on T1 and T2 are ignored. This function will typically
4013/// be called in a loop that successively "unwraps" pointer and
4014/// pointer-to-member types to compare them at each level.
4015bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4016 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4017 *T2PtrType = T2->getAs<PointerType>();
4018 if (T1PtrType && T2PtrType) {
4019 T1 = T1PtrType->getPointeeType();
4020 T2 = T2PtrType->getPointeeType();
4021 return true;
4022 }
4023
4024 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4025 *T2MPType = T2->getAs<MemberPointerType>();
4026 if (T1MPType && T2MPType &&
4027 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4028 QualType(T2MPType->getClass(), 0))) {
4029 T1 = T1MPType->getPointeeType();
4030 T2 = T2MPType->getPointeeType();
4031 return true;
4032 }
4033
David Blaikiebbafb8a2012-03-11 07:00:24 +00004034 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004035 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4036 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4037 if (T1OPType && T2OPType) {
4038 T1 = T1OPType->getPointeeType();
4039 T2 = T2OPType->getPointeeType();
4040 return true;
4041 }
4042 }
4043
4044 // FIXME: Block pointers, too?
4045
4046 return false;
4047}
4048
Jay Foad39c79802011-01-12 09:06:06 +00004049DeclarationNameInfo
4050ASTContext::getNameForTemplate(TemplateName Name,
4051 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004052 switch (Name.getKind()) {
4053 case TemplateName::QualifiedTemplate:
4054 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004055 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004056 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4057 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004058
John McCalld9dfe3a2011-06-30 08:33:18 +00004059 case TemplateName::OverloadedTemplate: {
4060 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4061 // DNInfo work in progress: CHECKME: what about DNLoc?
4062 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4063 }
4064
4065 case TemplateName::DependentTemplate: {
4066 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004067 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004068 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004069 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4070 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004071 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004072 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4073 // DNInfo work in progress: FIXME: source locations?
4074 DeclarationNameLoc DNLoc;
4075 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4076 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4077 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004078 }
4079 }
4080
John McCalld9dfe3a2011-06-30 08:33:18 +00004081 case TemplateName::SubstTemplateTemplateParm: {
4082 SubstTemplateTemplateParmStorage *subst
4083 = Name.getAsSubstTemplateTemplateParm();
4084 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4085 NameLoc);
4086 }
4087
4088 case TemplateName::SubstTemplateTemplateParmPack: {
4089 SubstTemplateTemplateParmPackStorage *subst
4090 = Name.getAsSubstTemplateTemplateParmPack();
4091 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4092 NameLoc);
4093 }
4094 }
4095
4096 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004097}
4098
Jay Foad39c79802011-01-12 09:06:06 +00004099TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004100 switch (Name.getKind()) {
4101 case TemplateName::QualifiedTemplate:
4102 case TemplateName::Template: {
4103 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004104 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004105 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004106 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4107
4108 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004109 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004110 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004111
John McCalld9dfe3a2011-06-30 08:33:18 +00004112 case TemplateName::OverloadedTemplate:
4113 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004114
John McCalld9dfe3a2011-06-30 08:33:18 +00004115 case TemplateName::DependentTemplate: {
4116 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4117 assert(DTN && "Non-dependent template names must refer to template decls.");
4118 return DTN->CanonicalTemplateName;
4119 }
4120
4121 case TemplateName::SubstTemplateTemplateParm: {
4122 SubstTemplateTemplateParmStorage *subst
4123 = Name.getAsSubstTemplateTemplateParm();
4124 return getCanonicalTemplateName(subst->getReplacement());
4125 }
4126
4127 case TemplateName::SubstTemplateTemplateParmPack: {
4128 SubstTemplateTemplateParmPackStorage *subst
4129 = Name.getAsSubstTemplateTemplateParmPack();
4130 TemplateTemplateParmDecl *canonParameter
4131 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4132 TemplateArgument canonArgPack
4133 = getCanonicalTemplateArgument(subst->getArgumentPack());
4134 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4135 }
4136 }
4137
4138 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004139}
4140
Douglas Gregoradee3e32009-11-11 23:06:43 +00004141bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4142 X = getCanonicalTemplateName(X);
4143 Y = getCanonicalTemplateName(Y);
4144 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4145}
4146
Mike Stump11289f42009-09-09 15:08:12 +00004147TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004148ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004149 switch (Arg.getKind()) {
4150 case TemplateArgument::Null:
4151 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004152
Douglas Gregora8e02e72009-07-28 23:00:59 +00004153 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004154 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004155
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004156 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004157 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004158 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004159 }
Mike Stump11289f42009-09-09 15:08:12 +00004160
Eli Friedmanb826a002012-09-26 02:36:12 +00004161 case TemplateArgument::NullPtr:
4162 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4163 /*isNullPtr*/true);
4164
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004165 case TemplateArgument::Template:
4166 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004167
4168 case TemplateArgument::TemplateExpansion:
4169 return TemplateArgument(getCanonicalTemplateName(
4170 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004171 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004172
Douglas Gregora8e02e72009-07-28 23:00:59 +00004173 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004174 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004175
Douglas Gregora8e02e72009-07-28 23:00:59 +00004176 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004177 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004178
Douglas Gregora8e02e72009-07-28 23:00:59 +00004179 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004180 if (Arg.pack_size() == 0)
4181 return Arg;
4182
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004183 TemplateArgument *CanonArgs
4184 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004185 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004186 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004187 AEnd = Arg.pack_end();
4188 A != AEnd; (void)++A, ++Idx)
4189 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004190
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004191 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004192 }
4193 }
4194
4195 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004196 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004197}
4198
Douglas Gregor333489b2009-03-27 23:10:48 +00004199NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004200ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004201 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004202 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004203
4204 switch (NNS->getKind()) {
4205 case NestedNameSpecifier::Identifier:
4206 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004207 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004208 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4209 NNS->getAsIdentifier());
4210
4211 case NestedNameSpecifier::Namespace:
4212 // A namespace is canonical; build a nested-name-specifier with
4213 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004214 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004215 NNS->getAsNamespace()->getOriginalNamespace());
4216
4217 case NestedNameSpecifier::NamespaceAlias:
4218 // A namespace is canonical; build a nested-name-specifier with
4219 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004220 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004221 NNS->getAsNamespaceAlias()->getNamespace()
4222 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004223
4224 case NestedNameSpecifier::TypeSpec:
4225 case NestedNameSpecifier::TypeSpecWithTemplate: {
4226 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004227
4228 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4229 // break it apart into its prefix and identifier, then reconsititute those
4230 // as the canonical nested-name-specifier. This is required to canonicalize
4231 // a dependent nested-name-specifier involving typedefs of dependent-name
4232 // types, e.g.,
4233 // typedef typename T::type T1;
4234 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004235 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4236 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004237 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004238
Eli Friedman5358a0a2012-03-03 04:09:56 +00004239 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4240 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4241 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004242 return NestedNameSpecifier::Create(*this, nullptr, false,
4243 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004244 }
4245
4246 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004247 case NestedNameSpecifier::Super:
4248 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004249 return NNS;
4250 }
4251
David Blaikie8a40f702012-01-17 06:56:22 +00004252 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004253}
4254
Chris Lattner7adf0762008-08-04 07:31:14 +00004255
Jay Foad39c79802011-01-12 09:06:06 +00004256const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004257 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004258 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004259 // Handle the common positive case fast.
4260 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4261 return AT;
4262 }
Mike Stump11289f42009-09-09 15:08:12 +00004263
John McCall8ccfcb52009-09-24 19:53:00 +00004264 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004265 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004266 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004267
John McCall8ccfcb52009-09-24 19:53:00 +00004268 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004269 // implements C99 6.7.3p8: "If the specification of an array type includes
4270 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004271
Chris Lattner7adf0762008-08-04 07:31:14 +00004272 // If we get here, we either have type qualifiers on the type, or we have
4273 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004274 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004275
John McCall33ddac02011-01-19 10:06:00 +00004276 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004277 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004278
Chris Lattner7adf0762008-08-04 07:31:14 +00004279 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004280 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004281 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004282 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004283
Chris Lattner7adf0762008-08-04 07:31:14 +00004284 // Otherwise, we have an array and we have qualifiers on it. Push the
4285 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004286 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004287
Chris Lattner7adf0762008-08-04 07:31:14 +00004288 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4289 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4290 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004291 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004292 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4293 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4294 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004295 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004296
Mike Stump11289f42009-09-09 15:08:12 +00004297 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004298 = dyn_cast<DependentSizedArrayType>(ATy))
4299 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004300 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004301 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004302 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004303 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004304 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004305
Chris Lattner7adf0762008-08-04 07:31:14 +00004306 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004307 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004308 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004309 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004310 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004311 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004312}
4313
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004314QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004315 if (T->isArrayType() || T->isFunctionType())
4316 return getDecayedType(T);
4317 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004318}
4319
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004320QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004321 T = getVariableArrayDecayedType(T);
4322 T = getAdjustedParameterType(T);
4323 return T.getUnqualifiedType();
4324}
4325
Chris Lattnera21ad802008-04-02 05:18:44 +00004326/// getArrayDecayedType - Return the properly qualified result of decaying the
4327/// specified array type to a pointer. This operation is non-trivial when
4328/// handling typedefs etc. The canonical type of "T" must be an array type,
4329/// this returns a pointer to a properly qualified element of the array.
4330///
4331/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004332QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004333 // Get the element type with 'getAsArrayType' so that we don't lose any
4334 // typedefs in the element type of the array. This also handles propagation
4335 // of type qualifiers from the array type into the element type if present
4336 // (C99 6.7.3p8).
4337 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4338 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004339
Chris Lattner7adf0762008-08-04 07:31:14 +00004340 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004341
4342 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004343 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004344}
4345
John McCall33ddac02011-01-19 10:06:00 +00004346QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4347 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004348}
4349
John McCall33ddac02011-01-19 10:06:00 +00004350QualType ASTContext::getBaseElementType(QualType type) const {
4351 Qualifiers qs;
4352 while (true) {
4353 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004354 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004355 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004356
John McCall33ddac02011-01-19 10:06:00 +00004357 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004358 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004359 }
Mike Stump11289f42009-09-09 15:08:12 +00004360
John McCall33ddac02011-01-19 10:06:00 +00004361 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004362}
4363
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004364/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004365uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004366ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4367 uint64_t ElementCount = 1;
4368 do {
4369 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004370 CA = dyn_cast_or_null<ConstantArrayType>(
4371 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004372 } while (CA);
4373 return ElementCount;
4374}
4375
Steve Naroff0af91202007-04-27 21:51:21 +00004376/// getFloatingRank - Return a relative rank for floating point types.
4377/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004378static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004379 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004380 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004381
John McCall9dd450b2009-09-21 23:43:11 +00004382 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4383 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004384 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004385 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004386 case BuiltinType::Float: return FloatRank;
4387 case BuiltinType::Double: return DoubleRank;
4388 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004389 }
4390}
4391
Mike Stump11289f42009-09-09 15:08:12 +00004392/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4393/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004394/// 'typeDomain' is a real floating point or complex type.
4395/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004396QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4397 QualType Domain) const {
4398 FloatingRank EltRank = getFloatingRank(Size);
4399 if (Domain->isComplexType()) {
4400 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004401 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004402 case FloatRank: return FloatComplexTy;
4403 case DoubleRank: return DoubleComplexTy;
4404 case LongDoubleRank: return LongDoubleComplexTy;
4405 }
Steve Naroff0af91202007-04-27 21:51:21 +00004406 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004407
4408 assert(Domain->isRealFloatingType() && "Unknown domain!");
4409 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004410 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004411 case FloatRank: return FloatTy;
4412 case DoubleRank: return DoubleTy;
4413 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004414 }
David Blaikief47fa302012-01-17 02:30:50 +00004415 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004416}
4417
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004418/// getFloatingTypeOrder - Compare the rank of the two specified floating
4419/// point types, ignoring the domain of the type (i.e. 'double' ==
4420/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004421/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004422int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004423 FloatingRank LHSR = getFloatingRank(LHS);
4424 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004425
Chris Lattnerb90739d2008-04-06 23:38:49 +00004426 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004427 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004428 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004429 return 1;
4430 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004431}
4432
Chris Lattner76a00cf2008-04-06 22:59:24 +00004433/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4434/// routine will assert if passed a built-in type that isn't an integer or enum,
4435/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004436unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004437 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004438
Chris Lattner76a00cf2008-04-06 22:59:24 +00004439 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004440 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004441 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004442 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004443 case BuiltinType::Char_S:
4444 case BuiltinType::Char_U:
4445 case BuiltinType::SChar:
4446 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004447 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004448 case BuiltinType::Short:
4449 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004450 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004451 case BuiltinType::Int:
4452 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004453 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004454 case BuiltinType::Long:
4455 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004456 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004457 case BuiltinType::LongLong:
4458 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004459 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004460 case BuiltinType::Int128:
4461 case BuiltinType::UInt128:
4462 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004463 }
4464}
4465
Eli Friedman629ffb92009-08-20 04:21:42 +00004466/// \brief Whether this is a promotable bitfield reference according
4467/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4468///
4469/// \returns the type this bit-field will promote to, or NULL if no
4470/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004471QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004472 if (E->isTypeDependent() || E->isValueDependent())
4473 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004474
4475 // FIXME: We should not do this unless E->refersToBitField() is true. This
4476 // matters in C where getSourceBitField() will find bit-fields for various
4477 // cases where the source expression is not a bit-field designator.
4478
John McCalld25db7e2013-05-06 21:39:12 +00004479 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004480 if (!Field)
4481 return QualType();
4482
4483 QualType FT = Field->getType();
4484
Richard Smithcaf33902011-10-10 18:28:20 +00004485 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004486 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004487 // C++ [conv.prom]p5:
4488 // A prvalue for an integral bit-field can be converted to a prvalue of type
4489 // int if int can represent all the values of the bit-field; otherwise, it
4490 // can be converted to unsigned int if unsigned int can represent all the
4491 // values of the bit-field. If the bit-field is larger yet, no integral
4492 // promotion applies to it.
4493 // C11 6.3.1.1/2:
4494 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4495 // If an int can represent all values of the original type (as restricted by
4496 // the width, for a bit-field), the value is converted to an int; otherwise,
4497 // it is converted to an unsigned int.
4498 //
4499 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4500 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004501 if (BitWidth < IntSize)
4502 return IntTy;
4503
4504 if (BitWidth == IntSize)
4505 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4506
4507 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004508 // like the base type. GCC has some weird bugs in this area that we
4509 // deliberately do not follow (GCC follows a pre-standard resolution to
4510 // C's DR315 which treats bit-width as being part of the type, and this leaks
4511 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004512 return QualType();
4513}
4514
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004515/// getPromotedIntegerType - Returns the type that Promotable will
4516/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4517/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004518QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004519 assert(!Promotable.isNull());
4520 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004521 if (const EnumType *ET = Promotable->getAs<EnumType>())
4522 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004523
4524 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4525 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4526 // (3.9.1) can be converted to a prvalue of the first of the following
4527 // types that can represent all the values of its underlying type:
4528 // int, unsigned int, long int, unsigned long int, long long int, or
4529 // unsigned long long int [...]
4530 // FIXME: Is there some better way to compute this?
4531 if (BT->getKind() == BuiltinType::WChar_S ||
4532 BT->getKind() == BuiltinType::WChar_U ||
4533 BT->getKind() == BuiltinType::Char16 ||
4534 BT->getKind() == BuiltinType::Char32) {
4535 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4536 uint64_t FromSize = getTypeSize(BT);
4537 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4538 LongLongTy, UnsignedLongLongTy };
4539 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4540 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4541 if (FromSize < ToSize ||
4542 (FromSize == ToSize &&
4543 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4544 return PromoteTypes[Idx];
4545 }
4546 llvm_unreachable("char type should fit into long long");
4547 }
4548 }
4549
4550 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004551 if (Promotable->isSignedIntegerType())
4552 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004553 uint64_t PromotableSize = getIntWidth(Promotable);
4554 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004555 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4556 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4557}
4558
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004559/// \brief Recurses in pointer/array types until it finds an objc retainable
4560/// type and returns its ownership.
4561Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4562 while (!T.isNull()) {
4563 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4564 return T.getObjCLifetime();
4565 if (T->isArrayType())
4566 T = getBaseElementType(T);
4567 else if (const PointerType *PT = T->getAs<PointerType>())
4568 T = PT->getPointeeType();
4569 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004570 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004571 else
4572 break;
4573 }
4574
4575 return Qualifiers::OCL_None;
4576}
4577
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004578static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4579 // Incomplete enum types are not treated as integer types.
4580 // FIXME: In C++, enum types are never integer types.
4581 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4582 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004583 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004584}
4585
Mike Stump11289f42009-09-09 15:08:12 +00004586/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004587/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004588/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004589int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004590 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4591 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004592
4593 // Unwrap enums to their underlying type.
4594 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4595 LHSC = getIntegerTypeForEnum(ET);
4596 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4597 RHSC = getIntegerTypeForEnum(ET);
4598
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004599 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004600
Chris Lattner76a00cf2008-04-06 22:59:24 +00004601 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4602 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004603
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004604 unsigned LHSRank = getIntegerRank(LHSC);
4605 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004606
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004607 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4608 if (LHSRank == RHSRank) return 0;
4609 return LHSRank > RHSRank ? 1 : -1;
4610 }
Mike Stump11289f42009-09-09 15:08:12 +00004611
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004612 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4613 if (LHSUnsigned) {
4614 // If the unsigned [LHS] type is larger, return it.
4615 if (LHSRank >= RHSRank)
4616 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004617
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004618 // If the signed type can represent all values of the unsigned type, it
4619 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004620 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004621 return -1;
4622 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004623
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004624 // If the unsigned [RHS] type is larger, return it.
4625 if (RHSRank >= LHSRank)
4626 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004627
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004628 // If the signed type can represent all values of the unsigned type, it
4629 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004630 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004631 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004632}
Anders Carlsson98f07902007-08-17 05:31:46 +00004633
Mike Stump11289f42009-09-09 15:08:12 +00004634// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004635QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004636 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004637 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004638 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004639
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004640 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004641
Anders Carlsson98f07902007-08-17 05:31:46 +00004642 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004643 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004644 // int flags;
4645 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004646 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004647 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004648 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004649 FieldTypes[3] = LongTy;
4650
Anders Carlsson98f07902007-08-17 05:31:46 +00004651 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004652 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004653 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004654 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004655 SourceLocation(), nullptr,
4656 FieldTypes[i], /*TInfo=*/nullptr,
4657 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004658 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004659 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004660 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004661 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004662 }
4663
Douglas Gregord5058122010-02-11 01:19:42 +00004664 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004665 }
Mike Stump11289f42009-09-09 15:08:12 +00004666
Anders Carlsson98f07902007-08-17 05:31:46 +00004667 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004668}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004669
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004670QualType ASTContext::getObjCSuperType() const {
4671 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004672 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004673 TUDecl->addDecl(ObjCSuperTypeDecl);
4674 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4675 }
4676 return ObjCSuperType;
4677}
4678
Douglas Gregor512b0772009-04-23 22:29:11 +00004679void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004680 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004681 assert(Rec && "Invalid CFConstantStringType");
4682 CFConstantStringTypeDecl = Rec->getDecl();
4683}
4684
Jay Foad39c79802011-01-12 09:06:06 +00004685QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004686 if (BlockDescriptorType)
4687 return getTagDeclType(BlockDescriptorType);
4688
Alp Toker2dea15b2013-12-17 01:22:38 +00004689 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004690 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004691 RD = buildImplicitRecord("__block_descriptor");
4692 RD->startDefinition();
4693
Mike Stumpd0153282009-10-20 02:12:22 +00004694 QualType FieldTypes[] = {
4695 UnsignedLongTy,
4696 UnsignedLongTy,
4697 };
4698
Craig Topperd6d31ac2013-07-15 08:24:27 +00004699 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004700 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004701 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004702 };
4703
4704 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004705 FieldDecl *Field = FieldDecl::Create(
4706 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004707 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4708 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004709 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004710 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004711 }
4712
Alp Toker2dea15b2013-12-17 01:22:38 +00004713 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004714
Alp Toker2dea15b2013-12-17 01:22:38 +00004715 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004716
4717 return getTagDeclType(BlockDescriptorType);
4718}
4719
Jay Foad39c79802011-01-12 09:06:06 +00004720QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004721 if (BlockDescriptorExtendedType)
4722 return getTagDeclType(BlockDescriptorExtendedType);
4723
Alp Toker2dea15b2013-12-17 01:22:38 +00004724 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004725 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004726 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4727 RD->startDefinition();
4728
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004729 QualType FieldTypes[] = {
4730 UnsignedLongTy,
4731 UnsignedLongTy,
4732 getPointerType(VoidPtrTy),
4733 getPointerType(VoidPtrTy)
4734 };
4735
Craig Topperd6d31ac2013-07-15 08:24:27 +00004736 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004737 "reserved",
4738 "Size",
4739 "CopyFuncPtr",
4740 "DestroyFuncPtr"
4741 };
4742
4743 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004744 FieldDecl *Field = FieldDecl::Create(
4745 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004746 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4747 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004748 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004749 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004750 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004751 }
4752
Alp Toker2dea15b2013-12-17 01:22:38 +00004753 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004754
Alp Toker2dea15b2013-12-17 01:22:38 +00004755 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004756 return getTagDeclType(BlockDescriptorExtendedType);
4757}
4758
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004759/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4760/// requires copy/dispose. Note that this must match the logic
4761/// in buildByrefHelpers.
4762bool ASTContext::BlockRequiresCopying(QualType Ty,
4763 const VarDecl *D) {
4764 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4765 const Expr *copyExpr = getBlockVarCopyInits(D);
4766 if (!copyExpr && record->hasTrivialDestructor()) return false;
4767
Mike Stump94967902009-10-21 18:16:27 +00004768 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004769 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004770
4771 if (!Ty->isObjCRetainableType()) return false;
4772
4773 Qualifiers qs = Ty.getQualifiers();
4774
4775 // If we have lifetime, that dominates.
4776 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4777 assert(getLangOpts().ObjCAutoRefCount);
4778
4779 switch (lifetime) {
4780 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4781
4782 // These are just bits as far as the runtime is concerned.
4783 case Qualifiers::OCL_ExplicitNone:
4784 case Qualifiers::OCL_Autoreleasing:
4785 return false;
4786
4787 // Tell the runtime that this is ARC __weak, called by the
4788 // byref routines.
4789 case Qualifiers::OCL_Weak:
4790 // ARC __strong __block variables need to be retained.
4791 case Qualifiers::OCL_Strong:
4792 return true;
4793 }
4794 llvm_unreachable("fell out of lifetime switch!");
4795 }
4796 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4797 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004798}
4799
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004800bool ASTContext::getByrefLifetime(QualType Ty,
4801 Qualifiers::ObjCLifetime &LifeTime,
4802 bool &HasByrefExtendedLayout) const {
4803
4804 if (!getLangOpts().ObjC1 ||
4805 getLangOpts().getGC() != LangOptions::NonGC)
4806 return false;
4807
4808 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004809 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004810 HasByrefExtendedLayout = true;
4811 LifeTime = Qualifiers::OCL_None;
4812 }
4813 else if (getLangOpts().ObjCAutoRefCount)
4814 LifeTime = Ty.getObjCLifetime();
4815 // MRR.
4816 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4817 LifeTime = Qualifiers::OCL_ExplicitNone;
4818 else
4819 LifeTime = Qualifiers::OCL_None;
4820 return true;
4821}
4822
Douglas Gregorbab8a962011-09-08 01:46:34 +00004823TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4824 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004825 ObjCInstanceTypeDecl =
4826 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004827 return ObjCInstanceTypeDecl;
4828}
4829
Anders Carlsson18acd442007-10-29 06:33:42 +00004830// This returns true if a type has been typedefed to BOOL:
4831// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004832static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004833 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004834 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4835 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004836
Anders Carlssond8499822007-10-29 05:01:08 +00004837 return false;
4838}
4839
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004840/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004841/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004842CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004843 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4844 return CharUnits::Zero();
4845
Ken Dyck40775002010-01-11 17:06:35 +00004846 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004847
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004848 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004849 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004850 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004851 // Treat arrays as pointers, since that's how they're passed in.
4852 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004853 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004854 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004855}
4856
Hans Wennborg56fc62b2014-07-17 20:25:23 +00004857bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4858 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4859 VD->getType()->isIntegralOrEnumerationType() &&
4860 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
4861}
4862
Ken Dyck40775002010-01-11 17:06:35 +00004863static inline
4864std::string charUnitsToString(const CharUnits &CU) {
4865 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004866}
4867
John McCall351762c2011-02-07 10:33:21 +00004868/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004869/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004870std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4871 std::string S;
4872
David Chisnall950a9512009-11-17 19:33:30 +00004873 const BlockDecl *Decl = Expr->getBlockDecl();
4874 QualType BlockTy =
4875 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4876 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004877 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004878 getObjCEncodingForMethodParameter(
4879 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4880 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004881 else
Alp Toker314cc812014-01-25 16:55:45 +00004882 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004883 // Compute size of all parameters.
4884 // Start with computing size of a pointer in number of bytes.
4885 // FIXME: There might(should) be a better way of doing this computation!
4886 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004887 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4888 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004889 for (auto PI : Decl->params()) {
4890 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004891 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004892 if (sz.isZero())
4893 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004894 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004895 ParmOffset += sz;
4896 }
4897 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004898 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004899 // Block pointer and offset.
4900 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004901
4902 // Argument types.
4903 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004904 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004905 QualType PType = PVDecl->getOriginalType();
4906 if (const ArrayType *AT =
4907 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4908 // Use array's original type only if it has known number of
4909 // elements.
4910 if (!isa<ConstantArrayType>(AT))
4911 PType = PVDecl->getType();
4912 } else if (PType->isFunctionType())
4913 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004914 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004915 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4916 S, true /*Extended*/);
4917 else
4918 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004919 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004920 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004921 }
John McCall351762c2011-02-07 10:33:21 +00004922
4923 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004924}
4925
Douglas Gregora9d84932011-05-27 01:19:52 +00004926bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004927 std::string& S) {
4928 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004929 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004930 CharUnits ParmOffset;
4931 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004932 for (auto PI : Decl->params()) {
4933 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004934 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004935 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004936 continue;
4937
David Chisnall50e4eba2010-12-30 14:05:53 +00004938 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004939 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004940 ParmOffset += sz;
4941 }
4942 S += charUnitsToString(ParmOffset);
4943 ParmOffset = CharUnits::Zero();
4944
4945 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004946 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004947 QualType PType = PVDecl->getOriginalType();
4948 if (const ArrayType *AT =
4949 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4950 // Use array's original type only if it has known number of
4951 // elements.
4952 if (!isa<ConstantArrayType>(AT))
4953 PType = PVDecl->getType();
4954 } else if (PType->isFunctionType())
4955 PType = PVDecl->getType();
4956 getObjCEncodingForType(PType, S);
4957 S += charUnitsToString(ParmOffset);
4958 ParmOffset += getObjCEncodingTypeSize(PType);
4959 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004960
4961 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004962}
4963
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004964/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4965/// method parameter or return type. If Extended, include class names and
4966/// block object types.
4967void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4968 QualType T, std::string& S,
4969 bool Extended) const {
4970 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4971 getObjCEncodingForTypeQualifier(QT, S);
4972 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00004973 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004974 true /*OutermostType*/,
4975 false /*EncodingProperty*/,
4976 false /*StructField*/,
4977 Extended /*EncodeBlockParameters*/,
4978 Extended /*EncodeClassNames*/);
4979}
4980
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004981/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004982/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004983bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004984 std::string& S,
4985 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004986 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004987 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004988 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4989 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004990 // Compute size of all parameters.
4991 // Start with computing size of a pointer in number of bytes.
4992 // FIXME: There might(should) be a better way of doing this computation!
4993 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004994 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004995 // The first two arguments (self and _cmd) are pointers; account for
4996 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004997 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004998 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004999 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005000 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005001 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005002 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005003 continue;
5004
Ken Dyck40775002010-01-11 17:06:35 +00005005 assert (sz.isPositive() &&
5006 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005007 ParmOffset += sz;
5008 }
Ken Dyck40775002010-01-11 17:06:35 +00005009 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005010 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005011 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005012
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005013 // Argument types.
5014 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005015 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005016 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005017 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005018 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005019 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005020 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5021 // Use array's original type only if it has known number of
5022 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005023 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005024 PType = PVDecl->getType();
5025 } else if (PType->isFunctionType())
5026 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005027 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5028 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005029 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005030 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005031 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005032
5033 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005034}
5035
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005036ObjCPropertyImplDecl *
5037ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5038 const ObjCPropertyDecl *PD,
5039 const Decl *Container) const {
5040 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005041 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005042 if (const ObjCCategoryImplDecl *CID =
5043 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005044 for (auto *PID : CID->property_impls())
5045 if (PID->getPropertyDecl() == PD)
5046 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005047 } else {
5048 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5049 for (auto *PID : OID->property_impls())
5050 if (PID->getPropertyDecl() == PD)
5051 return PID;
5052 }
5053 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005054}
5055
Daniel Dunbar4932b362008-08-28 04:38:10 +00005056/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005057/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005058/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5059/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005060/// Property attributes are stored as a comma-delimited C string. The simple
5061/// attributes readonly and bycopy are encoded as single characters. The
5062/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5063/// encoded as single characters, followed by an identifier. Property types
5064/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005065/// these attributes are defined by the following enumeration:
5066/// @code
5067/// enum PropertyAttributes {
5068/// kPropertyReadOnly = 'R', // property is read-only.
5069/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5070/// kPropertyByref = '&', // property is a reference to the value last assigned
5071/// kPropertyDynamic = 'D', // property is dynamic
5072/// kPropertyGetter = 'G', // followed by getter selector name
5073/// kPropertySetter = 'S', // followed by setter selector name
5074/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005075/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005076/// kPropertyWeak = 'W' // 'weak' property
5077/// kPropertyStrong = 'P' // property GC'able
5078/// kPropertyNonAtomic = 'N' // property non-atomic
5079/// };
5080/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005081void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005082 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005083 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005084 // Collect information from the property implementation decl(s).
5085 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005086 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005087
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005088 if (ObjCPropertyImplDecl *PropertyImpDecl =
5089 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5090 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5091 Dynamic = true;
5092 else
5093 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005094 }
5095
5096 // FIXME: This is not very efficient.
5097 S = "T";
5098
5099 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005100 // GCC has some special rules regarding encoding of properties which
5101 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005102 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005103
5104 if (PD->isReadOnly()) {
5105 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005106 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5107 S += ",C";
5108 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5109 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005110 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5111 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005112 } else {
5113 switch (PD->getSetterKind()) {
5114 case ObjCPropertyDecl::Assign: break;
5115 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005116 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005117 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005118 }
5119 }
5120
5121 // It really isn't clear at all what this means, since properties
5122 // are "dynamic by default".
5123 if (Dynamic)
5124 S += ",D";
5125
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005126 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5127 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005128
Daniel Dunbar4932b362008-08-28 04:38:10 +00005129 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5130 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005131 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005132 }
5133
5134 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5135 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005136 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005137 }
5138
5139 if (SynthesizePID) {
5140 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5141 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005142 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005143 }
5144
5145 // FIXME: OBJCGC: weak & strong
5146}
5147
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005148/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005149/// Another legacy compatibility encoding: 32-bit longs are encoded as
5150/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005151/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5152///
5153void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005154 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005155 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005156 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005157 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005158 else
Jay Foad39c79802011-01-12 09:06:06 +00005159 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005160 PointeeTy = IntTy;
5161 }
5162 }
5163}
5164
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005165void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005166 const FieldDecl *Field,
5167 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005168 // We follow the behavior of gcc, expanding structures which are
5169 // directly pointed to, and expanding embedded structures. Note that
5170 // these rules are sufficient to prevent recursive encoding of the
5171 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005172 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005173 true /* outermost type */, false, false,
5174 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005175}
5176
Joe Groff98ac7d22014-07-07 22:25:15 +00005177void ASTContext::getObjCEncodingForPropertyType(QualType T,
5178 std::string& S) const {
5179 // Encode result type.
5180 // GCC has some special rules regarding encoding of properties which
5181 // closely resembles encoding of ivars.
5182 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5183 true /* outermost type */,
5184 true /* encoding property */);
5185}
5186
John McCall393a78d2012-12-20 02:45:14 +00005187static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5188 BuiltinType::Kind kind) {
5189 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005190 case BuiltinType::Void: return 'v';
5191 case BuiltinType::Bool: return 'B';
5192 case BuiltinType::Char_U:
5193 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005194 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005195 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005196 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005197 case BuiltinType::UInt: return 'I';
5198 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005199 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005200 case BuiltinType::UInt128: return 'T';
5201 case BuiltinType::ULongLong: return 'Q';
5202 case BuiltinType::Char_S:
5203 case BuiltinType::SChar: return 'c';
5204 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005205 case BuiltinType::WChar_S:
5206 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005207 case BuiltinType::Int: return 'i';
5208 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005209 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005210 case BuiltinType::LongLong: return 'q';
5211 case BuiltinType::Int128: return 't';
5212 case BuiltinType::Float: return 'f';
5213 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005214 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005215 case BuiltinType::NullPtr: return '*'; // like char*
5216
5217 case BuiltinType::Half:
5218 // FIXME: potentially need @encodes for these!
5219 return ' ';
5220
5221 case BuiltinType::ObjCId:
5222 case BuiltinType::ObjCClass:
5223 case BuiltinType::ObjCSel:
5224 llvm_unreachable("@encoding ObjC primitive type");
5225
5226 // OpenCL and placeholder types don't need @encodings.
5227 case BuiltinType::OCLImage1d:
5228 case BuiltinType::OCLImage1dArray:
5229 case BuiltinType::OCLImage1dBuffer:
5230 case BuiltinType::OCLImage2d:
5231 case BuiltinType::OCLImage2dArray:
5232 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005233 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005234 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005235 case BuiltinType::Dependent:
5236#define BUILTIN_TYPE(KIND, ID)
5237#define PLACEHOLDER_TYPE(KIND, ID) \
5238 case BuiltinType::KIND:
5239#include "clang/AST/BuiltinTypes.def"
5240 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005241 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005242 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005243}
5244
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005245static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5246 EnumDecl *Enum = ET->getDecl();
5247
5248 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5249 if (!Enum->isFixed())
5250 return 'i';
5251
5252 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005253 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5254 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005255}
5256
Jay Foad39c79802011-01-12 09:06:06 +00005257static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005258 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005259 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005260 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005261 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5262 // The GNU runtime requires more information; bitfields are encoded as b,
5263 // then the offset (in bits) of the first element, then the type of the
5264 // bitfield, then the size in bits. For example, in this structure:
5265 //
5266 // struct
5267 // {
5268 // int integer;
5269 // int flags:2;
5270 // };
5271 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5272 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5273 // information is not especially sensible, but we're stuck with it for
5274 // compatibility with GCC, although providing it breaks anything that
5275 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005276 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005277 const RecordDecl *RD = FD->getParent();
5278 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005279 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005280 if (const EnumType *ET = T->getAs<EnumType>())
5281 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005282 else {
5283 const BuiltinType *BT = T->castAs<BuiltinType>();
5284 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5285 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005286 }
Richard Smithcaf33902011-10-10 18:28:20 +00005287 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005288}
5289
Daniel Dunbar07d07852009-10-18 21:17:35 +00005290// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005291void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5292 bool ExpandPointedToStructures,
5293 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005294 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005295 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005296 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005297 bool StructField,
5298 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005299 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005300 bool EncodePointerToObjCTypedef,
5301 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005302 CanQualType CT = getCanonicalType(T);
5303 switch (CT->getTypeClass()) {
5304 case Type::Builtin:
5305 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005306 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005307 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005308 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5309 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5310 else
5311 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005312 return;
Mike Stump11289f42009-09-09 15:08:12 +00005313
John McCall393a78d2012-12-20 02:45:14 +00005314 case Type::Complex: {
5315 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005316 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005317 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005318 return;
5319 }
John McCall393a78d2012-12-20 02:45:14 +00005320
5321 case Type::Atomic: {
5322 const AtomicType *AT = T->castAs<AtomicType>();
5323 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005324 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005325 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005326 }
John McCall393a78d2012-12-20 02:45:14 +00005327
5328 // encoding for pointer or reference types.
5329 case Type::Pointer:
5330 case Type::LValueReference:
5331 case Type::RValueReference: {
5332 QualType PointeeTy;
5333 if (isa<PointerType>(CT)) {
5334 const PointerType *PT = T->castAs<PointerType>();
5335 if (PT->isObjCSelType()) {
5336 S += ':';
5337 return;
5338 }
5339 PointeeTy = PT->getPointeeType();
5340 } else {
5341 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5342 }
5343
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005344 bool isReadOnly = false;
5345 // For historical/compatibility reasons, the read-only qualifier of the
5346 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5347 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005348 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005349 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005350 if (OutermostType && T.isConstQualified()) {
5351 isReadOnly = true;
5352 S += 'r';
5353 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005354 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005355 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005356 while (P->getAs<PointerType>())
5357 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005358 if (P.isConstQualified()) {
5359 isReadOnly = true;
5360 S += 'r';
5361 }
5362 }
5363 if (isReadOnly) {
5364 // Another legacy compatibility encoding. Some ObjC qualifier and type
5365 // combinations need to be rearranged.
5366 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005367 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005368 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005369 }
Mike Stump11289f42009-09-09 15:08:12 +00005370
Anders Carlssond8499822007-10-29 05:01:08 +00005371 if (PointeeTy->isCharType()) {
5372 // char pointer types should be encoded as '*' unless it is a
5373 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005374 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005375 S += '*';
5376 return;
5377 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005378 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005379 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5380 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5381 S += '#';
5382 return;
5383 }
5384 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5385 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5386 S += '@';
5387 return;
5388 }
5389 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005390 }
Anders Carlssond8499822007-10-29 05:01:08 +00005391 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005392 getLegacyIntegralTypeEncoding(PointeeTy);
5393
Mike Stump11289f42009-09-09 15:08:12 +00005394 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005395 nullptr, false, false, false, false, false, false,
5396 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005397 return;
5398 }
John McCall393a78d2012-12-20 02:45:14 +00005399
5400 case Type::ConstantArray:
5401 case Type::IncompleteArray:
5402 case Type::VariableArray: {
5403 const ArrayType *AT = cast<ArrayType>(CT);
5404
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005405 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005406 // Incomplete arrays are encoded as a pointer to the array element.
5407 S += '^';
5408
Mike Stump11289f42009-09-09 15:08:12 +00005409 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005410 false, ExpandStructures, FD);
5411 } else {
5412 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005413
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005414 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5415 S += llvm::utostr(CAT->getSize().getZExtValue());
5416 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005417 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005418 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5419 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005420 S += '0';
5421 }
Mike Stump11289f42009-09-09 15:08:12 +00005422
5423 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005424 false, ExpandStructures, FD,
5425 false, false, false, false, false, false,
5426 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005427 S += ']';
5428 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005429 return;
5430 }
Mike Stump11289f42009-09-09 15:08:12 +00005431
John McCall393a78d2012-12-20 02:45:14 +00005432 case Type::FunctionNoProto:
5433 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005434 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005435 return;
Mike Stump11289f42009-09-09 15:08:12 +00005436
John McCall393a78d2012-12-20 02:45:14 +00005437 case Type::Record: {
5438 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005439 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005440 // Anonymous structures print as '?'
5441 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5442 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005443 if (ClassTemplateSpecializationDecl *Spec
5444 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5445 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005446 llvm::raw_string_ostream OS(S);
5447 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005448 TemplateArgs.data(),
5449 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005450 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005451 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005452 } else {
5453 S += '?';
5454 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005455 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005456 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005457 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005458 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005459 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005460 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005461 if (FD) {
5462 S += '"';
5463 S += Field->getNameAsString();
5464 S += '"';
5465 }
Mike Stump11289f42009-09-09 15:08:12 +00005466
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005467 // Special case bit-fields.
5468 if (Field->isBitField()) {
5469 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005470 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005471 } else {
5472 QualType qt = Field->getType();
5473 getLegacyIntegralTypeEncoding(qt);
5474 getObjCEncodingForTypeImpl(qt, S, false, true,
5475 FD, /*OutermostType*/false,
5476 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005477 /*StructField*/true,
5478 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005479 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005480 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005481 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005482 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005483 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005484 return;
5485 }
Mike Stump11289f42009-09-09 15:08:12 +00005486
John McCall393a78d2012-12-20 02:45:14 +00005487 case Type::BlockPointer: {
5488 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005489 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005490 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005491 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005492
5493 S += '<';
5494 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005495 getObjCEncodingForTypeImpl(
5496 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5497 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005498 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5499 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005500 // Block self
5501 S += "@?";
5502 // Block parameters
5503 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005504 for (const auto &I : FPT->param_types())
5505 getObjCEncodingForTypeImpl(
5506 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5507 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005508 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5509 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005510 }
5511 S += '>';
5512 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005513 return;
5514 }
Mike Stump11289f42009-09-09 15:08:12 +00005515
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005516 case Type::ObjCObject: {
5517 // hack to match legacy encoding of *id and *Class
5518 QualType Ty = getObjCObjectPointerType(CT);
5519 if (Ty->isObjCIdType()) {
5520 S += "{objc_object=}";
5521 return;
5522 }
5523 else if (Ty->isObjCClassType()) {
5524 S += "{objc_class=}";
5525 return;
5526 }
5527 }
5528
John McCall393a78d2012-12-20 02:45:14 +00005529 case Type::ObjCInterface: {
5530 // Ignore protocol qualifiers when mangling at this level.
5531 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005532
John McCall393a78d2012-12-20 02:45:14 +00005533 // The assumption seems to be that this assert will succeed
5534 // because nested levels will have filtered out 'id' and 'Class'.
5535 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005536 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005537 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005538 S += '{';
5539 const IdentifierInfo *II = OI->getIdentifier();
5540 S += II->getName();
5541 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005542 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005543 DeepCollectObjCIvars(OI, true, Ivars);
5544 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005545 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005546 if (Field->isBitField())
5547 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005548 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005549 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5550 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005551 EncodePointerToObjCTypedef,
5552 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005553 }
5554 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005555 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005556 }
Mike Stump11289f42009-09-09 15:08:12 +00005557
John McCall393a78d2012-12-20 02:45:14 +00005558 case Type::ObjCObjectPointer: {
5559 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005560 if (OPT->isObjCIdType()) {
5561 S += '@';
5562 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005563 }
Mike Stump11289f42009-09-09 15:08:12 +00005564
Steve Narofff0c86112009-10-28 22:03:49 +00005565 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5566 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5567 // Since this is a binary compatibility issue, need to consult with runtime
5568 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005569 S += '#';
5570 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005571 }
Mike Stump11289f42009-09-09 15:08:12 +00005572
Chris Lattnere7cabb92009-07-13 00:10:46 +00005573 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005574 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005575 ExpandPointedToStructures,
5576 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005577 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005578 // Note that we do extended encoding of protocol qualifer list
5579 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005580 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005581 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005582 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005583 S += I->getNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005584 S += '>';
5585 }
5586 S += '"';
5587 }
5588 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005589 }
Mike Stump11289f42009-09-09 15:08:12 +00005590
Chris Lattnere7cabb92009-07-13 00:10:46 +00005591 QualType PointeeTy = OPT->getPointeeType();
5592 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005593 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5594 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005595 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005596 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005597 // {...};
5598 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005599 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005600 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005601 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5602 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5603 DeepCollectObjCIvars(OI, true, Ivars);
5604 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5605 if (cast<FieldDecl>(Ivars[i]) == FD) {
5606 S += '{';
5607 S += OI->getIdentifier()->getName();
5608 S += '}';
5609 return;
5610 }
5611 }
5612 }
Mike Stump11289f42009-09-09 15:08:12 +00005613 getObjCEncodingForTypeImpl(PointeeTy, S,
5614 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005615 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005616 false, false, false, false, false,
5617 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005618 return;
5619 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005620
5621 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005622 if (OPT->getInterfaceDecl() &&
5623 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005624 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005625 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Aaron Ballman83731462014-03-17 16:14:00 +00005626 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005627 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005628 S += I->getNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005629 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005630 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005631 S += '"';
5632 }
5633 return;
5634 }
Mike Stump11289f42009-09-09 15:08:12 +00005635
John McCalla9e6e8d2010-05-17 23:56:34 +00005636 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005637 // FIXME: we shoul do better than that. 'M' is available.
5638 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005639 // This matches gcc's encoding, even though technically it is insufficient.
5640 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005641 case Type::Vector:
5642 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005643 // Until we have a coherent encoding of these three types, issue warning.
5644 { if (NotEncodedT)
5645 *NotEncodedT = T;
5646 return;
5647 }
5648
5649 // We could see an undeduced auto type here during error recovery.
5650 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005651 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005652 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005653
Richard Smith27d807c2013-04-30 13:56:41 +00005654
John McCall393a78d2012-12-20 02:45:14 +00005655#define ABSTRACT_TYPE(KIND, BASE)
5656#define TYPE(KIND, BASE)
5657#define DEPENDENT_TYPE(KIND, BASE) \
5658 case Type::KIND:
5659#define NON_CANONICAL_TYPE(KIND, BASE) \
5660 case Type::KIND:
5661#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5662 case Type::KIND:
5663#include "clang/AST/TypeNodes.def"
5664 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005665 }
John McCall393a78d2012-12-20 02:45:14 +00005666 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005667}
5668
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005669void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5670 std::string &S,
5671 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005672 bool includeVBases,
5673 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005674 assert(RDecl && "Expected non-null RecordDecl");
5675 assert(!RDecl->isUnion() && "Should not be called for unions");
5676 if (!RDecl->getDefinition())
5677 return;
5678
5679 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5680 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5681 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5682
5683 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005684 for (const auto &BI : CXXRec->bases()) {
5685 if (!BI.isVirtual()) {
5686 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005687 if (base->isEmpty())
5688 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005689 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005690 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5691 std::make_pair(offs, base));
5692 }
5693 }
5694 }
5695
5696 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005697 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005698 uint64_t offs = layout.getFieldOffset(i);
5699 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005700 std::make_pair(offs, Field));
5701 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005702 }
5703
5704 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005705 for (const auto &BI : CXXRec->vbases()) {
5706 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005707 if (base->isEmpty())
5708 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005709 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005710 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5711 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005712 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5713 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005714 }
5715 }
5716
5717 CharUnits size;
5718 if (CXXRec) {
5719 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5720 } else {
5721 size = layout.getSize();
5722 }
5723
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005724#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005725 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005726#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005727 std::multimap<uint64_t, NamedDecl *>::iterator
5728 CurLayObj = FieldOrBaseOffsets.begin();
5729
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005730 if (CXXRec && CXXRec->isDynamicClass() &&
5731 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005732 if (FD) {
5733 S += "\"_vptr$";
5734 std::string recname = CXXRec->getNameAsString();
5735 if (recname.empty()) recname = "?";
5736 S += recname;
5737 S += '"';
5738 }
5739 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005740#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005741 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005742#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005743 }
5744
5745 if (!RDecl->hasFlexibleArrayMember()) {
5746 // Mark the end of the structure.
5747 uint64_t offs = toBits(size);
5748 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005749 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005750 }
5751
5752 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005753#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005754 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005755 if (CurOffs < CurLayObj->first) {
5756 uint64_t padding = CurLayObj->first - CurOffs;
5757 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5758 // packing/alignment of members is different that normal, in which case
5759 // the encoding will be out-of-sync with the real layout.
5760 // If the runtime switches to just consider the size of types without
5761 // taking into account alignment, we could make padding explicit in the
5762 // encoding (e.g. using arrays of chars). The encoding strings would be
5763 // longer then though.
5764 CurOffs += padding;
5765 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005766#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005767
5768 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005769 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005770 break; // reached end of structure.
5771
5772 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5773 // We expand the bases without their virtual bases since those are going
5774 // in the initial structure. Note that this differs from gcc which
5775 // expands virtual bases each time one is encountered in the hierarchy,
5776 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005777 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5778 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005779 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005780#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005781 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005782#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005783 } else {
5784 FieldDecl *field = cast<FieldDecl>(dcl);
5785 if (FD) {
5786 S += '"';
5787 S += field->getNameAsString();
5788 S += '"';
5789 }
5790
5791 if (field->isBitField()) {
5792 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005793#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005794 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005795#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005796 } else {
5797 QualType qt = field->getType();
5798 getLegacyIntegralTypeEncoding(qt);
5799 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5800 /*OutermostType*/false,
5801 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005802 /*StructField*/true,
5803 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005804#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005805 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005806#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005807 }
5808 }
5809 }
5810}
5811
Mike Stump11289f42009-09-09 15:08:12 +00005812void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005813 std::string& S) const {
5814 if (QT & Decl::OBJC_TQ_In)
5815 S += 'n';
5816 if (QT & Decl::OBJC_TQ_Inout)
5817 S += 'N';
5818 if (QT & Decl::OBJC_TQ_Out)
5819 S += 'o';
5820 if (QT & Decl::OBJC_TQ_Bycopy)
5821 S += 'O';
5822 if (QT & Decl::OBJC_TQ_Byref)
5823 S += 'R';
5824 if (QT & Decl::OBJC_TQ_Oneway)
5825 S += 'V';
5826}
5827
Douglas Gregor3ea72692011-08-12 05:46:01 +00005828TypedefDecl *ASTContext::getObjCIdDecl() const {
5829 if (!ObjCIdDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005830 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0);
Douglas Gregor3ea72692011-08-12 05:46:01 +00005831 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005832 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005833 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005834 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005835}
5836
Douglas Gregor52e02802011-08-12 06:17:30 +00005837TypedefDecl *ASTContext::getObjCSelDecl() const {
5838 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005839 QualType T = getPointerType(ObjCBuiltinSelTy);
5840 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005841 }
5842 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005843}
5844
Douglas Gregor0a586182011-08-12 05:59:41 +00005845TypedefDecl *ASTContext::getObjCClassDecl() const {
5846 if (!ObjCClassDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005847 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0);
Douglas Gregor0a586182011-08-12 05:59:41 +00005848 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005849 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005850 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005851 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005852}
5853
Douglas Gregord53ae832012-01-17 18:09:05 +00005854ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5855 if (!ObjCProtocolClassDecl) {
5856 ObjCProtocolClassDecl
5857 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5858 SourceLocation(),
5859 &Idents.get("Protocol"),
Craig Topper36250ad2014-05-12 05:36:57 +00005860 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00005861 SourceLocation(), true);
5862 }
5863
5864 return ObjCProtocolClassDecl;
5865}
5866
Meador Inge5d3fb222012-06-16 03:34:49 +00005867//===----------------------------------------------------------------------===//
5868// __builtin_va_list Construction Functions
5869//===----------------------------------------------------------------------===//
5870
5871static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5872 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005873 QualType T = Context->getPointerType(Context->CharTy);
5874 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005875}
5876
5877static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5878 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005879 QualType T = Context->getPointerType(Context->VoidTy);
5880 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005881}
5882
Tim Northover9bb857a2013-01-31 12:13:10 +00005883static TypedefDecl *
5884CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005885 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005886 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005887 if (Context->getLangOpts().CPlusPlus) {
5888 // namespace std { struct __va_list {
5889 NamespaceDecl *NS;
5890 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5891 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00005892 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00005893 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00005894 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00005895 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005896 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005897 }
5898
5899 VaListTagDecl->startDefinition();
5900
5901 const size_t NumFields = 5;
5902 QualType FieldTypes[NumFields];
5903 const char *FieldNames[NumFields];
5904
5905 // void *__stack;
5906 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5907 FieldNames[0] = "__stack";
5908
5909 // void *__gr_top;
5910 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5911 FieldNames[1] = "__gr_top";
5912
5913 // void *__vr_top;
5914 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5915 FieldNames[2] = "__vr_top";
5916
5917 // int __gr_offs;
5918 FieldTypes[3] = Context->IntTy;
5919 FieldNames[3] = "__gr_offs";
5920
5921 // int __vr_offs;
5922 FieldTypes[4] = Context->IntTy;
5923 FieldNames[4] = "__vr_offs";
5924
5925 // Create fields
5926 for (unsigned i = 0; i < NumFields; ++i) {
5927 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5928 VaListTagDecl,
5929 SourceLocation(),
5930 SourceLocation(),
5931 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005932 FieldTypes[i], /*TInfo=*/nullptr,
5933 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00005934 /*Mutable=*/false,
5935 ICIS_NoInit);
5936 Field->setAccess(AS_public);
5937 VaListTagDecl->addDecl(Field);
5938 }
5939 VaListTagDecl->completeDefinition();
5940 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5941 Context->VaListTagTy = VaListTagType;
5942
5943 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005944 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005945}
5946
Meador Inge5d3fb222012-06-16 03:34:49 +00005947static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5948 // typedef struct __va_list_tag {
5949 RecordDecl *VaListTagDecl;
5950
Alp Toker2dea15b2013-12-17 01:22:38 +00005951 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005952 VaListTagDecl->startDefinition();
5953
5954 const size_t NumFields = 5;
5955 QualType FieldTypes[NumFields];
5956 const char *FieldNames[NumFields];
5957
5958 // unsigned char gpr;
5959 FieldTypes[0] = Context->UnsignedCharTy;
5960 FieldNames[0] = "gpr";
5961
5962 // unsigned char fpr;
5963 FieldTypes[1] = Context->UnsignedCharTy;
5964 FieldNames[1] = "fpr";
5965
5966 // unsigned short reserved;
5967 FieldTypes[2] = Context->UnsignedShortTy;
5968 FieldNames[2] = "reserved";
5969
5970 // void* overflow_arg_area;
5971 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5972 FieldNames[3] = "overflow_arg_area";
5973
5974 // void* reg_save_area;
5975 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5976 FieldNames[4] = "reg_save_area";
5977
5978 // Create fields
5979 for (unsigned i = 0; i < NumFields; ++i) {
5980 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5981 SourceLocation(),
5982 SourceLocation(),
5983 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005984 FieldTypes[i], /*TInfo=*/nullptr,
5985 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00005986 /*Mutable=*/false,
5987 ICIS_NoInit);
5988 Field->setAccess(AS_public);
5989 VaListTagDecl->addDecl(Field);
5990 }
5991 VaListTagDecl->completeDefinition();
5992 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005993 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005994
5995 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005996 TypedefDecl *VaListTagTypedefDecl =
5997 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5998
Meador Inge5d3fb222012-06-16 03:34:49 +00005999 QualType VaListTagTypedefType =
6000 Context->getTypedefType(VaListTagTypedefDecl);
6001
6002 // typedef __va_list_tag __builtin_va_list[1];
6003 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6004 QualType VaListTagArrayType
6005 = Context->getConstantArrayType(VaListTagTypedefType,
6006 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006007 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006008}
6009
6010static TypedefDecl *
6011CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6012 // typedef struct __va_list_tag {
6013 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006014 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006015 VaListTagDecl->startDefinition();
6016
6017 const size_t NumFields = 4;
6018 QualType FieldTypes[NumFields];
6019 const char *FieldNames[NumFields];
6020
6021 // unsigned gp_offset;
6022 FieldTypes[0] = Context->UnsignedIntTy;
6023 FieldNames[0] = "gp_offset";
6024
6025 // unsigned fp_offset;
6026 FieldTypes[1] = Context->UnsignedIntTy;
6027 FieldNames[1] = "fp_offset";
6028
6029 // void* overflow_arg_area;
6030 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6031 FieldNames[2] = "overflow_arg_area";
6032
6033 // void* reg_save_area;
6034 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6035 FieldNames[3] = "reg_save_area";
6036
6037 // Create fields
6038 for (unsigned i = 0; i < NumFields; ++i) {
6039 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6040 VaListTagDecl,
6041 SourceLocation(),
6042 SourceLocation(),
6043 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006044 FieldTypes[i], /*TInfo=*/nullptr,
6045 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006046 /*Mutable=*/false,
6047 ICIS_NoInit);
6048 Field->setAccess(AS_public);
6049 VaListTagDecl->addDecl(Field);
6050 }
6051 VaListTagDecl->completeDefinition();
6052 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006053 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006054
6055 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006056 TypedefDecl *VaListTagTypedefDecl =
6057 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6058
Meador Inge5d3fb222012-06-16 03:34:49 +00006059 QualType VaListTagTypedefType =
6060 Context->getTypedefType(VaListTagTypedefDecl);
6061
6062 // typedef __va_list_tag __builtin_va_list[1];
6063 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6064 QualType VaListTagArrayType
6065 = Context->getConstantArrayType(VaListTagTypedefType,
6066 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006067 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006068}
6069
6070static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6071 // typedef int __builtin_va_list[4];
6072 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6073 QualType IntArrayType
6074 = Context->getConstantArrayType(Context->IntTy,
6075 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006076 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006077}
6078
Logan Chien57086ce2012-10-10 06:56:20 +00006079static TypedefDecl *
6080CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006081 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006082 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006083 if (Context->getLangOpts().CPlusPlus) {
6084 // namespace std { struct __va_list {
6085 NamespaceDecl *NS;
6086 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6087 Context->getTranslationUnitDecl(),
6088 /*Inline*/false, SourceLocation(),
6089 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006090 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006091 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006092 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006093 }
6094
6095 VaListDecl->startDefinition();
6096
6097 // void * __ap;
6098 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6099 VaListDecl,
6100 SourceLocation(),
6101 SourceLocation(),
6102 &Context->Idents.get("__ap"),
6103 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006104 /*TInfo=*/nullptr,
6105 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006106 /*Mutable=*/false,
6107 ICIS_NoInit);
6108 Field->setAccess(AS_public);
6109 VaListDecl->addDecl(Field);
6110
6111 // };
6112 VaListDecl->completeDefinition();
6113
6114 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006115 QualType T = Context->getRecordType(VaListDecl);
6116 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006117}
6118
Ulrich Weigand47445072013-05-06 16:26:41 +00006119static TypedefDecl *
6120CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6121 // typedef struct __va_list_tag {
6122 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006123 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006124 VaListTagDecl->startDefinition();
6125
6126 const size_t NumFields = 4;
6127 QualType FieldTypes[NumFields];
6128 const char *FieldNames[NumFields];
6129
6130 // long __gpr;
6131 FieldTypes[0] = Context->LongTy;
6132 FieldNames[0] = "__gpr";
6133
6134 // long __fpr;
6135 FieldTypes[1] = Context->LongTy;
6136 FieldNames[1] = "__fpr";
6137
6138 // void *__overflow_arg_area;
6139 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6140 FieldNames[2] = "__overflow_arg_area";
6141
6142 // void *__reg_save_area;
6143 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6144 FieldNames[3] = "__reg_save_area";
6145
6146 // Create fields
6147 for (unsigned i = 0; i < NumFields; ++i) {
6148 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6149 VaListTagDecl,
6150 SourceLocation(),
6151 SourceLocation(),
6152 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006153 FieldTypes[i], /*TInfo=*/nullptr,
6154 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006155 /*Mutable=*/false,
6156 ICIS_NoInit);
6157 Field->setAccess(AS_public);
6158 VaListTagDecl->addDecl(Field);
6159 }
6160 VaListTagDecl->completeDefinition();
6161 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6162 Context->VaListTagTy = VaListTagType;
6163
6164 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006165 TypedefDecl *VaListTagTypedefDecl =
6166 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006167 QualType VaListTagTypedefType =
6168 Context->getTypedefType(VaListTagTypedefDecl);
6169
6170 // typedef __va_list_tag __builtin_va_list[1];
6171 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6172 QualType VaListTagArrayType
6173 = Context->getConstantArrayType(VaListTagTypedefType,
6174 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006175
Alp Toker56b5cc92013-12-15 10:36:26 +00006176 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006177}
6178
Meador Inge5d3fb222012-06-16 03:34:49 +00006179static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6180 TargetInfo::BuiltinVaListKind Kind) {
6181 switch (Kind) {
6182 case TargetInfo::CharPtrBuiltinVaList:
6183 return CreateCharPtrBuiltinVaListDecl(Context);
6184 case TargetInfo::VoidPtrBuiltinVaList:
6185 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006186 case TargetInfo::AArch64ABIBuiltinVaList:
6187 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006188 case TargetInfo::PowerABIBuiltinVaList:
6189 return CreatePowerABIBuiltinVaListDecl(Context);
6190 case TargetInfo::X86_64ABIBuiltinVaList:
6191 return CreateX86_64ABIBuiltinVaListDecl(Context);
6192 case TargetInfo::PNaClABIBuiltinVaList:
6193 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006194 case TargetInfo::AAPCSABIBuiltinVaList:
6195 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006196 case TargetInfo::SystemZBuiltinVaList:
6197 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006198 }
6199
6200 llvm_unreachable("Unhandled __builtin_va_list type kind");
6201}
6202
6203TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006204 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006205 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006206 assert(BuiltinVaListDecl->isImplicit());
6207 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006208
6209 return BuiltinVaListDecl;
6210}
6211
Meador Ingecfb60902012-07-01 15:57:25 +00006212QualType ASTContext::getVaListTagType() const {
6213 // Force the creation of VaListTagTy by building the __builtin_va_list
6214 // declaration.
6215 if (VaListTagTy.isNull())
6216 (void) getBuiltinVaListDecl();
6217
6218 return VaListTagTy;
6219}
6220
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006221void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006222 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006223 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006224
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006225 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006226}
6227
John McCalld28ae272009-12-02 08:04:21 +00006228/// \brief Retrieve the template name that corresponds to a non-empty
6229/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006230TemplateName
6231ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6232 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006233 unsigned size = End - Begin;
6234 assert(size > 1 && "set is not overloaded!");
6235
6236 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6237 size * sizeof(FunctionTemplateDecl*));
6238 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6239
6240 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006241 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006242 NamedDecl *D = *I;
6243 assert(isa<FunctionTemplateDecl>(D) ||
6244 (isa<UsingShadowDecl>(D) &&
6245 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6246 *Storage++ = D;
6247 }
6248
6249 return TemplateName(OT);
6250}
6251
Douglas Gregordc572a32009-03-30 22:58:21 +00006252/// \brief Retrieve the template name that represents a qualified
6253/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006254TemplateName
6255ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6256 bool TemplateKeyword,
6257 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006258 assert(NNS && "Missing nested-name-specifier in qualified template name");
6259
Douglas Gregorc42075a2010-02-04 18:10:26 +00006260 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006261 llvm::FoldingSetNodeID ID;
6262 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6263
Craig Topper36250ad2014-05-12 05:36:57 +00006264 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006265 QualifiedTemplateName *QTN =
6266 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6267 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006268 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6269 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006270 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6271 }
6272
6273 return TemplateName(QTN);
6274}
6275
6276/// \brief Retrieve the template name that represents a dependent
6277/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006278TemplateName
6279ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6280 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006281 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006282 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006283
6284 llvm::FoldingSetNodeID ID;
6285 DependentTemplateName::Profile(ID, NNS, Name);
6286
Craig Topper36250ad2014-05-12 05:36:57 +00006287 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006288 DependentTemplateName *QTN =
6289 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6290
6291 if (QTN)
6292 return TemplateName(QTN);
6293
6294 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6295 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006296 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6297 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006298 } else {
6299 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006300 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6301 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006302 DependentTemplateName *CheckQTN =
6303 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6304 assert(!CheckQTN && "Dependent type name canonicalization broken");
6305 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006306 }
6307
6308 DependentTemplateNames.InsertNode(QTN, InsertPos);
6309 return TemplateName(QTN);
6310}
6311
Douglas Gregor71395fa2009-11-04 00:56:37 +00006312/// \brief Retrieve the template name that represents a dependent
6313/// template name such as \c MetaFun::template operator+.
6314TemplateName
6315ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006316 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006317 assert((!NNS || NNS->isDependent()) &&
6318 "Nested name specifier must be dependent");
6319
6320 llvm::FoldingSetNodeID ID;
6321 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006322
6323 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006324 DependentTemplateName *QTN
6325 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006326
6327 if (QTN)
6328 return TemplateName(QTN);
6329
6330 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6331 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006332 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6333 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006334 } else {
6335 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006336 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6337 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006338
6339 DependentTemplateName *CheckQTN
6340 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6341 assert(!CheckQTN && "Dependent template name canonicalization broken");
6342 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006343 }
6344
6345 DependentTemplateNames.InsertNode(QTN, InsertPos);
6346 return TemplateName(QTN);
6347}
6348
Douglas Gregor5590be02011-01-15 06:45:20 +00006349TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006350ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6351 TemplateName replacement) const {
6352 llvm::FoldingSetNodeID ID;
6353 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006354
6355 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006356 SubstTemplateTemplateParmStorage *subst
6357 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6358
6359 if (!subst) {
6360 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6361 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6362 }
6363
6364 return TemplateName(subst);
6365}
6366
6367TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006368ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6369 const TemplateArgument &ArgPack) const {
6370 ASTContext &Self = const_cast<ASTContext &>(*this);
6371 llvm::FoldingSetNodeID ID;
6372 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006373
6374 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006375 SubstTemplateTemplateParmPackStorage *Subst
6376 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6377
6378 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006379 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006380 ArgPack.pack_size(),
6381 ArgPack.pack_begin());
6382 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6383 }
6384
6385 return TemplateName(Subst);
6386}
6387
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006388/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006389/// TargetInfo, produce the corresponding type. The unsigned @p Type
6390/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006391CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006392 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006393 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006394 case TargetInfo::SignedChar: return SignedCharTy;
6395 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006396 case TargetInfo::SignedShort: return ShortTy;
6397 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6398 case TargetInfo::SignedInt: return IntTy;
6399 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6400 case TargetInfo::SignedLong: return LongTy;
6401 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6402 case TargetInfo::SignedLongLong: return LongLongTy;
6403 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6404 }
6405
David Blaikie83d382b2011-09-23 05:06:16 +00006406 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006407}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006408
6409//===----------------------------------------------------------------------===//
6410// Type Predicates.
6411//===----------------------------------------------------------------------===//
6412
Fariborz Jahanian96207692009-02-18 21:49:28 +00006413/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6414/// garbage collection attribute.
6415///
John McCall553d45a2011-01-12 00:34:59 +00006416Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006417 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006418 return Qualifiers::GCNone;
6419
David Blaikiebbafb8a2012-03-11 07:00:24 +00006420 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006421 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6422
6423 // Default behaviour under objective-C's gc is for ObjC pointers
6424 // (or pointers to them) be treated as though they were declared
6425 // as __strong.
6426 if (GCAttrs == Qualifiers::GCNone) {
6427 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6428 return Qualifiers::Strong;
6429 else if (Ty->isPointerType())
6430 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6431 } else {
6432 // It's not valid to set GC attributes on anything that isn't a
6433 // pointer.
6434#ifndef NDEBUG
6435 QualType CT = Ty->getCanonicalTypeInternal();
6436 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6437 CT = AT->getElementType();
6438 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6439#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006440 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006441 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006442}
6443
Chris Lattner49af6a42008-04-07 06:51:04 +00006444//===----------------------------------------------------------------------===//
6445// Type Compatibility Testing
6446//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006447
Mike Stump11289f42009-09-09 15:08:12 +00006448/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006449/// compatible.
6450static bool areCompatVectorTypes(const VectorType *LHS,
6451 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006452 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006453 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006454 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006455}
6456
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006457bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6458 QualType SecondVec) {
6459 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6460 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6461
6462 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6463 return true;
6464
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006465 // Treat Neon vector types and most AltiVec vector types as if they are the
6466 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006467 const VectorType *First = FirstVec->getAs<VectorType>();
6468 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006469 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006470 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006471 First->getVectorKind() != VectorType::AltiVecPixel &&
6472 First->getVectorKind() != VectorType::AltiVecBool &&
6473 Second->getVectorKind() != VectorType::AltiVecPixel &&
6474 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006475 return true;
6476
6477 return false;
6478}
6479
Steve Naroff8e6aee52009-07-23 01:01:38 +00006480//===----------------------------------------------------------------------===//
6481// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6482//===----------------------------------------------------------------------===//
6483
6484/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6485/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006486bool
6487ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6488 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006489 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006490 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006491 for (auto *PI : rProto->protocols())
6492 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006493 return true;
6494 return false;
6495}
6496
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006497/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6498/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006499bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6500 QualType rhs) {
6501 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6502 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6503 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6504
Aaron Ballman83731462014-03-17 16:14:00 +00006505 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006506 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006507 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006508 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6509 match = true;
6510 break;
6511 }
6512 }
6513 if (!match)
6514 return false;
6515 }
6516 return true;
6517}
6518
Steve Naroff8e6aee52009-07-23 01:01:38 +00006519/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6520/// ObjCQualifiedIDType.
6521bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6522 bool compare) {
6523 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006524 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006525 lhs->isObjCIdType() || lhs->isObjCClassType())
6526 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006527 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006528 rhs->isObjCIdType() || rhs->isObjCClassType())
6529 return true;
6530
6531 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006532 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006533
Steve Naroff8e6aee52009-07-23 01:01:38 +00006534 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006535
Steve Naroff8e6aee52009-07-23 01:01:38 +00006536 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006537 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006538 // make sure we check the class hierarchy.
6539 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006540 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006541 // when comparing an id<P> on lhs with a static type on rhs,
6542 // see if static class implements all of id's protocols, directly or
6543 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006544 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006545 return false;
6546 }
6547 }
6548 // If there are no qualifiers and no interface, we have an 'id'.
6549 return true;
6550 }
Mike Stump11289f42009-09-09 15:08:12 +00006551 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006552 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006553 bool match = false;
6554
6555 // when comparing an id<P> on lhs with a static type on rhs,
6556 // see if static class implements all of id's protocols, directly or
6557 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006558 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006559 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6560 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6561 match = true;
6562 break;
6563 }
6564 }
Mike Stump11289f42009-09-09 15:08:12 +00006565 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006566 // make sure we check the class hierarchy.
6567 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006568 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006569 // when comparing an id<P> on lhs with a static type on rhs,
6570 // see if static class implements all of id's protocols, directly or
6571 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006572 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006573 match = true;
6574 break;
6575 }
6576 }
6577 }
6578 if (!match)
6579 return false;
6580 }
Mike Stump11289f42009-09-09 15:08:12 +00006581
Steve Naroff8e6aee52009-07-23 01:01:38 +00006582 return true;
6583 }
Mike Stump11289f42009-09-09 15:08:12 +00006584
Steve Naroff8e6aee52009-07-23 01:01:38 +00006585 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6586 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6587
Mike Stump11289f42009-09-09 15:08:12 +00006588 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006589 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006590 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006591 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006592 bool match = false;
6593
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006594 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006595 // see if static class implements all of id's protocols, directly or
6596 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006597 // First, lhs protocols in the qualifier list must be found, direct
6598 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006599 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006600 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6601 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6602 match = true;
6603 break;
6604 }
6605 }
6606 if (!match)
6607 return false;
6608 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006609
6610 // Static class's protocols, or its super class or category protocols
6611 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6612 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6613 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6614 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6615 // This is rather dubious but matches gcc's behavior. If lhs has
6616 // no type qualifier and its class has no static protocol(s)
6617 // assume that it is mismatch.
6618 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6619 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006620 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006621 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006622 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006623 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6624 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6625 match = true;
6626 break;
6627 }
6628 }
6629 if (!match)
6630 return false;
6631 }
6632 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006633 return true;
6634 }
6635 return false;
6636}
6637
Eli Friedman47f77112008-08-22 00:56:42 +00006638/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006639/// compatible for assignment from RHS to LHS. This handles validation of any
6640/// protocol qualifiers on the LHS or RHS.
6641///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006642bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6643 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006644 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6645 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6646
Steve Naroff1329fa02009-07-15 18:40:39 +00006647 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006648 if (LHS->isObjCUnqualifiedIdOrClass() ||
6649 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006650 return true;
6651
John McCall8b07ec22010-05-15 11:32:37 +00006652 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006653 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6654 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006655 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006656
6657 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6658 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6659 QualType(RHSOPT,0));
6660
John McCall8b07ec22010-05-15 11:32:37 +00006661 // If we have 2 user-defined types, fall into that path.
6662 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006663 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006664
Steve Naroff8e6aee52009-07-23 01:01:38 +00006665 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006666}
6667
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006668/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006669/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006670/// arguments in block literals. When passed as arguments, passing 'A*' where
6671/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6672/// not OK. For the return type, the opposite is not OK.
6673bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6674 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006675 const ObjCObjectPointerType *RHSOPT,
6676 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006677 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006678 return true;
6679
6680 if (LHSOPT->isObjCBuiltinType()) {
6681 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6682 }
6683
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006684 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006685 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6686 QualType(RHSOPT,0),
6687 false);
6688
6689 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6690 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6691 if (LHS && RHS) { // We have 2 user-defined types.
6692 if (LHS != RHS) {
6693 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006694 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006695 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006696 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006697 }
6698 else
6699 return true;
6700 }
6701 return false;
6702}
6703
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006704/// getIntersectionOfProtocols - This routine finds the intersection of set
6705/// of protocols inherited from two distinct objective-c pointer objects.
6706/// It is used to build composite qualifier list of the composite type of
6707/// the conditional expression involving two objective-c pointer objects.
6708static
6709void getIntersectionOfProtocols(ASTContext &Context,
6710 const ObjCObjectPointerType *LHSOPT,
6711 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006712 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006713
John McCall8b07ec22010-05-15 11:32:37 +00006714 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6715 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6716 assert(LHS->getInterface() && "LHS must have an interface base");
6717 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006718
6719 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6720 unsigned LHSNumProtocols = LHS->getNumProtocols();
6721 if (LHSNumProtocols > 0)
6722 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6723 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006724 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006725 Context.CollectInheritedProtocols(LHS->getInterface(),
6726 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006727 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6728 LHSInheritedProtocols.end());
6729 }
6730
6731 unsigned RHSNumProtocols = RHS->getNumProtocols();
6732 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006733 ObjCProtocolDecl **RHSProtocols =
6734 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006735 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6736 if (InheritedProtocolSet.count(RHSProtocols[i]))
6737 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006738 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006739 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006740 Context.CollectInheritedProtocols(RHS->getInterface(),
6741 RHSInheritedProtocols);
Craig Topperc6914d02014-08-25 04:15:02 +00006742 for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols)
6743 if (InheritedProtocolSet.count(ProtDecl))
6744 IntersectionOfProtocols.push_back(ProtDecl);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006745 }
6746}
6747
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006748/// areCommonBaseCompatible - Returns common base class of the two classes if
6749/// one found. Note that this is O'2 algorithm. But it will be called as the
6750/// last type comparison in a ?-exp of ObjC pointer types before a
6751/// warning is issued. So, its invokation is extremely rare.
6752QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006753 const ObjCObjectPointerType *Lptr,
6754 const ObjCObjectPointerType *Rptr) {
6755 const ObjCObjectType *LHS = Lptr->getObjectType();
6756 const ObjCObjectType *RHS = Rptr->getObjectType();
6757 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6758 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006759 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006760 return QualType();
6761
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006762 do {
John McCall8b07ec22010-05-15 11:32:37 +00006763 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006764 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006765 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006766 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6767
6768 QualType Result = QualType(LHS, 0);
6769 if (!Protocols.empty())
6770 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6771 Result = getObjCObjectPointerType(Result);
6772 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006773 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006774 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006775
6776 return QualType();
6777}
6778
John McCall8b07ec22010-05-15 11:32:37 +00006779bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6780 const ObjCObjectType *RHS) {
6781 assert(LHS->getInterface() && "LHS is not an interface type");
6782 assert(RHS->getInterface() && "RHS is not an interface type");
6783
Chris Lattner49af6a42008-04-07 06:51:04 +00006784 // Verify that the base decls are compatible: the RHS must be a subclass of
6785 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006786 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006787 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006788
Chris Lattner49af6a42008-04-07 06:51:04 +00006789 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6790 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006791 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006792 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006793
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006794 // Okay, we know the LHS has protocol qualifiers. But RHS may or may not.
6795 // More detailed analysis is required.
6796 // OK, if LHS is same or a superclass of RHS *and*
6797 // this LHS, or as RHS's super class is assignment compatible with LHS.
6798 bool IsSuperClass =
6799 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6800 if (IsSuperClass) {
6801 // OK if conversion of LHS to SuperClass results in narrowing of types
6802 // ; i.e., SuperClass may implement at least one of the protocols
6803 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6804 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6805 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6806 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6807 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
6808 // qualifiers.
6809 for (auto *RHSPI : RHS->quals())
6810 SuperClassInheritedProtocols.insert(RHSPI->getCanonicalDecl());
6811 // If there is no protocols associated with RHS, it is not a match.
6812 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00006813 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006814
6815 for (const auto *LHSProto : LHS->quals()) {
6816 bool SuperImplementsProtocol = false;
6817 for (auto *SuperClassProto : SuperClassInheritedProtocols)
6818 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6819 SuperImplementsProtocol = true;
6820 break;
6821 }
6822 if (!SuperImplementsProtocol)
6823 return false;
6824 }
6825 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006826 }
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006827 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006828}
6829
Steve Naroffb7605152009-02-12 17:52:19 +00006830bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6831 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006832 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6833 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006834
Steve Naroff7cae42b2009-07-10 23:34:53 +00006835 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006836 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006837
6838 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6839 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006840}
6841
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006842bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6843 return canAssignObjCInterfaces(
6844 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6845 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6846}
6847
Mike Stump11289f42009-09-09 15:08:12 +00006848/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006849/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006850/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006851/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006852bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6853 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006854 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006855 return hasSameType(LHS, RHS);
6856
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006857 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006858}
6859
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006860bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006861 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006862}
6863
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006864bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6865 return !mergeTypes(LHS, RHS, true).isNull();
6866}
6867
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006868/// mergeTransparentUnionType - if T is a transparent union type and a member
6869/// of T is compatible with SubType, return the merged type, else return
6870/// QualType()
6871QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6872 bool OfBlockPointer,
6873 bool Unqualified) {
6874 if (const RecordType *UT = T->getAsUnionType()) {
6875 RecordDecl *UD = UT->getDecl();
6876 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006877 for (const auto *I : UD->fields()) {
6878 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006879 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6880 if (!MT.isNull())
6881 return MT;
6882 }
6883 }
6884 }
6885
6886 return QualType();
6887}
6888
Alp Toker9cacbab2014-01-20 20:26:09 +00006889/// mergeFunctionParameterTypes - merge two types which appear as function
6890/// parameter types
6891QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6892 bool OfBlockPointer,
6893 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006894 // GNU extension: two types are compatible if they appear as a function
6895 // argument, one of the types is a transparent union type and the other
6896 // type is compatible with a union member
6897 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6898 Unqualified);
6899 if (!lmerge.isNull())
6900 return lmerge;
6901
6902 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6903 Unqualified);
6904 if (!rmerge.isNull())
6905 return rmerge;
6906
6907 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6908}
6909
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006910QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006911 bool OfBlockPointer,
6912 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006913 const FunctionType *lbase = lhs->getAs<FunctionType>();
6914 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006915 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6916 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006917 bool allLTypes = true;
6918 bool allRTypes = true;
6919
6920 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006921 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006922 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006923 QualType RHS = rbase->getReturnType();
6924 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006925 bool UnqualifiedResult = Unqualified;
6926 if (!UnqualifiedResult)
6927 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006928 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006929 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006930 else
Alp Toker314cc812014-01-25 16:55:45 +00006931 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006932 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006933 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006934
6935 if (Unqualified)
6936 retType = retType.getUnqualifiedType();
6937
Alp Toker314cc812014-01-25 16:55:45 +00006938 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6939 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006940 if (Unqualified) {
6941 LRetType = LRetType.getUnqualifiedType();
6942 RRetType = RRetType.getUnqualifiedType();
6943 }
6944
6945 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006946 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006947 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006948 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006949
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006950 // FIXME: double check this
6951 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6952 // rbase->getRegParmAttr() != 0 &&
6953 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006954 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6955 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006956
Douglas Gregor8c940862010-01-18 17:14:39 +00006957 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006958 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006959 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006960
John McCall8c6b56f2010-12-15 01:06:38 +00006961 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006962 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6963 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006964 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6965 return QualType();
6966
John McCall31168b02011-06-15 23:02:42 +00006967 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6968 return QualType();
6969
John McCall8c6b56f2010-12-15 01:06:38 +00006970 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6971 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006972
Rafael Espindola8778c282012-11-29 16:09:03 +00006973 if (lbaseInfo.getNoReturn() != NoReturn)
6974 allLTypes = false;
6975 if (rbaseInfo.getNoReturn() != NoReturn)
6976 allRTypes = false;
6977
John McCall31168b02011-06-15 23:02:42 +00006978 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006979
Eli Friedman47f77112008-08-22 00:56:42 +00006980 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006981 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6982 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006983 // Compatible functions must have the same number of parameters
6984 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006985 return QualType();
6986
6987 // Variadic and non-variadic functions aren't compatible
6988 if (lproto->isVariadic() != rproto->isVariadic())
6989 return QualType();
6990
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006991 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6992 return QualType();
6993
Fariborz Jahanian97676972011-09-28 21:52:05 +00006994 if (LangOpts.ObjCAutoRefCount &&
6995 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6996 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006997
6998 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006999 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007000 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7001 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7002 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7003 QualType paramType = mergeFunctionParameterTypes(
7004 lParamType, rParamType, OfBlockPointer, Unqualified);
7005 if (paramType.isNull())
7006 return QualType();
7007
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007008 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007009 paramType = paramType.getUnqualifiedType();
7010
7011 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007012 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007013 lParamType = lParamType.getUnqualifiedType();
7014 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007015 }
Alp Toker601b22c2014-01-21 23:35:24 +00007016
7017 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007018 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007019 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007020 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007021 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007022
Eli Friedman47f77112008-08-22 00:56:42 +00007023 if (allLTypes) return lhs;
7024 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007025
7026 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7027 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007028 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007029 }
7030
7031 if (lproto) allRTypes = false;
7032 if (rproto) allLTypes = false;
7033
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007034 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007035 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007036 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007037 if (proto->isVariadic()) return QualType();
7038 // Check that the types are compatible with the types that
7039 // would result from default argument promotions (C99 6.7.5.3p15).
7040 // The only types actually affected are promotable integer
7041 // types and floats, which would be passed as a different
7042 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007043 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7044 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007045
Eli Friedman448ce402012-08-30 00:44:15 +00007046 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007047 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007048 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7049 paramTy = Enum->getDecl()->getIntegerType();
7050 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007051 return QualType();
7052 }
Alp Toker601b22c2014-01-21 23:35:24 +00007053
7054 if (paramTy->isPromotableIntegerType() ||
7055 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007056 return QualType();
7057 }
7058
7059 if (allLTypes) return lhs;
7060 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007061
7062 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7063 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007064 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007065 }
7066
7067 if (allLTypes) return lhs;
7068 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007069 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007070}
7071
John McCall433c2e62013-03-21 00:10:07 +00007072/// Given that we have an enum type and a non-enum type, try to merge them.
7073static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7074 QualType other, bool isBlockReturnType) {
7075 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7076 // a signed integer type, or an unsigned integer type.
7077 // Compatibility is based on the underlying type, not the promotion
7078 // type.
7079 QualType underlyingType = ET->getDecl()->getIntegerType();
7080 if (underlyingType.isNull()) return QualType();
7081 if (Context.hasSameType(underlyingType, other))
7082 return other;
7083
7084 // In block return types, we're more permissive and accept any
7085 // integral type of the same size.
7086 if (isBlockReturnType && other->isIntegerType() &&
7087 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7088 return other;
7089
7090 return QualType();
7091}
7092
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007093QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007094 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007095 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007096 // C++ [expr]: If an expression initially has the type "reference to T", the
7097 // type is adjusted to "T" prior to any further analysis, the expression
7098 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007099 // expression is an lvalue unless the reference is an rvalue reference and
7100 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007101 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7102 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007103
7104 if (Unqualified) {
7105 LHS = LHS.getUnqualifiedType();
7106 RHS = RHS.getUnqualifiedType();
7107 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007108
Eli Friedman47f77112008-08-22 00:56:42 +00007109 QualType LHSCan = getCanonicalType(LHS),
7110 RHSCan = getCanonicalType(RHS);
7111
7112 // If two types are identical, they are compatible.
7113 if (LHSCan == RHSCan)
7114 return LHS;
7115
John McCall8ccfcb52009-09-24 19:53:00 +00007116 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007117 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7118 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007119 if (LQuals != RQuals) {
7120 // If any of these qualifiers are different, we have a type
7121 // mismatch.
7122 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007123 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7124 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007125 return QualType();
7126
7127 // Exactly one GC qualifier difference is allowed: __strong is
7128 // okay if the other type has no GC qualifier but is an Objective
7129 // C object pointer (i.e. implicitly strong by default). We fix
7130 // this by pretending that the unqualified type was actually
7131 // qualified __strong.
7132 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7133 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7134 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7135
7136 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7137 return QualType();
7138
7139 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7140 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7141 }
7142 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7143 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7144 }
Eli Friedman47f77112008-08-22 00:56:42 +00007145 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007146 }
7147
7148 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007149
Eli Friedmandcca6332009-06-01 01:22:52 +00007150 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7151 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007152
Chris Lattnerfd652912008-01-14 05:45:46 +00007153 // We want to consider the two function types to be the same for these
7154 // comparisons, just force one to the other.
7155 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7156 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007157
7158 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007159 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7160 LHSClass = Type::ConstantArray;
7161 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7162 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007163
John McCall8b07ec22010-05-15 11:32:37 +00007164 // ObjCInterfaces are just specialized ObjCObjects.
7165 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7166 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7167
Nate Begemance4d7fc2008-04-18 23:10:10 +00007168 // Canonicalize ExtVector -> Vector.
7169 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7170 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007171
Chris Lattner95554662008-04-07 05:43:21 +00007172 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007173 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007174 // Note that we only have special rules for turning block enum
7175 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007176 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007177 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007178 }
John McCall9dd450b2009-09-21 23:43:11 +00007179 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007180 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007181 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007182 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007183 if (OfBlockPointer && !BlockReturnType) {
7184 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7185 return LHS;
7186 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7187 return RHS;
7188 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007189
Eli Friedman47f77112008-08-22 00:56:42 +00007190 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007191 }
Eli Friedman47f77112008-08-22 00:56:42 +00007192
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007193 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007194 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007195#define TYPE(Class, Base)
7196#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007197#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007198#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7199#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7200#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007201 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007202
Richard Smith27d807c2013-04-30 13:56:41 +00007203 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007204 case Type::LValueReference:
7205 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007206 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007207 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007208
John McCall8b07ec22010-05-15 11:32:37 +00007209 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007210 case Type::IncompleteArray:
7211 case Type::VariableArray:
7212 case Type::FunctionProto:
7213 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007214 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007215
Chris Lattnerfd652912008-01-14 05:45:46 +00007216 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007217 {
7218 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007219 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7220 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007221 if (Unqualified) {
7222 LHSPointee = LHSPointee.getUnqualifiedType();
7223 RHSPointee = RHSPointee.getUnqualifiedType();
7224 }
7225 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7226 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007227 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007228 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007229 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007230 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007231 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007232 return getPointerType(ResultType);
7233 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007234 case Type::BlockPointer:
7235 {
7236 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007237 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7238 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007239 if (Unqualified) {
7240 LHSPointee = LHSPointee.getUnqualifiedType();
7241 RHSPointee = RHSPointee.getUnqualifiedType();
7242 }
7243 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7244 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007245 if (ResultType.isNull()) return QualType();
7246 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7247 return LHS;
7248 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7249 return RHS;
7250 return getBlockPointerType(ResultType);
7251 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007252 case Type::Atomic:
7253 {
7254 // Merge two pointer types, while trying to preserve typedef info
7255 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7256 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7257 if (Unqualified) {
7258 LHSValue = LHSValue.getUnqualifiedType();
7259 RHSValue = RHSValue.getUnqualifiedType();
7260 }
7261 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7262 Unqualified);
7263 if (ResultType.isNull()) return QualType();
7264 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7265 return LHS;
7266 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7267 return RHS;
7268 return getAtomicType(ResultType);
7269 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007270 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007271 {
7272 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7273 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7274 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7275 return QualType();
7276
7277 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7278 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007279 if (Unqualified) {
7280 LHSElem = LHSElem.getUnqualifiedType();
7281 RHSElem = RHSElem.getUnqualifiedType();
7282 }
7283
7284 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007285 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007286 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7287 return LHS;
7288 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7289 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007290 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7291 ArrayType::ArraySizeModifier(), 0);
7292 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7293 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007294 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7295 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007296 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7297 return LHS;
7298 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7299 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007300 if (LVAT) {
7301 // FIXME: This isn't correct! But tricky to implement because
7302 // the array's size has to be the size of LHS, but the type
7303 // has to be different.
7304 return LHS;
7305 }
7306 if (RVAT) {
7307 // FIXME: This isn't correct! But tricky to implement because
7308 // the array's size has to be the size of RHS, but the type
7309 // has to be different.
7310 return RHS;
7311 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007312 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7313 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007314 return getIncompleteArrayType(ResultType,
7315 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007316 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007317 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007318 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007319 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007320 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007321 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007322 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007323 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007324 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007325 case Type::Complex:
7326 // Distinct complex types are incompatible.
7327 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007328 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007329 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007330 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7331 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007332 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007333 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007334 case Type::ObjCObject: {
7335 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007336 // FIXME: This should be type compatibility, e.g. whether
7337 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007338 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7339 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7340 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007341 return LHS;
7342
Eli Friedman47f77112008-08-22 00:56:42 +00007343 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007344 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007345 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007346 if (OfBlockPointer) {
7347 if (canAssignObjCInterfacesInBlockPointer(
7348 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007349 RHS->getAs<ObjCObjectPointerType>(),
7350 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007351 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007352 return QualType();
7353 }
John McCall9dd450b2009-09-21 23:43:11 +00007354 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7355 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007356 return LHS;
7357
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007358 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007359 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007360 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007361
David Blaikie8a40f702012-01-17 06:56:22 +00007362 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007363}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007364
Fariborz Jahanian97676972011-09-28 21:52:05 +00007365bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7366 const FunctionProtoType *FromFunctionType,
7367 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007368 if (FromFunctionType->hasAnyConsumedParams() !=
7369 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007370 return false;
7371 FunctionProtoType::ExtProtoInfo FromEPI =
7372 FromFunctionType->getExtProtoInfo();
7373 FunctionProtoType::ExtProtoInfo ToEPI =
7374 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007375 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007376 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7377 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007378 return false;
7379 }
7380 return true;
7381}
7382
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007383/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7384/// 'RHS' attributes and returns the merged version; including for function
7385/// return types.
7386QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7387 QualType LHSCan = getCanonicalType(LHS),
7388 RHSCan = getCanonicalType(RHS);
7389 // If two types are identical, they are compatible.
7390 if (LHSCan == RHSCan)
7391 return LHS;
7392 if (RHSCan->isFunctionType()) {
7393 if (!LHSCan->isFunctionType())
7394 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007395 QualType OldReturnType =
7396 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007397 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007398 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007399 QualType ResReturnType =
7400 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7401 if (ResReturnType.isNull())
7402 return QualType();
7403 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7404 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7405 // In either case, use OldReturnType to build the new function type.
7406 const FunctionType *F = LHS->getAs<FunctionType>();
7407 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007408 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7409 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007410 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007411 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007412 return ResultType;
7413 }
7414 }
7415 return QualType();
7416 }
7417
7418 // If the qualifiers are different, the types can still be merged.
7419 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7420 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7421 if (LQuals != RQuals) {
7422 // If any of these qualifiers are different, we have a type mismatch.
7423 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7424 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7425 return QualType();
7426
7427 // Exactly one GC qualifier difference is allowed: __strong is
7428 // okay if the other type has no GC qualifier but is an Objective
7429 // C object pointer (i.e. implicitly strong by default). We fix
7430 // this by pretending that the unqualified type was actually
7431 // qualified __strong.
7432 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7433 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7434 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7435
7436 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7437 return QualType();
7438
7439 if (GC_L == Qualifiers::Strong)
7440 return LHS;
7441 if (GC_R == Qualifiers::Strong)
7442 return RHS;
7443 return QualType();
7444 }
7445
7446 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7447 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7448 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7449 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7450 if (ResQT == LHSBaseQT)
7451 return LHS;
7452 if (ResQT == RHSBaseQT)
7453 return RHS;
7454 }
7455 return QualType();
7456}
7457
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007458//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007459// Integer Predicates
7460//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007461
Jay Foad39c79802011-01-12 09:06:06 +00007462unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007463 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007464 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007465 if (T->isBooleanType())
7466 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007467 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007468 return (unsigned)getTypeSize(T);
7469}
7470
Abramo Bagnara13640492012-09-09 10:21:24 +00007471QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007472 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007473
7474 // Turn <4 x signed int> -> <4 x unsigned int>
7475 if (const VectorType *VTy = T->getAs<VectorType>())
7476 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007477 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007478
7479 // For enums, we return the unsigned version of the base type.
7480 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007481 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007482
7483 const BuiltinType *BTy = T->getAs<BuiltinType>();
7484 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007485 switch (BTy->getKind()) {
7486 case BuiltinType::Char_S:
7487 case BuiltinType::SChar:
7488 return UnsignedCharTy;
7489 case BuiltinType::Short:
7490 return UnsignedShortTy;
7491 case BuiltinType::Int:
7492 return UnsignedIntTy;
7493 case BuiltinType::Long:
7494 return UnsignedLongTy;
7495 case BuiltinType::LongLong:
7496 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007497 case BuiltinType::Int128:
7498 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007499 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007500 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007501 }
7502}
7503
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007504ASTMutationListener::~ASTMutationListener() { }
7505
Richard Smith1fa5d642013-05-11 05:45:24 +00007506void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7507 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007508
7509//===----------------------------------------------------------------------===//
7510// Builtin Type Computation
7511//===----------------------------------------------------------------------===//
7512
7513/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007514/// pointer over the consumed characters. This returns the resultant type. If
7515/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7516/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7517/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007518///
7519/// RequiresICE is filled in on return to indicate whether the value is required
7520/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007521static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007522 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007523 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007524 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007525 // Modifiers.
7526 int HowLong = 0;
7527 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007528 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007529
Chris Lattnerdc226c22010-10-01 22:42:38 +00007530 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007531 bool Done = false;
7532 while (!Done) {
7533 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007534 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007535 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007536 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007537 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007538 case 'S':
7539 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7540 assert(!Signed && "Can't use 'S' modifier multiple times!");
7541 Signed = true;
7542 break;
7543 case 'U':
7544 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7545 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7546 Unsigned = true;
7547 break;
7548 case 'L':
7549 assert(HowLong <= 2 && "Can't have LLLL modifier");
7550 ++HowLong;
7551 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007552 case 'W':
7553 // This modifier represents int64 type.
7554 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7555 switch (Context.getTargetInfo().getInt64Type()) {
7556 default:
7557 llvm_unreachable("Unexpected integer type");
7558 case TargetInfo::SignedLong:
7559 HowLong = 1;
7560 break;
7561 case TargetInfo::SignedLongLong:
7562 HowLong = 2;
7563 break;
7564 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007565 }
7566 }
7567
7568 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007569
Chris Lattnerecd79c62009-06-14 00:45:47 +00007570 // Read the base type.
7571 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007572 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007573 case 'v':
7574 assert(HowLong == 0 && !Signed && !Unsigned &&
7575 "Bad modifiers used with 'v'!");
7576 Type = Context.VoidTy;
7577 break;
Jack Carter24bef982013-08-15 15:16:57 +00007578 case 'h':
7579 assert(HowLong == 0 && !Signed && !Unsigned &&
7580 "Bad modifiers used with 'f'!");
7581 Type = Context.HalfTy;
7582 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007583 case 'f':
7584 assert(HowLong == 0 && !Signed && !Unsigned &&
7585 "Bad modifiers used with 'f'!");
7586 Type = Context.FloatTy;
7587 break;
7588 case 'd':
7589 assert(HowLong < 2 && !Signed && !Unsigned &&
7590 "Bad modifiers used with 'd'!");
7591 if (HowLong)
7592 Type = Context.LongDoubleTy;
7593 else
7594 Type = Context.DoubleTy;
7595 break;
7596 case 's':
7597 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7598 if (Unsigned)
7599 Type = Context.UnsignedShortTy;
7600 else
7601 Type = Context.ShortTy;
7602 break;
7603 case 'i':
7604 if (HowLong == 3)
7605 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7606 else if (HowLong == 2)
7607 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7608 else if (HowLong == 1)
7609 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7610 else
7611 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7612 break;
7613 case 'c':
7614 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7615 if (Signed)
7616 Type = Context.SignedCharTy;
7617 else if (Unsigned)
7618 Type = Context.UnsignedCharTy;
7619 else
7620 Type = Context.CharTy;
7621 break;
7622 case 'b': // boolean
7623 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7624 Type = Context.BoolTy;
7625 break;
7626 case 'z': // size_t.
7627 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7628 Type = Context.getSizeType();
7629 break;
7630 case 'F':
7631 Type = Context.getCFConstantStringType();
7632 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007633 case 'G':
7634 Type = Context.getObjCIdType();
7635 break;
7636 case 'H':
7637 Type = Context.getObjCSelType();
7638 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007639 case 'M':
7640 Type = Context.getObjCSuperType();
7641 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007642 case 'a':
7643 Type = Context.getBuiltinVaListType();
7644 assert(!Type.isNull() && "builtin va list type not initialized!");
7645 break;
7646 case 'A':
7647 // This is a "reference" to a va_list; however, what exactly
7648 // this means depends on how va_list is defined. There are two
7649 // different kinds of va_list: ones passed by value, and ones
7650 // passed by reference. An example of a by-value va_list is
7651 // x86, where va_list is a char*. An example of by-ref va_list
7652 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7653 // we want this argument to be a char*&; for x86-64, we want
7654 // it to be a __va_list_tag*.
7655 Type = Context.getBuiltinVaListType();
7656 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007657 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007658 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007659 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007660 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007661 break;
7662 case 'V': {
7663 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007664 unsigned NumElements = strtoul(Str, &End, 10);
7665 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007666 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007667
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007668 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7669 RequiresICE, false);
7670 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007671
7672 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007673 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007674 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007675 break;
7676 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007677 case 'E': {
7678 char *End;
7679
7680 unsigned NumElements = strtoul(Str, &End, 10);
7681 assert(End != Str && "Missing vector size");
7682
7683 Str = End;
7684
7685 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7686 false);
7687 Type = Context.getExtVectorType(ElementType, NumElements);
7688 break;
7689 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007690 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007691 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7692 false);
7693 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007694 Type = Context.getComplexType(ElementType);
7695 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007696 }
7697 case 'Y' : {
7698 Type = Context.getPointerDiffType();
7699 break;
7700 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007701 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007702 Type = Context.getFILEType();
7703 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007704 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007705 return QualType();
7706 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007707 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007708 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007709 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007710 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007711 else
7712 Type = Context.getjmp_bufType();
7713
Mike Stump2adb4da2009-07-28 23:47:15 +00007714 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007715 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007716 return QualType();
7717 }
7718 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007719 case 'K':
7720 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7721 Type = Context.getucontext_tType();
7722
7723 if (Type.isNull()) {
7724 Error = ASTContext::GE_Missing_ucontext;
7725 return QualType();
7726 }
7727 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007728 case 'p':
7729 Type = Context.getProcessIDType();
7730 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007731 }
Mike Stump11289f42009-09-09 15:08:12 +00007732
Chris Lattnerdc226c22010-10-01 22:42:38 +00007733 // If there are modifiers and if we're allowed to parse them, go for it.
7734 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007735 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007736 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007737 default: Done = true; --Str; break;
7738 case '*':
7739 case '&': {
7740 // Both pointers and references can have their pointee types
7741 // qualified with an address space.
7742 char *End;
7743 unsigned AddrSpace = strtoul(Str, &End, 10);
7744 if (End != Str && AddrSpace != 0) {
7745 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7746 Str = End;
7747 }
7748 if (c == '*')
7749 Type = Context.getPointerType(Type);
7750 else
7751 Type = Context.getLValueReferenceType(Type);
7752 break;
7753 }
7754 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7755 case 'C':
7756 Type = Type.withConst();
7757 break;
7758 case 'D':
7759 Type = Context.getVolatileType(Type);
7760 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007761 case 'R':
7762 Type = Type.withRestrict();
7763 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007764 }
7765 }
Chris Lattner84733392010-10-01 07:13:18 +00007766
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007767 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007768 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007769
Chris Lattnerecd79c62009-06-14 00:45:47 +00007770 return Type;
7771}
7772
7773/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007774QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007775 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007776 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007777 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007778
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007779 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007780
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007781 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007782 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007783 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7784 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007785 if (Error != GE_None)
7786 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007787
7788 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7789
Chris Lattnerecd79c62009-06-14 00:45:47 +00007790 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007791 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007792 if (Error != GE_None)
7793 return QualType();
7794
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007795 // If this argument is required to be an IntegerConstantExpression and the
7796 // caller cares, fill in the bitmask we return.
7797 if (RequiresICE && IntegerConstantArgs)
7798 *IntegerConstantArgs |= 1 << ArgTypes.size();
7799
Chris Lattnerecd79c62009-06-14 00:45:47 +00007800 // Do array -> pointer decay. The builtin should use the decayed type.
7801 if (Ty->isArrayType())
7802 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007803
Chris Lattnerecd79c62009-06-14 00:45:47 +00007804 ArgTypes.push_back(Ty);
7805 }
7806
7807 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7808 "'.' should only occur at end of builtin type list!");
7809
Reid Kleckner78af0702013-08-27 23:08:25 +00007810 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007811 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7812
7813 bool Variadic = (TypeStr[0] == '.');
7814
7815 // We really shouldn't be making a no-proto type here, especially in C++.
7816 if (ArgTypes.empty() && Variadic)
7817 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007818
John McCalldb40c7f2010-12-14 08:05:40 +00007819 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007820 EPI.ExtInfo = EI;
7821 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007822
Jordan Rose5c382722013-03-08 21:51:21 +00007823 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007824}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007825
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007826static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
7827 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007828 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007829 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007830
Rafael Espindola3ae00052013-05-13 00:12:11 +00007831 GVALinkage External = GVA_StrongExternal;
7832 switch (FD->getTemplateSpecializationKind()) {
7833 case TSK_Undeclared:
7834 case TSK_ExplicitSpecialization:
7835 External = GVA_StrongExternal;
7836 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007837
Rafael Espindola3ae00052013-05-13 00:12:11 +00007838 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007839 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007840
David Majnemerc3d07332014-05-15 06:25:57 +00007841 // C++11 [temp.explicit]p10:
7842 // [ Note: The intent is that an inline function that is the subject of
7843 // an explicit instantiation declaration will still be implicitly
7844 // instantiated when used so that the body can be considered for
7845 // inlining, but that no out-of-line copy of the inline function would be
7846 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00007847 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00007848 return GVA_AvailableExternally;
7849
Rafael Espindola3ae00052013-05-13 00:12:11 +00007850 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007851 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007852 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007853 }
7854
7855 if (!FD->isInlined())
7856 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007857
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007858 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
7859 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007860 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007861 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
7862
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007863 // GNU or C99 inline semantics. Determine whether this symbol should be
7864 // externally visible.
7865 if (FD->isInlineDefinitionExternallyVisible())
7866 return External;
7867
7868 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00007869 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007870 }
7871
David Majnemer54e3ba52014-04-02 23:17:29 +00007872 // Functions specified with extern and inline in -fms-compatibility mode
7873 // forcibly get emitted. While the body of the function cannot be later
7874 // replaced, the function definition cannot be discarded.
7875 if (FD->getMostRecentDecl()->isMSExternInline())
7876 return GVA_StrongODR;
7877
David Majnemer27d69db2014-04-28 22:17:59 +00007878 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007879}
7880
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007881static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
7882 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
7883 // dllexport/dllimport on inline functions.
7884 if (D->hasAttr<DLLImportAttr>()) {
7885 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
7886 return GVA_AvailableExternally;
7887 } else if (D->hasAttr<DLLExportAttr>()) {
7888 if (L == GVA_DiscardableODR)
7889 return GVA_StrongODR;
7890 }
7891 return L;
7892}
7893
7894GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
7895 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
7896 FD);
7897}
7898
7899static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
7900 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007901 if (!VD->isExternallyVisible())
7902 return GVA_Internal;
7903
David Majnemer27d69db2014-04-28 22:17:59 +00007904 if (VD->isStaticLocal()) {
7905 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
7906 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
7907 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
7908 LexicalContext = LexicalContext->getLexicalParent();
7909
7910 // Let the static local variable inherit it's linkage from the nearest
7911 // enclosing function.
7912 if (LexicalContext)
7913 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007914 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00007915
7916 // GVA_StrongODR function linkage is stronger than what we need,
7917 // downgrade to GVA_DiscardableODR.
7918 // This allows us to discard the variable if we never end up needing it.
7919 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
7920 : StaticLocalLinkage;
7921 }
7922
Hans Wennborg56fc62b2014-07-17 20:25:23 +00007923 // MSVC treats in-class initialized static data members as definitions.
7924 // By giving them non-strong linkage, out-of-line definitions won't
7925 // cause link errors.
7926 if (Context.isMSStaticDataMemberInlineDefinition(VD))
7927 return GVA_DiscardableODR;
7928
Richard Smith8809a0c2013-09-27 20:14:12 +00007929 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007930 case TSK_Undeclared:
7931 case TSK_ExplicitSpecialization:
7932 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007933
Rafael Espindola3ae00052013-05-13 00:12:11 +00007934 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007935 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007936
David Majnemer27d69db2014-04-28 22:17:59 +00007937 case TSK_ExplicitInstantiationDeclaration:
7938 return GVA_AvailableExternally;
7939
Rafael Espindola3ae00052013-05-13 00:12:11 +00007940 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007941 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007942 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007943
7944 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007945}
7946
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007947GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7948 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
7949 VD);
7950}
7951
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007952bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007953 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7954 if (!VD->isFileVarDecl())
7955 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00007956 // Global named register variables (GNU extension) are never emitted.
7957 if (VD->getStorageClass() == SC_Register)
7958 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007959 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7960 // We never need to emit an uninstantiated function template.
7961 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7962 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00007963 } else if (isa<OMPThreadPrivateDecl>(D))
7964 return true;
7965 else
Richard Smith5205a8c2013-04-01 20:22:16 +00007966 return false;
7967
7968 // If this is a member of a class template, we do not need to emit it.
7969 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007970 return false;
7971
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007972 // Weak references don't produce any output by themselves.
7973 if (D->hasAttr<WeakRefAttr>())
7974 return false;
7975
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007976 // Aliases and used decls are required.
7977 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7978 return true;
7979
7980 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7981 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007982 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007983 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007984
7985 // Constructors and destructors are required.
7986 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7987 return true;
7988
John McCall6bd2a892013-01-25 22:31:03 +00007989 // The key function for a class is required. This rule only comes
7990 // into play when inline functions can be key functions, though.
7991 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7992 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7993 const CXXRecordDecl *RD = MD->getParent();
7994 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7995 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7996 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7997 return true;
7998 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007999 }
8000 }
8001
8002 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8003
8004 // static, static inline, always_inline, and extern inline functions can
8005 // always be deferred. Normal inline functions can be deferred in C99/C++.
8006 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008007 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8008 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008009 return false;
8010 return true;
8011 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008012
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008013 const VarDecl *VD = cast<VarDecl>(D);
8014 assert(VD->isFileVarDecl() && "Expected file scoped var");
8015
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008016 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8017 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008018 return false;
8019
Richard Smitha0e5e542012-11-12 21:38:00 +00008020 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008021 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008022 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8023 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008024 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008025
Richard Smitha0e5e542012-11-12 21:38:00 +00008026 // Variables that have destruction with side-effects are required.
8027 if (VD->getType().isDestructedType())
8028 return true;
8029
8030 // Variables that have initialization with side-effects are required.
8031 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
8032 return true;
8033
8034 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008035}
Charles Davis53c59df2010-08-16 03:33:14 +00008036
Reid Kleckner78af0702013-08-27 23:08:25 +00008037CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8038 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008039 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008040 if (IsCXXMethod)
8041 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008042
Reid Kleckner78af0702013-08-27 23:08:25 +00008043 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00008044}
8045
Jay Foad39c79802011-01-12 09:06:06 +00008046bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008047 // Pass through to the C++ ABI object
8048 return ABI->isNearlyEmpty(RD);
8049}
8050
Reid Kleckner96f8f932014-02-05 17:27:08 +00008051VTableContextBase *ASTContext::getVTableContext() {
8052 if (!VTContext.get()) {
8053 if (Target->getCXXABI().isMicrosoft())
8054 VTContext.reset(new MicrosoftVTableContext(*this));
8055 else
8056 VTContext.reset(new ItaniumVTableContext(*this));
8057 }
8058 return VTContext.get();
8059}
8060
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008061MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008062 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008063 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008064 case TargetCXXABI::GenericItanium:
8065 case TargetCXXABI::GenericARM:
8066 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008067 case TargetCXXABI::iOS64:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008068 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008069 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008070 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008071 }
David Blaikie83d382b2011-09-23 05:06:16 +00008072 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008073}
8074
Charles Davis53c59df2010-08-16 03:33:14 +00008075CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008076
8077size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008078 return ASTRecordLayouts.getMemorySize() +
8079 llvm::capacity_in_bytes(ObjCLayouts) +
8080 llvm::capacity_in_bytes(KeyFunctions) +
8081 llvm::capacity_in_bytes(ObjCImpls) +
8082 llvm::capacity_in_bytes(BlockVarCopyInits) +
8083 llvm::capacity_in_bytes(DeclAttrs) +
8084 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8085 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8086 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8087 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8088 llvm::capacity_in_bytes(OverriddenMethods) +
8089 llvm::capacity_in_bytes(Types) +
8090 llvm::capacity_in_bytes(VariableArrayTypes) +
8091 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008092}
Ted Kremenek540017e2011-10-06 05:00:56 +00008093
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008094/// getIntTypeForBitwidth -
8095/// sets integer QualTy according to specified details:
8096/// bitwidth, signed/unsigned.
8097/// Returns empty type if there is no appropriate target types.
8098QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8099 unsigned Signed) const {
8100 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8101 CanQualType QualTy = getFromTargetType(Ty);
8102 if (!QualTy && DestWidth == 128)
8103 return Signed ? Int128Ty : UnsignedInt128Ty;
8104 return QualTy;
8105}
8106
8107/// getRealTypeForBitwidth -
8108/// sets floating point QualTy according to specified bitwidth.
8109/// Returns empty type if there is no appropriate target types.
8110QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8111 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8112 switch (Ty) {
8113 case TargetInfo::Float:
8114 return FloatTy;
8115 case TargetInfo::Double:
8116 return DoubleTy;
8117 case TargetInfo::LongDouble:
8118 return LongDoubleTy;
8119 case TargetInfo::NoFloat:
8120 return QualType();
8121 }
8122
8123 llvm_unreachable("Unhandled TargetInfo::RealType value");
8124}
8125
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008126void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8127 if (Number > 1)
8128 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008129}
8130
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008131unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8132 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8133 MangleNumbers.find(ND);
8134 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008135}
8136
David Majnemer2206bf52014-03-05 08:57:59 +00008137void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8138 if (Number > 1)
8139 StaticLocalNumbers[VD] = Number;
8140}
8141
8142unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8143 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8144 StaticLocalNumbers.find(VD);
8145 return I != StaticLocalNumbers.end() ? I->second : 1;
8146}
8147
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008148MangleNumberingContext &
8149ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008150 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8151 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8152 if (!MCtx)
8153 MCtx = createMangleNumberingContext();
8154 return *MCtx;
8155}
8156
8157MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8158 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008159}
8160
Ted Kremenek540017e2011-10-06 05:00:56 +00008161void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8162 ParamIndices[D] = index;
8163}
8164
8165unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8166 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8167 assert(I != ParamIndices.end() &&
8168 "ParmIndices lacks entry set by ParmVarDecl");
8169 return I->second;
8170}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008171
Richard Smithe6c01442013-06-05 00:46:14 +00008172APValue *
8173ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8174 bool MayCreate) {
8175 assert(E && E->getStorageDuration() == SD_Static &&
8176 "don't need to cache the computed value for this temporary");
8177 if (MayCreate)
8178 return &MaterializedTemporaryValues[E];
8179
8180 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8181 MaterializedTemporaryValues.find(E);
Craig Topper36250ad2014-05-12 05:36:57 +00008182 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
Richard Smithe6c01442013-06-05 00:46:14 +00008183}
8184
Fariborz Jahanian615de762013-05-28 17:37:39 +00008185bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8186 const llvm::Triple &T = getTargetInfo().getTriple();
8187 if (!T.isOSDarwin())
8188 return false;
8189
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008190 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8191 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8192 return false;
8193
Fariborz Jahanian615de762013-05-28 17:37:39 +00008194 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8195 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8196 uint64_t Size = sizeChars.getQuantity();
8197 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8198 unsigned Align = alignChars.getQuantity();
8199 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8200 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8201}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008202
8203namespace {
8204
8205 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8206 /// parents as defined by the \c RecursiveASTVisitor.
8207 ///
8208 /// Note that the relationship described here is purely in terms of AST
8209 /// traversal - there are other relationships (for example declaration context)
8210 /// in the AST that are better modeled by special matchers.
8211 ///
8212 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8213 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8214
8215 public:
8216 /// \brief Builds and returns the translation unit's parent map.
8217 ///
8218 /// The caller takes ownership of the returned \c ParentMap.
8219 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8220 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8221 Visitor.TraverseDecl(&TU);
8222 return Visitor.Parents;
8223 }
8224
8225 private:
8226 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8227
8228 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8229 }
8230
8231 bool shouldVisitTemplateInstantiations() const {
8232 return true;
8233 }
8234 bool shouldVisitImplicitCode() const {
8235 return true;
8236 }
8237 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8238 // are not triggered during data recursion.
8239 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8240 return false;
8241 }
8242
8243 template <typename T>
8244 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008245 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008246 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008247 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008248 // FIXME: Currently we add the same parent multiple times, but only
8249 // when no memoization data is available for the type.
8250 // For example when we visit all subexpressions of template
8251 // instantiations; this is suboptimal, but benign: the only way to
8252 // visit those is with hasAncestor / hasParent, and those do not create
8253 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008254 // The plan is to enable DynTypedNode to be storable in a map or hash
8255 // map. The main problem there is to implement hash functions /
8256 // comparison operators for all types that DynTypedNode supports that
8257 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008258 auto &NodeOrVector = (*Parents)[Node];
8259 if (NodeOrVector.isNull()) {
8260 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008261 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008262 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8263 auto *Node =
8264 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8265 auto *Vector = new ASTContext::ParentVector(1, *Node);
8266 NodeOrVector = Vector;
8267 delete Node;
8268 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008269 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008270
8271 auto *Vector =
8272 NodeOrVector.template get<ASTContext::ParentVector *>();
8273 // Skip duplicates for types that have memoization data.
8274 // We must check that the type has memoization data before calling
8275 // std::find() because DynTypedNode::operator== can't compare all
8276 // types.
8277 bool Found = ParentStack.back().getMemoizationData() &&
8278 std::find(Vector->begin(), Vector->end(),
8279 ParentStack.back()) != Vector->end();
8280 if (!Found)
8281 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008282 }
8283 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008284 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8285 bool Result = (this ->* traverse) (Node);
8286 ParentStack.pop_back();
8287 return Result;
8288 }
8289
8290 bool TraverseDecl(Decl *DeclNode) {
8291 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8292 }
8293
8294 bool TraverseStmt(Stmt *StmtNode) {
8295 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8296 }
8297
8298 ASTContext::ParentMap *Parents;
8299 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8300
8301 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8302 };
8303
8304} // end namespace
8305
Benjamin Kramer07935292014-10-04 17:01:26 +00008306ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008307ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8308 assert(Node.getMemoizationData() &&
8309 "Invariant broken: only nodes that support memoization may be "
8310 "used in the parent map.");
8311 if (!AllParents) {
8312 // We always need to run over the whole translation unit, as
8313 // hasAncestor can escape any subtree.
8314 AllParents.reset(
8315 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8316 }
8317 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8318 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008319 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008320 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008321 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8322 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008323 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008324 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008325}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008326
8327bool
8328ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8329 const ObjCMethodDecl *MethodImpl) {
8330 // No point trying to match an unavailable/deprecated mothod.
8331 if (MethodDecl->hasAttr<UnavailableAttr>()
8332 || MethodDecl->hasAttr<DeprecatedAttr>())
8333 return false;
8334 if (MethodDecl->getObjCDeclQualifier() !=
8335 MethodImpl->getObjCDeclQualifier())
8336 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008337 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008338 return false;
8339
8340 if (MethodDecl->param_size() != MethodImpl->param_size())
8341 return false;
8342
8343 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8344 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8345 EF = MethodDecl->param_end();
8346 IM != EM && IF != EF; ++IM, ++IF) {
8347 const ParmVarDecl *DeclVar = (*IF);
8348 const ParmVarDecl *ImplVar = (*IM);
8349 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8350 return false;
8351 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8352 return false;
8353 }
8354 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8355
8356}
Richard Smith053f6c62014-05-16 23:01:30 +00008357
8358// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8359// doesn't include ASTContext.h
8360template
8361clang::LazyGenerationalUpdatePtr<
8362 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8363clang::LazyGenerationalUpdatePtr<
8364 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8365 const clang::ASTContext &Ctx, Decl *Value);