blob: ea96a07763190f015eaef3f413c3289a45210d50 [file] [log] [blame]
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
Chris Lattnerddc135e2006-11-10 06:34:16 +00002//
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"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000016#include "clang/AST/APValue.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/ASTMutationListener.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000018#include "clang/AST/ASTTypeTraits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Attr.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000020#include "clang/AST/AttrIterator.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000021#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000022#include "clang/AST/Comment.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000023#include "clang/AST/Decl.h"
24#include "clang/AST/DeclBase.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000025#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000026#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000027#include "clang/AST/DeclObjC.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000028#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000029#include "clang/AST/DeclTemplate.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000030#include "clang/AST/DeclarationName.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000031#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000032#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000033#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000034#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000035#include "clang/AST/MangleNumberingContext.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000036#include "clang/AST/NestedNameSpecifier.h"
37#include "clang/AST/RawCommentList.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000038#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000039#include "clang/AST/RecursiveASTVisitor.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000040#include "clang/AST/Stmt.h"
41#include "clang/AST/TemplateBase.h"
42#include "clang/AST/TemplateName.h"
43#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000044#include "clang/AST/TypeLoc.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000045#include "clang/AST/UnresolvedSet.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000046#include "clang/AST/VTableBuilder.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000047#include "clang/Basic/AddressSpaces.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000048#include "clang/Basic/Builtins.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000049#include "clang/Basic/CommentOptions.h"
50#include "clang/Basic/IdentifierTable.h"
51#include "clang/Basic/LLVM.h"
52#include "clang/Basic/LangOptions.h"
53#include "clang/Basic/Linkage.h"
54#include "clang/Basic/ObjCRuntime.h"
55#include "clang/Basic/SanitizerBlacklist.h"
56#include "clang/Basic/SourceLocation.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000057#include "clang/Basic/SourceManager.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000058#include "clang/Basic/Specifiers.h"
59#include "clang/Basic/TargetCXXABI.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000060#include "clang/Basic/TargetInfo.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000061#include "clang/Basic/XRayLists.h"
62#include "llvm/ADT/APInt.h"
63#include "llvm/ADT/APSInt.h"
64#include "llvm/ADT/ArrayRef.h"
65#include "llvm/ADT/DenseMap.h"
66#include "llvm/ADT/DenseSet.h"
67#include "llvm/ADT/FoldingSet.h"
68#include "llvm/ADT/None.h"
69#include "llvm/ADT/Optional.h"
70#include "llvm/ADT/PointerUnion.h"
71#include "llvm/ADT/STLExtras.h"
72#include "llvm/ADT/SmallPtrSet.h"
73#include "llvm/ADT/SmallVector.h"
Anders Carlssond8499822007-10-29 05:01:08 +000074#include "llvm/ADT/StringExtras.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000075#include "llvm/ADT/StringRef.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000076#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000077#include "llvm/Support/Capacity.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000078#include "llvm/Support/Casting.h"
79#include "llvm/Support/Compiler.h"
80#include "llvm/Support/ErrorHandling.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000081#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000082#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000083#include <algorithm>
84#include <cassert>
85#include <cstddef>
86#include <cstdint>
87#include <cstdlib>
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000088#include <map>
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000089#include <memory>
90#include <string>
91#include <tuple>
92#include <utility>
Anders Carlssona4267a62009-07-18 21:19:52 +000093
Chris Lattnerddc135e2006-11-10 06:34:16 +000094using namespace clang;
95
Douglas Gregor9672f922010-07-03 00:47:00 +000096unsigned ASTContext::NumImplicitDefaultConstructors;
97unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000098unsigned ASTContext::NumImplicitCopyConstructors;
99unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000100unsigned ASTContext::NumImplicitMoveConstructors;
101unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000102unsigned ASTContext::NumImplicitCopyAssignmentOperators;
103unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000104unsigned ASTContext::NumImplicitMoveAssignmentOperators;
105unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +0000106unsigned ASTContext::NumImplicitDestructors;
107unsigned ASTContext::NumImplicitDestructorsDeclared;
108
Steve Naroff0af91202007-04-27 21:51:21 +0000109enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +0000110 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +0000111};
112
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000113RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000114 if (!CommentsLoaded && ExternalSource) {
115 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +0000116
117#ifndef NDEBUG
118 ArrayRef<RawComment *> RawComments = Comments.getComments();
119 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
120 BeforeThanCompare<RawComment>(SourceMgr)));
121#endif
122
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000123 CommentsLoaded = true;
124 }
125
126 assert(D);
127
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000128 // User can not attach documentation to implicit declarations.
129 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +0000130 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000131
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000132 // User can not attach documentation to implicit instantiations.
133 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
134 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000135 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000136 }
137
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000138 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
139 if (VD->isStaticDataMember() &&
140 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000141 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000142 }
143
144 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
145 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000146 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000147 }
148
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000149 if (const ClassTemplateSpecializationDecl *CTSD =
150 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
151 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
152 if (TSK == TSK_ImplicitInstantiation ||
153 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000154 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000155 }
156
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000157 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
158 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000159 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000160 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000161 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
162 // When tag declaration (but not definition!) is part of the
163 // decl-specifier-seq of some other declaration, it doesn't get comment
164 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000165 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000166 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // TODO: handle comments for function parameters properly.
168 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000169 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000170
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000171 // TODO: we could look up template parameter documentation in the template
172 // documentation.
173 if (isa<TemplateTypeParmDecl>(D) ||
174 isa<NonTypeTemplateParmDecl>(D) ||
175 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000176 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000177
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000178 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000179
180 // If there are no comments anywhere, we won't find anything.
181 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000182 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000183
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000184 // Find declaration location.
185 // For Objective-C declarations we generally don't expect to have multiple
186 // declarators, thus use declaration starting location as the "declaration
187 // location".
188 // For all other declarations multiple declarators are used quite frequently,
189 // so we use the location of the identifier as the "declaration location".
190 SourceLocation DeclLoc;
191 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000192 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000193 isa<RedeclarableTemplateDecl>(D) ||
194 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000195 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000196 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000197 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000198 if (DeclLoc.isMacroID()) {
199 if (isa<TypedefDecl>(D)) {
200 // If location of the typedef name is in a macro, it is because being
201 // declared via a macro. Try using declaration's starting location as
202 // the "declaration location".
203 DeclLoc = D->getLocStart();
204 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
205 // If location of the tag decl is inside a macro, but the spelling of
206 // the tag name comes from a macro argument, it looks like a special
207 // macro like NS_ENUM is being used to define the tag decl. In that
208 // case, adjust the source location to the expansion loc so that we can
209 // attach the comment to the tag decl.
210 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
211 TD->isCompleteDefinition())
212 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
213 }
214 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000215 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000216
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000217 // If the declaration doesn't map directly to a location in a file, we
218 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000219 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000220 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000221
222 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000223 ArrayRef<RawComment *>::iterator Comment;
224 {
225 // When searching for comments during parsing, the comment we are looking
226 // for is usually among the last two comments we parsed -- check them
227 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000228 RawComment CommentAtDeclLoc(
David L. Jones13d5a872018-03-02 00:07:45 +0000229 SourceMgr, SourceRange(DeclLoc), LangOpts.CommentOpts, false);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000230 BeforeThanCompare<RawComment> Compare(SourceMgr);
231 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
232 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
233 if (!Found && RawComments.size() >= 2) {
234 MaybeBeforeDecl--;
235 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
236 }
237
238 if (Found) {
239 Comment = MaybeBeforeDecl + 1;
240 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
241 &CommentAtDeclLoc, Compare));
242 } else {
243 // Slow path.
244 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
245 &CommentAtDeclLoc, Compare);
246 }
247 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000248
249 // Decompose the location for the declaration and find the beginning of the
250 // file buffer.
251 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
252
253 // First check whether we have a trailing comment.
254 if (Comment != RawComments.end() &&
David L. Jones13d5a872018-03-02 00:07:45 +0000255 ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
256 && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000257 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000258 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000259 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000260 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000261 // Check that Doxygen trailing comment comes after the declaration, starts
262 // on the same line and in the same file as the declaration.
263 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
264 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
265 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
266 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000267 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000268 }
269 }
270
271 // The comment just after the declaration was not a trailing comment.
272 // Let's look at the previous comment.
273 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000274 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000275 --Comment;
276
277 // Check that we actually have a non-member Doxygen comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000278 if (!((*Comment)->isDocumentation() ||
279 LangOpts.CommentOpts.ParseAllComments) ||
280 (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000281 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000282
283 // Decompose the end of the comment.
284 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000285 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000286
287 // If the comment and the declaration aren't in the same file, then they
288 // aren't related.
289 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000290 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000291
292 // Get the corresponding buffer.
293 bool Invalid = false;
294 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
295 &Invalid).data();
296 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000297 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000298
299 // Extract text between the comment and declaration.
300 StringRef Text(Buffer + CommentEndDecomp.second,
301 DeclLocDecomp.second - CommentEndDecomp.second);
302
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000303 // There should be no other declarations or preprocessor directives between
304 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000305 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000306 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000307
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000308 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000309}
310
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000311/// If we have a 'templated' declaration for a template, adjust 'D' to
312/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000313/// If we have an implicit instantiation, adjust 'D' to refer to template.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000314static const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000315 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000316 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000317 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000318 return FTD;
319
320 // Nothing to do if function is not an implicit instantiation.
321 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
322 return D;
323
324 // Function is an implicit instantiation of a function template?
325 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
326 return FTD;
327
328 // Function is instantiated from a member definition of a class template?
329 if (const FunctionDecl *MemberDecl =
330 FD->getInstantiatedFromMemberFunction())
331 return MemberDecl;
332
333 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000334 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000335 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
336 // Static data member is instantiated from a member definition of a class
337 // template?
338 if (VD->isStaticDataMember())
339 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
340 return MemberDecl;
341
342 return D;
343 }
344 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
345 // Is this class declaration part of a class template?
346 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
347 return CTD;
348
349 // Class is an implicit instantiation of a class template or partial
350 // specialization?
351 if (const ClassTemplateSpecializationDecl *CTSD =
352 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
353 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
354 return D;
355 llvm::PointerUnion<ClassTemplateDecl *,
356 ClassTemplatePartialSpecializationDecl *>
357 PU = CTSD->getSpecializedTemplateOrPartial();
358 return PU.is<ClassTemplateDecl*>() ?
359 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
360 static_cast<const Decl*>(
361 PU.get<ClassTemplatePartialSpecializationDecl *>());
362 }
363
364 // Class is instantiated from a member definition of a class template?
365 if (const MemberSpecializationInfo *Info =
366 CRD->getMemberSpecializationInfo())
367 return Info->getInstantiatedFrom();
368
369 return D;
370 }
371 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
372 // Enum is instantiated from a member definition of a class template?
373 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
374 return MemberDecl;
375
376 return D;
377 }
378 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000379 return D;
380}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000381
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000382const RawComment *ASTContext::getRawCommentForAnyRedecl(
383 const Decl *D,
384 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000385 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000386
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000387 // Check whether we have cached a comment for this declaration already.
388 {
389 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
390 RedeclComments.find(D);
391 if (Pos != RedeclComments.end()) {
392 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000393 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
394 if (OriginalDecl)
395 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000396 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000397 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000398 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000399 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000400
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000401 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000402 const RawComment *RC = nullptr;
403 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000404 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000405 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000406 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000407 if (Pos != RedeclComments.end()) {
408 const RawCommentAndCacheFlags &Raw = Pos->second;
409 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
410 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000411 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000412 break;
413 }
414 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000415 RC = getRawCommentForDeclNoCache(I);
416 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000417 RawCommentAndCacheFlags Raw;
418 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000419 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
420 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000421 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000422 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000423 } else
424 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000425 Raw.setOriginalDecl(I);
426 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000427 if (RC)
428 break;
429 }
430 }
431
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000432 // If we found a comment, it should be a documentation comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000433 assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000434
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000435 if (OriginalDecl)
436 *OriginalDecl = OriginalDeclForRC;
437
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000438 // Update cache for every declaration in the redeclaration chain.
439 RawCommentAndCacheFlags Raw;
440 Raw.setRaw(RC);
441 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000442 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000443
Aaron Ballman86c93902014-03-06 23:45:36 +0000444 for (auto I : D->redecls()) {
445 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000446 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
447 R = Raw;
448 }
449
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000450 return RC;
451}
452
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000453static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
454 SmallVectorImpl<const NamedDecl *> &Redeclared) {
455 const DeclContext *DC = ObjCMethod->getDeclContext();
456 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
457 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
458 if (!ID)
459 return;
460 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000461 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000463 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000464 ObjCMethod->isInstanceMethod()))
465 Redeclared.push_back(RedeclaredMethod);
466 }
467 }
468}
469
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000470comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
471 const Decl *D) const {
472 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
473 ThisDeclInfo->CommentDecl = D;
474 ThisDeclInfo->IsFilled = false;
475 ThisDeclInfo->fill();
476 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000477 if (!ThisDeclInfo->TemplateParameters)
478 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000479 comments::FullComment *CFC =
480 new (*this) comments::FullComment(FC->getBlocks(),
481 ThisDeclInfo);
482 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000483}
484
Richard Smithb39b9d52013-05-21 05:24:00 +0000485comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
486 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000487 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000488}
489
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000490comments::FullComment *ASTContext::getCommentForDecl(
491 const Decl *D,
492 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000493 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000494 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000495 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000496
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000497 const Decl *Canonical = D->getCanonicalDecl();
498 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
499 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000500
501 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000502 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000503 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000504 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000505 return CFC;
506 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000507 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000508 }
509
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000510 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000511
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000512 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000513 if (!RC) {
514 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000515 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000516 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000517 if (OMD && OMD->isPropertyAccessor())
518 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
519 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
520 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000521 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000522 addRedeclaredMethods(OMD, Overridden);
523 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000524 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
525 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
526 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000527 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000528 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000529 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000530 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000531 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000532 if (const TagType *TT = QT->getAs<TagType>())
533 if (const Decl *TD = TT->getDecl())
534 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000535 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000536 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000537 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
538 while (IC->getSuperClass()) {
539 IC = IC->getSuperClass();
540 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
541 return cloneFullComment(FC, D);
542 }
543 }
544 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
545 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
546 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
547 return cloneFullComment(FC, D);
548 }
549 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
550 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000551 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000552 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000553 for (const auto &I : RD->bases()) {
554 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000555 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000556 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000557 if (Ty.isNull())
558 continue;
559 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
560 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
561 continue;
562
563 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
564 return cloneFullComment(FC, D);
565 }
566 }
567 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000568 for (const auto &I : RD->vbases()) {
569 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000570 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000571 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000572 if (Ty.isNull())
573 continue;
574 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
575 if (!(VirtualBase= VirtualBase->getDefinition()))
576 continue;
577 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
578 return cloneFullComment(FC, D);
579 }
580 }
581 }
Craig Topper36250ad2014-05-12 05:36:57 +0000582 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000583 }
584
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000585 // If the RawComment was attached to other redeclaration of this Decl, we
586 // should parse the comment in context of that other Decl. This is important
587 // because comments can contain references to parameter names which can be
588 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000589 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000590 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000591
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000592 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000593 ParsedComments[Canonical] = FC;
594 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000595}
596
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000597void
598ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
599 TemplateTemplateParmDecl *Parm) {
600 ID.AddInteger(Parm->getDepth());
601 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000602 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000603
604 TemplateParameterList *Params = Parm->getTemplateParameters();
605 ID.AddInteger(Params->size());
606 for (TemplateParameterList::const_iterator P = Params->begin(),
607 PEnd = Params->end();
608 P != PEnd; ++P) {
609 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
610 ID.AddInteger(0);
611 ID.AddBoolean(TTP->isParameterPack());
612 continue;
613 }
614
615 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
616 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000617 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000618 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000619 if (NTTP->isExpandedParameterPack()) {
620 ID.AddBoolean(true);
621 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
623 QualType T = NTTP->getExpansionType(I);
624 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
625 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000626 } else
627 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000628 continue;
629 }
630
631 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
632 ID.AddInteger(2);
633 Profile(ID, TTP);
634 }
635}
636
637TemplateTemplateParmDecl *
638ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000639 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000640 // Check if we already have a canonical template template parameter.
641 llvm::FoldingSetNodeID ID;
642 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000643 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000644 CanonicalTemplateTemplateParm *Canonical
645 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
646 if (Canonical)
647 return Canonical->getParam();
648
649 // Build a canonical template parameter list.
650 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000651 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000652 CanonParams.reserve(Params->size());
653 for (TemplateParameterList::const_iterator P = Params->begin(),
654 PEnd = Params->end();
655 P != PEnd; ++P) {
656 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
657 CanonParams.push_back(
658 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000659 SourceLocation(),
660 SourceLocation(),
661 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000662 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000663 TTP->isParameterPack()));
664 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000665 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
666 QualType T = getCanonicalType(NTTP->getType());
667 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
668 NonTypeTemplateParmDecl *Param;
669 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000670 SmallVector<QualType, 2> ExpandedTypes;
671 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000672 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
673 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
674 ExpandedTInfos.push_back(
675 getTrivialTypeSourceInfo(ExpandedTypes.back()));
676 }
677
678 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000679 SourceLocation(),
680 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000681 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000682 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000683 T,
684 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000685 ExpandedTypes,
686 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000687 } else {
688 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000689 SourceLocation(),
690 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000691 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000692 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000693 T,
694 NTTP->isParameterPack(),
695 TInfo);
696 }
697 CanonParams.push_back(Param);
698
699 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000700 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
701 cast<TemplateTemplateParmDecl>(*P)));
702 }
703
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000704 assert(!TTP->getRequiresClause() &&
705 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000706 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000707
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000708 TemplateTemplateParmDecl *CanonTTP
709 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
710 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000711 TTP->getPosition(),
712 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000713 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000714 TemplateParameterList::Create(*this, SourceLocation(),
715 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000716 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000717 SourceLocation(),
718 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000719
720 // Get the new insert position for the node we care about.
721 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000722 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000723 (void)Canonical;
724
725 // Create the canonical template template parameter entry.
726 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
727 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
728 return CanonTTP;
729}
730
Charles Davis53c59df2010-08-16 03:33:14 +0000731CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000732 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000733
John McCall359b8852013-01-25 22:30:49 +0000734 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000735 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000736 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000737 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000738 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000739 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000740 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000741 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000742 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000743 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000744 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000745 return CreateMicrosoftCXXABI(*this);
746 }
David Blaikie8a40f702012-01-17 06:56:22 +0000747 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000748}
749
Alexander Richardson6d989432017-10-15 18:48:14 +0000750static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
751 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000752 if (LOpts.FakeAddressSpaceMap) {
753 // The fake address space map must have a distinct entry for each
754 // language-specific address space.
755 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000756 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000757 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000758 3, // opencl_local
759 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000760 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000761 4, // opencl_generic
762 5, // cuda_device
763 6, // cuda_constant
764 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000765 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000766 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000767 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000768 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000769 }
770}
771
David Tweed31d09b02013-09-13 12:04:22 +0000772static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
773 const LangOptions &LangOpts) {
774 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000775 case LangOptions::ASMM_Target:
776 return TI.useAddressSpaceMapMangling();
777 case LangOptions::ASMM_On:
778 return true;
779 case LangOptions::ASMM_Off:
780 return false;
781 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000782 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000783}
784
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000785ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000786 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000787 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000788 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
789 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000790 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000791 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000792 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
793 LangOpts.XRayNeverInstrumentFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000794 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000795 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000796 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000797 TUDecl = TranslationUnitDecl::Create(*this);
798}
799
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000800ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000801 ReleaseParentMapEntries();
802
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000803 // Release the DenseMaps associated with DeclContext objects.
804 // FIXME: Is this the ideal solution?
805 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000806
Manuel Klimeka7328992013-06-03 13:51:33 +0000807 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000808 for (auto &Pair : Deallocations)
809 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000810
Ted Kremenek076baeb2010-06-08 23:00:58 +0000811 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000812 // because they can contain DenseMaps.
813 for (llvm::DenseMap<const ObjCContainerDecl*,
814 const ASTRecordLayout*>::iterator
815 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
816 // Increment in loop to prevent using deallocated memory.
817 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
818 R->Destroy(*this);
819
Ted Kremenek076baeb2010-06-08 23:00:58 +0000820 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
821 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
822 // Increment in loop to prevent using deallocated memory.
823 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
824 R->Destroy(*this);
825 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000826
827 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
828 AEnd = DeclAttrs.end();
829 A != AEnd; ++A)
830 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000831
David Majnemere694f3e2015-08-14 14:43:50 +0000832 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
833 MaterializedTemporaryValues)
834 MTVPair.second->~APValue();
835
Richard Smith423f46f2016-07-20 21:38:26 +0000836 for (const auto &Value : ModuleInitializers)
837 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000838}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000839
Manuel Klimek95403e62014-05-21 13:28:59 +0000840void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000841 if (!PointerParents) return;
842 for (const auto &Entry : *PointerParents) {
843 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
844 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
845 } else if (Entry.second.is<ParentVector *>()) {
846 delete Entry.second.get<ParentVector *>();
847 }
848 }
849 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000850 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
851 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000852 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000853 delete Entry.second.get<ParentVector *>();
854 }
855 }
856}
857
Douglas Gregor1a809332010-05-23 18:26:36 +0000858void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000859 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000860}
861
Mike Stump11289f42009-09-09 15:08:12 +0000862void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000863ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000864 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000865}
866
Chris Lattner4eb445d2007-01-26 01:27:23 +0000867void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000868 llvm::errs() << "\n*** AST Context Stats:\n";
869 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000870
Douglas Gregora30d0462009-05-26 14:40:08 +0000871 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000872#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000873#define ABSTRACT_TYPE(Name, Parent)
874#include "clang/AST/TypeNodes.def"
875 0 // Extra
876 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000877
Chris Lattner4eb445d2007-01-26 01:27:23 +0000878 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
879 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000880 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000881 }
882
Douglas Gregora30d0462009-05-26 14:40:08 +0000883 unsigned Idx = 0;
884 unsigned TotalBytes = 0;
885#define TYPE(Name, Parent) \
886 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000887 llvm::errs() << " " << counts[Idx] << " " << #Name \
888 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000889 TotalBytes += counts[Idx] * sizeof(Name##Type); \
890 ++Idx;
891#define ABSTRACT_TYPE(Name, Parent)
892#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000893
Chandler Carruth3c147a72011-07-04 05:32:14 +0000894 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
895
Douglas Gregor7454c562010-07-02 20:37:36 +0000896 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000897 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
898 << NumImplicitDefaultConstructors
899 << " implicit default constructors created\n";
900 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
901 << NumImplicitCopyConstructors
902 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000903 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000904 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
905 << NumImplicitMoveConstructors
906 << " implicit move constructors created\n";
907 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
908 << NumImplicitCopyAssignmentOperators
909 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000910 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000911 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
912 << NumImplicitMoveAssignmentOperators
913 << " implicit move assignment operators created\n";
914 llvm::errs() << NumImplicitDestructorsDeclared << "/"
915 << NumImplicitDestructors
916 << " implicit destructors created\n";
917
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000918 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000919 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000920 ExternalSource->PrintStats();
921 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000922
Douglas Gregor5b11d492010-07-25 17:53:33 +0000923 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000924}
925
Richard Smith42413142015-05-15 20:05:43 +0000926void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
927 bool NotifyListeners) {
928 if (NotifyListeners)
929 if (auto *Listener = getASTMutationListener())
930 Listener->RedefinedHiddenDefinition(ND, M);
931
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000932 if (getLangOpts().ModulesLocalVisibility)
933 MergedDefModules[ND].push_back(M);
934 else
Richard Smith90dc5252017-06-23 01:04:34 +0000935 ND->setVisibleDespiteOwningModule();
Richard Smith42413142015-05-15 20:05:43 +0000936}
937
938void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
939 auto It = MergedDefModules.find(ND);
940 if (It == MergedDefModules.end())
941 return;
942
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000943 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000944 llvm::DenseSet<Module*> Found;
945 for (Module *&M : Merged)
946 if (!Found.insert(M).second)
947 M = nullptr;
948 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
949}
950
Richard Smithdc1f0422016-07-20 19:10:16 +0000951void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
952 if (LazyInitializers.empty())
953 return;
954
955 auto *Source = Ctx.getExternalSource();
956 assert(Source && "lazy initializers but no external source");
957
958 auto LazyInits = std::move(LazyInitializers);
959 LazyInitializers.clear();
960
961 for (auto ID : LazyInits)
962 Initializers.push_back(Source->GetExternalDecl(ID));
963
964 assert(LazyInitializers.empty() &&
965 "GetExternalDecl for lazy module initializer added more inits");
966}
967
968void ASTContext::addModuleInitializer(Module *M, Decl *D) {
969 // One special case: if we add a module initializer that imports another
970 // module, and that module's only initializer is an ImportDecl, simplify.
971 if (auto *ID = dyn_cast<ImportDecl>(D)) {
972 auto It = ModuleInitializers.find(ID->getImportedModule());
973
974 // Maybe the ImportDecl does nothing at all. (Common case.)
975 if (It == ModuleInitializers.end())
976 return;
977
978 // Maybe the ImportDecl only imports another ImportDecl.
979 auto &Imported = *It->second;
980 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
981 Imported.resolve(*this);
982 auto *OnlyDecl = Imported.Initializers.front();
983 if (isa<ImportDecl>(OnlyDecl))
984 D = OnlyDecl;
985 }
986 }
987
988 auto *&Inits = ModuleInitializers[M];
989 if (!Inits)
990 Inits = new (*this) PerModuleInitializers;
991 Inits->Initializers.push_back(D);
992}
993
994void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
995 auto *&Inits = ModuleInitializers[M];
996 if (!Inits)
997 Inits = new (*this) PerModuleInitializers;
998 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
999 IDs.begin(), IDs.end());
1000}
1001
1002ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
1003 auto It = ModuleInitializers.find(M);
1004 if (It == ModuleInitializers.end())
1005 return None;
1006
1007 auto *Inits = It->second;
1008 Inits->resolve(*this);
1009 return Inits->Initializers;
1010}
1011
Richard Smithf19e1272015-03-07 00:04:49 +00001012ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1013 if (!ExternCContext)
1014 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1015
1016 return ExternCContext;
1017}
1018
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001019BuiltinTemplateDecl *
1020ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1021 const IdentifierInfo *II) const {
1022 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1023 BuiltinTemplate->setImplicit();
1024 TUDecl->addDecl(BuiltinTemplate);
1025
1026 return BuiltinTemplate;
1027}
1028
1029BuiltinTemplateDecl *
1030ASTContext::getMakeIntegerSeqDecl() const {
1031 if (!MakeIntegerSeqDecl)
1032 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1033 getMakeIntegerSeqName());
1034 return MakeIntegerSeqDecl;
1035}
1036
Eric Fiselier6ad68552016-07-01 01:24:09 +00001037BuiltinTemplateDecl *
1038ASTContext::getTypePackElementDecl() const {
1039 if (!TypePackElementDecl)
1040 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1041 getTypePackElementName());
1042 return TypePackElementDecl;
1043}
1044
Alp Toker2dea15b2013-12-17 01:22:38 +00001045RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1046 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001047 SourceLocation Loc;
1048 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001049 if (getLangOpts().CPlusPlus)
1050 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1051 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001052 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001053 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1054 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001055 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001056 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1057 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001058 return NewDecl;
1059}
1060
1061TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1062 StringRef Name) const {
1063 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1064 TypedefDecl *NewDecl = TypedefDecl::Create(
1065 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1066 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1067 NewDecl->setImplicit();
1068 return NewDecl;
1069}
1070
Douglas Gregor801c99d2011-08-12 06:49:56 +00001071TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001072 if (!Int128Decl)
1073 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001074 return Int128Decl;
1075}
1076
1077TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001078 if (!UInt128Decl)
1079 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001080 return UInt128Decl;
1081}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001082
John McCall48f2d582009-10-23 23:03:21 +00001083void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +00001084 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001085 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001086 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001087}
1088
Artem Belevichb5bc9232015-09-22 17:23:22 +00001089void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1090 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001091 assert((!this->Target || this->Target == &Target) &&
1092 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001093 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001094
Douglas Gregore8bbc122011-09-02 00:18:52 +00001095 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001096 this->AuxTarget = AuxTarget;
1097
Douglas Gregore8bbc122011-09-02 00:18:52 +00001098 ABI.reset(createCXXABI(Target));
1099 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001100 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001101
Chris Lattner970e54e2006-11-12 00:37:36 +00001102 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001103 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001104
Chris Lattner970e54e2006-11-12 00:37:36 +00001105 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001106 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001107 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001108 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001109 InitBuiltinType(CharTy, BuiltinType::Char_S);
1110 else
1111 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001112 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001113 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1114 InitBuiltinType(ShortTy, BuiltinType::Short);
1115 InitBuiltinType(IntTy, BuiltinType::Int);
1116 InitBuiltinType(LongTy, BuiltinType::Long);
1117 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001118
Chris Lattner970e54e2006-11-12 00:37:36 +00001119 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001120 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1121 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1122 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1123 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1124 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001125
Chris Lattner970e54e2006-11-12 00:37:36 +00001126 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001127 InitBuiltinType(FloatTy, BuiltinType::Float);
1128 InitBuiltinType(DoubleTy, BuiltinType::Double);
1129 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001130
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001131 // GNU extension, __float128 for IEEE quadruple precision
1132 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1133
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001134 // C11 extension ISO/IEC TS 18661-3
1135 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1136
Chris Lattnerf122cef2009-04-30 02:43:43 +00001137 // GNU extension, 128-bit integers.
1138 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1139 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1140
Hans Wennborg0d81e012013-05-10 10:08:40 +00001141 // C++ 3.9.1p5
1142 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1143 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1144 else // -fshort-wchar makes wchar_t be unsigned.
1145 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1146 if (LangOpts.CPlusPlus && LangOpts.WChar)
1147 WideCharTy = WCharTy;
1148 else {
1149 // C99 (or C++ using -fno-wchar).
1150 WideCharTy = getFromTargetType(Target.getWCharType());
1151 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001152
James Molloy36365542012-05-04 10:55:22 +00001153 WIntTy = getFromTargetType(Target.getWIntType());
1154
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001155 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1156 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1157 else // C99
1158 Char16Ty = getFromTargetType(Target.getChar16Type());
1159
1160 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1161 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1162 else // C99
1163 Char32Ty = getFromTargetType(Target.getChar32Type());
1164
Douglas Gregor4619e432008-12-05 23:32:09 +00001165 // Placeholder type for type-dependent expressions whose type is
1166 // completely unknown. No code should ever check a type against
1167 // DependentTy and users should never see it; however, it is here to
1168 // help diagnose failures to properly check for type-dependent
1169 // expressions.
1170 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001171
John McCall36e7fe32010-10-12 00:20:44 +00001172 // Placeholder type for functions.
1173 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1174
John McCall0009fcc2011-04-26 20:42:42 +00001175 // Placeholder type for bound members.
1176 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1177
John McCall526ab472011-10-25 17:37:35 +00001178 // Placeholder type for pseudo-objects.
1179 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1180
John McCall31996342011-04-07 08:22:57 +00001181 // "any" type; useful for debugger-like clients.
1182 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1183
John McCall8a6b59a2011-10-17 18:09:15 +00001184 // Placeholder type for unbridged ARC casts.
1185 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1186
Eli Friedman34866c72012-08-31 00:14:07 +00001187 // Placeholder type for builtin functions.
1188 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1189
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001190 // Placeholder type for OMP array sections.
1191 if (LangOpts.OpenMP)
1192 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1193
Chris Lattner970e54e2006-11-12 00:37:36 +00001194 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001195 FloatComplexTy = getComplexType(FloatTy);
1196 DoubleComplexTy = getComplexType(DoubleTy);
1197 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001198 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001199
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001200 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001201 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1202 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001203 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001204
Alexey Bader954ba212016-04-08 13:40:33 +00001205 if (LangOpts.OpenCL) {
1206#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1207 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001208#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001209
Guy Benyei61054192013-02-07 10:55:47 +00001210 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001211 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001212 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1213 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001214 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001215 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001216
1217 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001218 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1219 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001220
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001221 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001222
1223 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001224
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001225 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001226 if (LangOpts.OpenCLVersion >= 200) {
1227 auto Q = VoidTy.getQualifiers();
1228 Q.setAddressSpace(LangAS::opencl_generic);
1229 VoidPtrTy = getPointerType(getCanonicalType(
1230 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1231 } else {
1232 VoidPtrTy = getPointerType(VoidTy);
1233 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001234
1235 // nullptr type (C++0x 2.14.7)
1236 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001237
1238 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1239 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001240
1241 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001242 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001243}
1244
David Blaikie9c902b52011-09-25 23:23:43 +00001245DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001246 return SourceMgr.getDiagnostics();
1247}
1248
Douglas Gregor561eceb2010-08-30 16:49:28 +00001249AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1250 AttrVec *&Result = DeclAttrs[D];
1251 if (!Result) {
1252 void *Mem = Allocate(sizeof(AttrVec));
1253 Result = new (Mem) AttrVec;
1254 }
1255
1256 return *Result;
1257}
1258
1259/// \brief Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001260void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001261 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1262 if (Pos != DeclAttrs.end()) {
1263 Pos->second->~AttrVec();
1264 DeclAttrs.erase(Pos);
1265 }
1266}
1267
Larisse Voufo39a1e502013-08-06 01:03:05 +00001268// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001269MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001270ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001271 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001272 return getTemplateOrSpecializationInfo(Var)
1273 .dyn_cast<MemberSpecializationInfo *>();
1274}
1275
1276ASTContext::TemplateOrSpecializationInfo
1277ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1278 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1279 TemplateOrInstantiation.find(Var);
1280 if (Pos == TemplateOrInstantiation.end())
1281 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001282
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001283 return Pos->second;
1284}
1285
Mike Stump11289f42009-09-09 15:08:12 +00001286void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001287ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001288 TemplateSpecializationKind TSK,
1289 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001290 assert(Inst->isStaticDataMember() && "Not a static data member");
1291 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001292 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1293 Tmpl, TSK, PointOfInstantiation));
1294}
1295
1296void
1297ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1298 TemplateOrSpecializationInfo TSI) {
1299 assert(!TemplateOrInstantiation[Inst] &&
1300 "Already noted what the variable was instantiated from");
1301 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001302}
1303
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001304FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1305 const FunctionDecl *FD){
1306 assert(FD && "Specialization is 0");
1307 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001308 = ClassScopeSpecializationPattern.find(FD);
1309 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001310 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001311
1312 return Pos->second;
1313}
1314
1315void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1316 FunctionDecl *Pattern) {
1317 assert(FD && "Specialization is 0");
1318 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001319 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001320}
1321
John McCalle61f2ba2009-11-18 02:36:19 +00001322NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001323ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1324 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001325 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001326 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001327
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001328 return Pos->second;
1329}
1330
1331void
Richard Smithd8a9e372016-12-18 21:39:37 +00001332ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001333 assert((isa<UsingDecl>(Pattern) ||
1334 isa<UnresolvedUsingValueDecl>(Pattern) ||
1335 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1336 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001337 assert((isa<UsingDecl>(Inst) ||
1338 isa<UnresolvedUsingValueDecl>(Inst) ||
1339 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1340 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001341 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1342 InstantiatedFromUsingDecl[Inst] = Pattern;
1343}
1344
1345UsingShadowDecl *
1346ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1347 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1348 = InstantiatedFromUsingShadowDecl.find(Inst);
1349 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001350 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001351
1352 return Pos->second;
1353}
1354
1355void
1356ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1357 UsingShadowDecl *Pattern) {
1358 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1359 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001360}
1361
Anders Carlsson5da84842009-09-01 04:26:58 +00001362FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1363 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1364 = InstantiatedFromUnnamedFieldDecl.find(Field);
1365 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001366 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001367
Anders Carlsson5da84842009-09-01 04:26:58 +00001368 return Pos->second;
1369}
1370
1371void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1372 FieldDecl *Tmpl) {
1373 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1374 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1375 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1376 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001377
Anders Carlsson5da84842009-09-01 04:26:58 +00001378 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1379}
1380
Douglas Gregor832940b2010-03-02 23:58:15 +00001381ASTContext::overridden_cxx_method_iterator
1382ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001383 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001384}
1385
1386ASTContext::overridden_cxx_method_iterator
1387ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001388 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001389}
1390
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001391unsigned
1392ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001393 auto Range = overridden_methods(Method);
1394 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001395}
1396
Clement Courbet6ecaec82016-07-05 07:49:31 +00001397ASTContext::overridden_method_range
1398ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001399 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1400 OverriddenMethods.find(Method->getCanonicalDecl());
1401 if (Pos == OverriddenMethods.end())
1402 return overridden_method_range(nullptr, nullptr);
1403 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001404}
1405
Douglas Gregor832940b2010-03-02 23:58:15 +00001406void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1407 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001408 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001409 OverriddenMethods[Method].push_back(Overridden);
1410}
1411
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001412void ASTContext::getOverriddenMethods(
1413 const NamedDecl *D,
1414 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001415 assert(D);
1416
1417 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001418 Overridden.append(overridden_methods_begin(CXXMethod),
1419 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001420 return;
1421 }
1422
1423 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1424 if (!Method)
1425 return;
1426
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001427 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1428 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001429 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001430}
1431
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001432void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1433 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1434 assert(!Import->isFromASTFile() && "Non-local import declaration");
1435 if (!FirstLocalImport) {
1436 FirstLocalImport = Import;
1437 LastLocalImport = Import;
1438 return;
1439 }
1440
1441 LastLocalImport->NextLocalImport = Import;
1442 LastLocalImport = Import;
1443}
1444
Chris Lattner53cfe802007-07-18 17:52:12 +00001445//===----------------------------------------------------------------------===//
1446// Type Sizing and Analysis
1447//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001448
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001449/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1450/// scalar floating point type.
1451const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001452 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001453 assert(BT && "Not a floating point type!");
1454 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001455 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001456 case BuiltinType::Float16:
1457 case BuiltinType::Half:
1458 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001459 case BuiltinType::Float: return Target->getFloatFormat();
1460 case BuiltinType::Double: return Target->getDoubleFormat();
1461 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001462 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001463 }
1464}
1465
Rafael Espindola71eccb32013-08-08 19:53:46 +00001466CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001467 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001468
John McCall94268702010-10-08 18:24:19 +00001469 bool UseAlignAttrOnly = false;
1470 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1471 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001472
John McCall94268702010-10-08 18:24:19 +00001473 // __attribute__((aligned)) can increase or decrease alignment
1474 // *except* on a struct or struct member, where it only increases
1475 // alignment unless 'packed' is also specified.
1476 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001477 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001478 // ignore that possibility; Sema should diagnose it.
1479 if (isa<FieldDecl>(D)) {
1480 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1481 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1482 } else {
1483 UseAlignAttrOnly = true;
1484 }
1485 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001486 else if (isa<FieldDecl>(D))
1487 UseAlignAttrOnly =
1488 D->hasAttr<PackedAttr>() ||
1489 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001490
John McCall4e819612011-01-20 07:57:12 +00001491 // If we're using the align attribute only, just ignore everything
1492 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001493 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001494 // do nothing
John McCall94268702010-10-08 18:24:19 +00001495 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001496 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001497 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001498 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001499 T = RT->getPointeeType();
1500 else
1501 T = getPointerType(RT->getPointeeType());
1502 }
Richard Smithf6d70302014-06-10 23:34:28 +00001503 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001504 if (T->isFunctionType())
1505 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1506 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001507 // Adjust alignments of declarations with array type by the
1508 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001509 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001510 unsigned MinWidth = Target->getLargeArrayMinWidth();
1511 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001512 if (isa<VariableArrayType>(arrayType))
1513 Align = std::max(Align, Target->getLargeArrayAlign());
1514 else if (isa<ConstantArrayType>(arrayType) &&
1515 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1516 Align = std::max(Align, Target->getLargeArrayAlign());
1517 }
John McCall33ddac02011-01-19 10:06:00 +00001518 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001519 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001520 if (BaseT.getQualifiers().hasUnaligned())
1521 Align = Target->getCharWidth();
Ulrich Weigandfa806422013-05-06 16:23:57 +00001522 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001523 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001524 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1525 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001526 }
John McCall4e819612011-01-20 07:57:12 +00001527
1528 // Fields can be subject to extra alignment constraints, like if
1529 // the field is packed, the struct is packed, or the struct has a
1530 // a max-field-alignment constraint (#pragma pack). So calculate
1531 // the actual alignment of the field within the struct, and then
1532 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001533 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1534 const RecordDecl *Parent = Field->getParent();
1535 // We can only produce a sensible answer if the record is valid.
1536 if (!Parent->isInvalidDecl()) {
1537 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001538
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001539 // Start with the record's overall alignment.
1540 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001541
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001542 // Use the GCD of that and the offset within the record.
1543 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1544 if (Offset > 0) {
1545 // Alignment is always a power of 2, so the GCD will be a power of 2,
1546 // which means we get to do this crazy thing instead of Euclid's.
1547 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1548 if (LowBitOfOffset < FieldAlign)
1549 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1550 }
1551
1552 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001553 }
Charles Davis3fc51072010-02-23 04:52:00 +00001554 }
Chris Lattner68061312009-01-24 21:53:27 +00001555 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001556
Ken Dyckcc56c542011-01-15 18:38:59 +00001557 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001558}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001559
John McCallf1249922012-08-21 04:10:00 +00001560// getTypeInfoDataSizeInChars - Return the size of a type, in
1561// chars. If the type is a record, its data size is returned. This is
1562// the size of the memcpy that's performed when assigning this type
1563// using a trivial copy/move assignment operator.
1564std::pair<CharUnits, CharUnits>
1565ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1566 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1567
1568 // In C++, objects can sometimes be allocated into the tail padding
1569 // of a base-class subobject. We decide whether that's possible
1570 // during class layout, so here we can just trust the layout results.
1571 if (getLangOpts().CPlusPlus) {
1572 if (const RecordType *RT = T->getAs<RecordType>()) {
1573 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1574 sizeAndAlign.first = layout.getDataSize();
1575 }
1576 }
1577
1578 return sizeAndAlign;
1579}
1580
Richard Trieu04d2d942013-05-14 21:59:17 +00001581/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1582/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1583std::pair<CharUnits, CharUnits>
1584static getConstantArrayInfoInChars(const ASTContext &Context,
1585 const ConstantArrayType *CAT) {
1586 std::pair<CharUnits, CharUnits> EltInfo =
1587 Context.getTypeInfoInChars(CAT->getElementType());
1588 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001589 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1590 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001591 "Overflow in array type char size evaluation");
1592 uint64_t Width = EltInfo.first.getQuantity() * Size;
1593 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001594 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1595 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001596 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001597 return std::make_pair(CharUnits::fromQuantity(Width),
1598 CharUnits::fromQuantity(Align));
1599}
1600
John McCall87fe5d52010-05-20 01:18:31 +00001601std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001602ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001603 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1604 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001605 TypeInfo Info = getTypeInfo(T);
1606 return std::make_pair(toCharUnitsFromBits(Info.Width),
1607 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001608}
1609
1610std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001611ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001612 return getTypeInfoInChars(T.getTypePtr());
1613}
1614
David Majnemer34b57492014-07-30 01:30:47 +00001615bool ASTContext::isAlignmentRequired(const Type *T) const {
1616 return getTypeInfo(T).AlignIsRequired;
1617}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001618
David Majnemer34b57492014-07-30 01:30:47 +00001619bool ASTContext::isAlignmentRequired(QualType T) const {
1620 return isAlignmentRequired(T.getTypePtr());
1621}
1622
Richard Smithb2f0f052016-10-10 18:54:32 +00001623unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1624 // An alignment on a typedef overrides anything else.
1625 if (auto *TT = T->getAs<TypedefType>())
1626 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1627 return Align;
1628
1629 // If we have an (array of) complete type, we're done.
1630 T = getBaseElementType(T);
1631 if (!T->isIncompleteType())
1632 return getTypeAlign(T);
1633
1634 // If we had an array type, its element type might be a typedef
1635 // type with an alignment attribute.
1636 if (auto *TT = T->getAs<TypedefType>())
1637 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1638 return Align;
1639
1640 // Otherwise, see if the declaration of the type had an attribute.
1641 if (auto *TT = T->getAs<TagType>())
1642 return TT->getDecl()->getMaxAlignment();
1643
1644 return 0;
1645}
1646
David Majnemer34b57492014-07-30 01:30:47 +00001647TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001648 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1649 if (I != MemoizedTypeInfo.end())
1650 return I->second;
1651
1652 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1653 TypeInfo TI = getTypeInfoImpl(T);
1654 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001655 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001656}
1657
1658/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1659/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001660///
1661/// FIXME: Pointers into different addr spaces could have different sizes and
1662/// alignment requirements: getPointerInfo should take an AddrSpace, this
1663/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001664TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1665 uint64_t Width = 0;
1666 unsigned Align = 8;
1667 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001668 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001669 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001670#define TYPE(Class, Base)
1671#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001672#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001673#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001674#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1675 case Type::Class: \
1676 assert(!T->isDependentType() && "should not see dependent types here"); \
1677 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001678#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001679 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001680
Chris Lattner355332d2007-07-13 22:27:08 +00001681 case Type::FunctionNoProto:
1682 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001683 // GCC extension: alignof(function) = 32 bits
1684 Width = 0;
1685 Align = 32;
1686 break;
1687
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001688 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001689 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001690 Width = 0;
1691 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1692 break;
1693
Steve Naroff5c131802007-08-30 01:06:46 +00001694 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001695 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001696
David Majnemer34b57492014-07-30 01:30:47 +00001697 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001698 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001699 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001700 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001701 Width = EltInfo.Width * Size;
1702 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001703 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1704 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001705 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001706 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001707 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001708 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001709 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001710 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001711 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1712 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001713 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001714 // If the alignment is not a power of 2, round up to the next power of 2.
1715 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001716 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001717 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001718 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001719 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001720 // Adjust the alignment based on the target max.
1721 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1722 if (TargetVectorAlign && TargetVectorAlign < Align)
1723 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001724 break;
1725 }
Chris Lattner647fb222007-07-18 18:26:58 +00001726
Chris Lattner7570e9c2008-03-08 08:52:55 +00001727 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001728 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001729 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001730 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001731 // GCC extension: alignof(void) = 8 bits.
1732 Width = 0;
1733 Align = 8;
1734 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001735 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001736 Width = Target->getBoolWidth();
1737 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001738 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001739 case BuiltinType::Char_S:
1740 case BuiltinType::Char_U:
1741 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001742 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001743 Width = Target->getCharWidth();
1744 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001745 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001746 case BuiltinType::WChar_S:
1747 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001748 Width = Target->getWCharWidth();
1749 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001750 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001751 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001752 Width = Target->getChar16Width();
1753 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001754 break;
1755 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001756 Width = Target->getChar32Width();
1757 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001758 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001759 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001760 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001761 Width = Target->getShortWidth();
1762 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001763 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001764 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001765 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001766 Width = Target->getIntWidth();
1767 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001768 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001769 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001770 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001771 Width = Target->getLongWidth();
1772 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001773 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001774 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001775 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001776 Width = Target->getLongLongWidth();
1777 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001778 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001779 case BuiltinType::Int128:
1780 case BuiltinType::UInt128:
1781 Width = 128;
1782 Align = 128; // int128_t is 128-bit aligned on all targets.
1783 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001784 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001785 case BuiltinType::Half:
1786 Width = Target->getHalfWidth();
1787 Align = Target->getHalfAlign();
1788 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001789 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001790 Width = Target->getFloatWidth();
1791 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001792 break;
1793 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001794 Width = Target->getDoubleWidth();
1795 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001796 break;
1797 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001798 Width = Target->getLongDoubleWidth();
1799 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001800 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001801 case BuiltinType::Float128:
1802 Width = Target->getFloat128Width();
1803 Align = Target->getFloat128Align();
1804 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001805 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001806 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1807 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001808 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001809 case BuiltinType::ObjCId:
1810 case BuiltinType::ObjCClass:
1811 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001812 Width = Target->getPointerWidth(0);
1813 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001814 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001815 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001816 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001817 case BuiltinType::OCLClkEvent:
1818 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001819 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001820#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1821 case BuiltinType::Id:
1822#include "clang/Basic/OpenCLImageTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00001823 AS = getTargetAddressSpace(
1824 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001825 Width = Target->getPointerWidth(AS);
1826 Align = Target->getPointerAlign(AS);
1827 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001828 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001829 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001830 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001831 Width = Target->getPointerWidth(0);
1832 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001833 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001834 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001835 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001836 Width = Target->getPointerWidth(AS);
1837 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001838 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001839 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001840 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001841 // alignof and sizeof should never enter this code path here, so we go
1842 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001843 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001844 Width = Target->getPointerWidth(AS);
1845 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001846 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001847 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001848 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001849 Width = Target->getPointerWidth(AS);
1850 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001851 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001852 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001853 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00001854 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1855 Width = MPI.Width;
1856 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00001857 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001858 }
Chris Lattner647fb222007-07-18 18:26:58 +00001859 case Type::Complex: {
1860 // Complex types have the same alignment as their elements, but twice the
1861 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001862 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1863 Width = EltInfo.Width * 2;
1864 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001865 break;
1866 }
John McCall8b07ec22010-05-15 11:32:37 +00001867 case Type::ObjCObject:
1868 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001869 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001870 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001871 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001872 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001873 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001874 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001875 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001876 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001877 break;
1878 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001879 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001880 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001881 const TagType *TT = cast<TagType>(T);
1882
1883 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001884 Width = 8;
1885 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001886 break;
1887 }
Mike Stump11289f42009-09-09 15:08:12 +00001888
David Majnemer475b25e2015-01-21 10:54:38 +00001889 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1890 const EnumDecl *ED = ET->getDecl();
1891 TypeInfo Info =
1892 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1893 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1894 Info.Align = AttrAlign;
1895 Info.AlignIsRequired = true;
1896 }
1897 return Info;
1898 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001899
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001900 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001901 const RecordDecl *RD = RT->getDecl();
1902 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001903 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001904 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001905 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001906 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001907 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001908
Chris Lattner63d2b362009-10-22 05:17:15 +00001909 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001910 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1911 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001912
Richard Smith600b5262017-01-26 20:40:47 +00001913 case Type::Auto:
1914 case Type::DeducedTemplateSpecialization: {
1915 const DeducedType *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001916 assert(!A->getDeducedType().isNull() &&
1917 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001918 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001919 }
1920
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001921 case Type::Paren:
1922 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1923
Manman Rene6be26c2016-09-13 17:25:08 +00001924 case Type::ObjCTypeParam:
1925 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1926
Douglas Gregoref462e62009-04-30 17:32:17 +00001927 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001928 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001929 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001930 // If the typedef has an aligned attribute on it, it overrides any computed
1931 // alignment we have. This violates the GCC documentation (which says that
1932 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001933 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001934 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001935 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001936 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001937 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001938 AlignIsRequired = Info.AlignIsRequired;
1939 }
David Majnemer34b57492014-07-30 01:30:47 +00001940 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001941 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001942 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001943
Abramo Bagnara6150c882010-05-11 21:36:43 +00001944 case Type::Elaborated:
1945 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001946
John McCall81904512011-01-06 01:58:22 +00001947 case Type::Attributed:
1948 return getTypeInfo(
1949 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1950
Eli Friedman0dfb8892011-10-06 23:00:33 +00001951 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001952 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001953 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1954 Width = Info.Width;
1955 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001956
1957 // If the size of the type doesn't exceed the platform's max
1958 // atomic promotion width, make the size and alignment more
1959 // favorable to atomic operations:
1960 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1961 // Round the size up to a power of 2.
1962 if (!llvm::isPowerOf2_64(Width))
1963 Width = llvm::NextPowerOf2(Width);
1964
1965 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001966 Align = static_cast<unsigned>(Width);
1967 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001968 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001969 break;
1970
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001971 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00001972 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
1973 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001974 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00001975 }
Mike Stump11289f42009-09-09 15:08:12 +00001976
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001977 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001978 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001979}
1980
Alexey Bataev00396512015-07-02 03:40:19 +00001981unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1982 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1983 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1984 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1985 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1986 getTargetInfo().getABI() == "elfv1-qpx" &&
1987 T->isSpecificBuiltinType(BuiltinType::Double))
1988 SimdAlign = 256;
1989 return SimdAlign;
1990}
1991
Ken Dyckcc56c542011-01-15 18:38:59 +00001992/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1993CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1994 return CharUnits::fromQuantity(BitSize / getCharWidth());
1995}
1996
Ken Dyckb0fcc592011-02-11 01:54:29 +00001997/// toBits - Convert a size in characters to a size in characters.
1998int64_t ASTContext::toBits(CharUnits CharSize) const {
1999 return CharSize.getQuantity() * getCharWidth();
2000}
2001
Ken Dyck8c89d592009-12-22 14:23:30 +00002002/// getTypeSizeInChars - Return the size of the specified type, in characters.
2003/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002004CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002005 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002006}
Jay Foad39c79802011-01-12 09:06:06 +00002007CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002008 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002009}
2010
Ken Dycka6046ab2010-01-26 17:25:18 +00002011/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002012/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002013CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002014 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002015}
Jay Foad39c79802011-01-12 09:06:06 +00002016CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002017 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002018}
2019
Chris Lattnera3402cd2009-01-27 18:08:34 +00002020/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2021/// type for the current target in bits. This can be different than the ABI
2022/// alignment in cases where it is beneficial for performance to overalign
2023/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002024unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002025 TypeInfo TI = getTypeInfo(T);
2026 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002027
David Majnemere1544562015-04-24 01:25:05 +00002028 T = T->getBaseElementTypeUnsafe();
2029
2030 // The preferred alignment of member pointers is that of a pointer.
2031 if (T->isMemberPointerType())
2032 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2033
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002034 if (!Target->allowsLargerPreferedTypeAlignment())
2035 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002036
Eli Friedman7ab09572009-05-25 21:27:19 +00002037 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00002038 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002039 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00002040 if (const EnumType *ET = T->getAs<EnumType>())
2041 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002042 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002043 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2044 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002045 // Don't increase the alignment if an alignment attribute was specified on a
2046 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002047 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002048 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002049
Chris Lattnera3402cd2009-01-27 18:08:34 +00002050 return ABIAlign;
2051}
2052
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002053/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2054/// for __attribute__((aligned)) on this target, to be used if no alignment
2055/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002056unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002057 return getTargetInfo().getDefaultAlignForAttributeAligned();
2058}
2059
Ulrich Weigandfa806422013-05-06 16:23:57 +00002060/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2061/// to a global variable of the specified type.
2062unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2063 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2064}
2065
2066/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2067/// should be given to a global variable of the specified type.
2068CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2069 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2070}
2071
David Majnemer08ef2ba2015-06-23 20:34:18 +00002072CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2073 CharUnits Offset = CharUnits::Zero();
2074 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2075 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2076 Offset += Layout->getBaseClassOffset(Base);
2077 Layout = &getASTRecordLayout(Base);
2078 }
2079 return Offset;
2080}
2081
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002082/// DeepCollectObjCIvars -
2083/// This routine first collects all declared, but not synthesized, ivars in
2084/// super class and then collects all ivars, including those synthesized for
2085/// current class. This routine is used for implementation of current class
2086/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002087void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2088 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002089 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002090 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2091 DeepCollectObjCIvars(SuperClass, false, Ivars);
2092 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002093 for (const auto *I : OI->ivars())
2094 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002095 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002096 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002097 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002098 Iv= Iv->getNextIvar())
2099 Ivars.push_back(Iv);
2100 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002101}
2102
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002103/// CollectInheritedProtocols - Collect all protocols in current class and
2104/// those inherited by it.
2105void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002106 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002107 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002108 // We can use protocol_iterator here instead of
2109 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002110 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002111 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002112 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002113
2114 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002115 for (const auto *Cat : OI->visible_categories())
2116 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002117
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002118 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2119 while (SD) {
2120 CollectInheritedProtocols(SD, Protocols);
2121 SD = SD->getSuperClass();
2122 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002123 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002124 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002125 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002126 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002127 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002128 // Insert the protocol.
2129 if (!Protocols.insert(
2130 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2131 return;
2132
2133 for (auto *Proto : OP->protocols())
2134 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002135 }
2136}
2137
Erich Keane8a6b7402017-11-30 16:37:02 +00002138static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2139 const RecordDecl *RD) {
2140 assert(RD->isUnion() && "Must be union type");
2141 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2142
2143 for (const auto *Field : RD->fields()) {
2144 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2145 return false;
2146 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2147 if (FieldSize != UnionSize)
2148 return false;
2149 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002150 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002151}
2152
Benjamin Kramer802e6252017-12-24 12:46:22 +00002153static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002154 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2155
2156 if (!RD->field_empty())
2157 return false;
2158
2159 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2160 return ClassDecl->isEmpty();
2161
2162 return true;
2163}
2164
2165static llvm::Optional<int64_t>
2166structHasUniqueObjectRepresentations(const ASTContext &Context,
2167 const RecordDecl *RD) {
2168 assert(!RD->isUnion() && "Must be struct/class type");
2169 const auto &Layout = Context.getASTRecordLayout(RD);
2170
2171 int64_t CurOffsetInBits = 0;
2172 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2173 if (ClassDecl->isDynamicClass())
2174 return llvm::None;
2175
2176 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2177 for (const auto Base : ClassDecl->bases()) {
2178 // Empty types can be inherited from, and non-empty types can potentially
2179 // have tail padding, so just make sure there isn't an error.
2180 if (!isStructEmpty(Base.getType())) {
2181 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2182 Context, Base.getType()->getAs<RecordType>()->getDecl());
2183 if (!Size)
2184 return llvm::None;
2185 Bases.emplace_back(Base.getType(), Size.getValue());
2186 }
2187 }
2188
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00002189 llvm::sort(
Erich Keane8a6b7402017-11-30 16:37:02 +00002190 Bases.begin(), Bases.end(), [&](const std::pair<QualType, int64_t> &L,
2191 const std::pair<QualType, int64_t> &R) {
2192 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2193 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2194 });
2195
2196 for (const auto Base : Bases) {
2197 int64_t BaseOffset = Context.toBits(
2198 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2199 int64_t BaseSize = Base.second;
2200 if (BaseOffset != CurOffsetInBits)
2201 return llvm::None;
2202 CurOffsetInBits = BaseOffset + BaseSize;
2203 }
2204 }
2205
2206 for (const auto *Field : RD->fields()) {
2207 if (!Field->getType()->isReferenceType() &&
2208 !Context.hasUniqueObjectRepresentations(Field->getType()))
2209 return llvm::None;
2210
2211 int64_t FieldSizeInBits =
2212 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2213 if (Field->isBitField()) {
2214 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2215
2216 if (BitfieldSize > FieldSizeInBits)
2217 return llvm::None;
2218 FieldSizeInBits = BitfieldSize;
2219 }
2220
2221 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2222
2223 if (FieldOffsetInBits != CurOffsetInBits)
2224 return llvm::None;
2225
2226 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2227 }
2228
2229 return CurOffsetInBits;
2230}
2231
2232bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2233 // C++17 [meta.unary.prop]:
2234 // The predicate condition for a template specialization
2235 // has_unique_object_representations<T> shall be
2236 // satisfied if and only if:
2237 // (9.1) - T is trivially copyable, and
2238 // (9.2) - any two objects of type T with the same value have the same
2239 // object representation, where two objects
2240 // of array or non-union class type are considered to have the same value
2241 // if their respective sequences of
2242 // direct subobjects have the same values, and two objects of union type
2243 // are considered to have the same
2244 // value if they have the same active member and the corresponding members
2245 // have the same value.
2246 // The set of scalar types for which this condition holds is
2247 // implementation-defined. [ Note: If a type has padding
2248 // bits, the condition does not hold; otherwise, the condition holds true
2249 // for unsigned integral types. -- end note ]
2250 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2251
2252 // Arrays are unique only if their element type is unique.
2253 if (Ty->isArrayType())
2254 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2255
2256 // (9.1) - T is trivially copyable...
2257 if (!Ty.isTriviallyCopyableType(*this))
2258 return false;
2259
2260 // All integrals and enums are unique.
2261 if (Ty->isIntegralOrEnumerationType())
2262 return true;
2263
2264 // All other pointers are unique.
2265 if (Ty->isPointerType())
2266 return true;
2267
2268 if (Ty->isMemberPointerType()) {
2269 const MemberPointerType *MPT = Ty->getAs<MemberPointerType>();
2270 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2271 }
2272
2273 if (Ty->isRecordType()) {
2274 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2275
Erich Keanebd2197c2017-12-12 16:02:06 +00002276 if (Record->isInvalidDecl())
2277 return false;
2278
Erich Keane8a6b7402017-11-30 16:37:02 +00002279 if (Record->isUnion())
2280 return unionHasUniqueObjectRepresentations(*this, Record);
2281
2282 Optional<int64_t> StructSize =
2283 structHasUniqueObjectRepresentations(*this, Record);
2284
2285 return StructSize &&
2286 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2287 }
2288
2289 // FIXME: More cases to handle here (list by rsmith):
2290 // vectors (careful about, eg, vector of 3 foo)
2291 // _Complex int and friends
2292 // _Atomic T
2293 // Obj-C block pointers
2294 // Obj-C object pointers
2295 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2296 // clk_event_t, queue_t, reserve_id_t)
2297 // There're also Obj-C class types and the Obj-C selector type, but I think it
2298 // makes sense for those to return false here.
2299
2300 return false;
2301}
2302
Jay Foad39c79802011-01-12 09:06:06 +00002303unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002304 unsigned count = 0;
2305 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002306 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002307 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002308
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002309 // Count ivar defined in this class's implementation. This
2310 // includes synthesized ivars.
2311 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002312 count += ImplDecl->ivar_size();
2313
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002314 return count;
2315}
2316
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002317bool ASTContext::isSentinelNullExpr(const Expr *E) {
2318 if (!E)
2319 return false;
2320
2321 // nullptr_t is always treated as null.
2322 if (E->getType()->isNullPtrType()) return true;
2323
2324 if (E->getType()->isAnyPointerType() &&
2325 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2326 Expr::NPC_ValueDependentIsNull))
2327 return true;
2328
2329 // Unfortunately, __null has type 'int'.
2330 if (isa<GNUNullExpr>(E)) return true;
2331
2332 return false;
2333}
2334
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002335/// \brief Get the implementation of ObjCInterfaceDecl, or nullptr if none
2336/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002337ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2338 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2339 I = ObjCImpls.find(D);
2340 if (I != ObjCImpls.end())
2341 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002342 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002343}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002344
2345/// \brief Get the implementation of ObjCCategoryDecl, or nullptr if none
2346/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002347ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2348 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2349 I = ObjCImpls.find(D);
2350 if (I != ObjCImpls.end())
2351 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002352 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002353}
2354
2355/// \brief Set the implementation of ObjCInterfaceDecl.
2356void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2357 ObjCImplementationDecl *ImplD) {
2358 assert(IFaceD && ImplD && "Passed null params");
2359 ObjCImpls[IFaceD] = ImplD;
2360}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002361
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002362/// \brief Set the implementation of ObjCCategoryDecl.
2363void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2364 ObjCCategoryImplDecl *ImplD) {
2365 assert(CatD && ImplD && "Passed null params");
2366 ObjCImpls[CatD] = ImplD;
2367}
2368
Chandler Carruth21c90602015-12-30 03:24:14 +00002369const ObjCMethodDecl *
2370ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2371 return ObjCMethodRedecls.lookup(MD);
2372}
2373
2374void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2375 const ObjCMethodDecl *Redecl) {
2376 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2377 ObjCMethodRedecls[MD] = Redecl;
2378}
2379
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002380const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2381 const NamedDecl *ND) const {
2382 if (const ObjCInterfaceDecl *ID =
2383 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002384 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002385 if (const ObjCCategoryDecl *CD =
2386 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002387 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002388 if (const ObjCImplDecl *IMD =
2389 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002390 return IMD->getClassInterface();
2391
Craig Topper36250ad2014-05-12 05:36:57 +00002392 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002393}
2394
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002395/// \brief Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002396/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002397Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002398 assert(VD && "Passed null params");
2399 assert(VD->hasAttr<BlocksAttr>() &&
2400 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002401 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002402 I = BlockVarCopyInits.find(VD);
George Burgess IV00f70bd2018-03-01 05:43:23 +00002403 return (I != BlockVarCopyInits.end()) ? I->second : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002404}
2405
2406/// \brief Set the copy inialization expression of a block var decl.
2407void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2408 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002409 assert(VD->hasAttr<BlocksAttr>() &&
2410 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002411 BlockVarCopyInits[VD] = Init;
2412}
2413
John McCallbcd03502009-12-07 02:54:59 +00002414TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002415 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002416 if (!DataSize)
2417 DataSize = TypeLoc::getFullDataSizeForType(T);
2418 else
2419 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002420 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002421
John McCallbcd03502009-12-07 02:54:59 +00002422 TypeSourceInfo *TInfo =
2423 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2424 new (TInfo) TypeSourceInfo(T);
2425 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002426}
2427
John McCallbcd03502009-12-07 02:54:59 +00002428TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002429 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002430 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002431 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002432 return DI;
2433}
2434
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002435const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002436ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002437 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002438}
2439
2440const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002441ASTContext::getASTObjCImplementationLayout(
2442 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002443 return getObjCLayout(D->getClassInterface(), D);
2444}
2445
Chris Lattner983a8bb2007-07-13 22:13:22 +00002446//===----------------------------------------------------------------------===//
2447// Type creation/memoization methods
2448//===----------------------------------------------------------------------===//
2449
Jay Foad39c79802011-01-12 09:06:06 +00002450QualType
John McCall33ddac02011-01-19 10:06:00 +00002451ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2452 unsigned fastQuals = quals.getFastQualifiers();
2453 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002454
2455 // Check if we've already instantiated this type.
2456 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002457 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002458 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002459 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2460 assert(eq->getQualifiers() == quals);
2461 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002462 }
2463
John McCall33ddac02011-01-19 10:06:00 +00002464 // If the base type is not canonical, make the appropriate canonical type.
2465 QualType canon;
2466 if (!baseType->isCanonicalUnqualified()) {
2467 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002468 canonSplit.Quals.addConsistentQualifiers(quals);
2469 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002470
2471 // Re-find the insert position.
2472 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2473 }
2474
2475 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2476 ExtQualNodes.InsertNode(eq, insertPos);
2477 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002478}
2479
Alexander Richardson6d989432017-10-15 18:48:14 +00002480QualType ASTContext::getAddrSpaceQualType(QualType T,
2481 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002482 QualType CanT = getCanonicalType(T);
2483 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002484 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002485
John McCall8ccfcb52009-09-24 19:53:00 +00002486 // If we are composing extended qualifiers together, merge together
2487 // into one ExtQuals node.
2488 QualifierCollector Quals;
2489 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002490
John McCall8ccfcb52009-09-24 19:53:00 +00002491 // If this type already has an address space specified, it cannot get
2492 // another one.
2493 assert(!Quals.hasAddressSpace() &&
2494 "Type cannot be in multiple addr spaces!");
2495 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002496
John McCall8ccfcb52009-09-24 19:53:00 +00002497 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002498}
2499
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002500QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2501 // If we are composing extended qualifiers together, merge together
2502 // into one ExtQuals node.
2503 QualifierCollector Quals;
2504 const Type *TypeNode = Quals.strip(T);
2505
2506 // If the qualifier doesn't have an address space just return it.
2507 if (!Quals.hasAddressSpace())
2508 return T;
2509
2510 Quals.removeAddressSpace();
2511
2512 // Removal of the address space can mean there are no longer any
2513 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2514 // or required.
2515 if (Quals.hasNonFastQualifiers())
2516 return getExtQualType(TypeNode, Quals);
2517 else
2518 return QualType(TypeNode, Quals.getFastQualifiers());
2519}
2520
Chris Lattnerd60183d2009-02-18 22:53:11 +00002521QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002522 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002523 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002524 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002525 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002526
John McCall53fa7142010-12-24 02:08:15 +00002527 if (const PointerType *ptr = T->getAs<PointerType>()) {
2528 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002529 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002530 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2531 return getPointerType(ResultType);
2532 }
2533 }
Mike Stump11289f42009-09-09 15:08:12 +00002534
John McCall8ccfcb52009-09-24 19:53:00 +00002535 // If we are composing extended qualifiers together, merge together
2536 // into one ExtQuals node.
2537 QualifierCollector Quals;
2538 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002539
John McCall8ccfcb52009-09-24 19:53:00 +00002540 // If this type already has an ObjCGC specified, it cannot get
2541 // another one.
2542 assert(!Quals.hasObjCGCAttr() &&
2543 "Type cannot have multiple ObjCGCs!");
2544 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002545
John McCall8ccfcb52009-09-24 19:53:00 +00002546 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002547}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002548
John McCall4f5019e2010-12-19 02:44:49 +00002549const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2550 FunctionType::ExtInfo Info) {
2551 if (T->getExtInfo() == Info)
2552 return T;
2553
2554 QualType Result;
2555 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002556 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002557 } else {
2558 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2559 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2560 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002561 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002562 }
2563
2564 return cast<FunctionType>(Result.getTypePtr());
2565}
2566
Richard Smith2a7d4812013-05-04 07:00:32 +00002567void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2568 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002569 FD = FD->getMostRecentDecl();
2570 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002571 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2572 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002573 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002574 if (FunctionDecl *Next = FD->getPreviousDecl())
2575 FD = Next;
2576 else
2577 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002578 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002579 if (ASTMutationListener *L = getASTMutationListener())
2580 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002581}
2582
Richard Smith0b3a4622014-11-13 20:01:57 +00002583/// Get a function type and produce the equivalent function type with the
2584/// specified exception specification. Type sugar that can be present on a
2585/// declaration of a function with an exception specification is permitted
2586/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002587QualType ASTContext::getFunctionTypeWithExceptionSpec(
2588 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002589 // Might have some parens.
2590 if (auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002591 return getParenType(
2592 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002593
2594 // Might have a calling-convention attribute.
2595 if (auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002596 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002597 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002598 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2599 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002600
2601 // Anything else must be a function type. Rebuild it with the new exception
2602 // specification.
2603 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002604 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002605 Proto->getReturnType(), Proto->getParamTypes(),
2606 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2607}
2608
Richard Smithdfe85e22016-12-15 02:35:39 +00002609bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2610 QualType U) {
2611 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002612 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002613 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2614 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002615}
2616
Richard Smith0b3a4622014-11-13 20:01:57 +00002617void ASTContext::adjustExceptionSpec(
2618 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2619 bool AsWritten) {
2620 // Update the type.
2621 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002622 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002623 FD->setType(Updated);
2624
2625 if (!AsWritten)
2626 return;
2627
2628 // Update the type in the type source information too.
2629 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2630 // If the type and the type-as-written differ, we may need to update
2631 // the type-as-written too.
2632 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002633 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002634
2635 // FIXME: When we get proper type location information for exceptions,
2636 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2637 // up the TypeSourceInfo;
2638 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2639 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2640 "TypeLoc size mismatch from updating exception specification");
2641 TSInfo->overrideType(Updated);
2642 }
2643}
2644
Akira Hatanaka02914dc2018-02-05 20:23:22 +00002645bool ASTContext::isParamDestroyedInCallee(QualType T) const {
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00002646 if (getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
2647 return true;
2648 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2649 return RT->getDecl()->isParamDestroyedInCallee();
2650 return false;
Akira Hatanaka02914dc2018-02-05 20:23:22 +00002651}
2652
Chris Lattnerc6395932007-06-22 20:56:16 +00002653/// getComplexType - Return the uniqued reference to the type for a complex
2654/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002655QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002656 // Unique pointers, to guarantee there is only one pointer of a particular
2657 // structure.
2658 llvm::FoldingSetNodeID ID;
2659 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002660
Craig Topper36250ad2014-05-12 05:36:57 +00002661 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002662 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2663 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002664
Chris Lattnerc6395932007-06-22 20:56:16 +00002665 // If the pointee type isn't canonical, this won't be a canonical type either,
2666 // so fill in the canonical type field.
2667 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002668 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002669 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002670
Chris Lattnerc6395932007-06-22 20:56:16 +00002671 // Get the new insert position for the node we care about.
2672 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002673 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002674 }
John McCall90d1c2d2009-09-24 23:30:46 +00002675 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002676 Types.push_back(New);
2677 ComplexTypes.InsertNode(New, InsertPos);
2678 return QualType(New, 0);
2679}
2680
Chris Lattner970e54e2006-11-12 00:37:36 +00002681/// getPointerType - Return the uniqued reference to the type for a pointer to
2682/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002683QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002684 // Unique pointers, to guarantee there is only one pointer of a particular
2685 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002686 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002687 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002688
Craig Topper36250ad2014-05-12 05:36:57 +00002689 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002690 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002691 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002692
Chris Lattner7ccecb92006-11-12 08:50:50 +00002693 // If the pointee type isn't canonical, this won't be a canonical type either,
2694 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002695 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002696 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002697 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002698
Bob Wilsonc8541f22013-03-15 17:12:43 +00002699 // Get the new insert position for the node we care about.
2700 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002701 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002702 }
John McCall90d1c2d2009-09-24 23:30:46 +00002703 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002704 Types.push_back(New);
2705 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002706 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002707}
2708
Reid Kleckner0503a872013-12-05 01:23:43 +00002709QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2710 llvm::FoldingSetNodeID ID;
2711 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002712 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002713 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2714 if (AT)
2715 return QualType(AT, 0);
2716
2717 QualType Canonical = getCanonicalType(New);
2718
2719 // Get the new insert position for the node we care about.
2720 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002721 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002722
2723 AT = new (*this, TypeAlignment)
2724 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2725 Types.push_back(AT);
2726 AdjustedTypes.InsertNode(AT, InsertPos);
2727 return QualType(AT, 0);
2728}
2729
Reid Kleckner8a365022013-06-24 17:51:48 +00002730QualType ASTContext::getDecayedType(QualType T) const {
2731 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2732
Reid Kleckner8a365022013-06-24 17:51:48 +00002733 QualType Decayed;
2734
2735 // C99 6.7.5.3p7:
2736 // A declaration of a parameter as "array of type" shall be
2737 // adjusted to "qualified pointer to type", where the type
2738 // qualifiers (if any) are those specified within the [ and ] of
2739 // the array type derivation.
2740 if (T->isArrayType())
2741 Decayed = getArrayDecayedType(T);
2742
2743 // C99 6.7.5.3p8:
2744 // A declaration of a parameter as "function returning type"
2745 // shall be adjusted to "pointer to function returning type", as
2746 // in 6.3.2.1.
2747 if (T->isFunctionType())
2748 Decayed = getPointerType(T);
2749
Reid Kleckner0503a872013-12-05 01:23:43 +00002750 llvm::FoldingSetNodeID ID;
2751 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002752 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002753 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2754 if (AT)
2755 return QualType(AT, 0);
2756
Reid Kleckner8a365022013-06-24 17:51:48 +00002757 QualType Canonical = getCanonicalType(Decayed);
2758
2759 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002760 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002761 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002762
Reid Kleckner0503a872013-12-05 01:23:43 +00002763 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2764 Types.push_back(AT);
2765 AdjustedTypes.InsertNode(AT, InsertPos);
2766 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002767}
2768
Mike Stump11289f42009-09-09 15:08:12 +00002769/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002770/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002771QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002772 assert(T->isFunctionType() && "block of function types only");
2773 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002774 // structure.
2775 llvm::FoldingSetNodeID ID;
2776 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002777
Craig Topper36250ad2014-05-12 05:36:57 +00002778 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002779 if (BlockPointerType *PT =
2780 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2781 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002782
2783 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002784 // type either so fill in the canonical type field.
2785 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002786 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002787 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002788
Steve Naroffec33ed92008-08-27 16:04:49 +00002789 // Get the new insert position for the node we care about.
2790 BlockPointerType *NewIP =
2791 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002792 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002793 }
John McCall90d1c2d2009-09-24 23:30:46 +00002794 BlockPointerType *New
2795 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002796 Types.push_back(New);
2797 BlockPointerTypes.InsertNode(New, InsertPos);
2798 return QualType(New, 0);
2799}
2800
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002801/// getLValueReferenceType - Return the uniqued reference to the type for an
2802/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002803QualType
2804ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002805 assert(getCanonicalType(T) != OverloadTy &&
2806 "Unresolved overloaded function type");
2807
Bill Wendling3708c182007-05-27 10:15:43 +00002808 // Unique pointers, to guarantee there is only one pointer of a particular
2809 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002810 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002811 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002812
Craig Topper36250ad2014-05-12 05:36:57 +00002813 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002814 if (LValueReferenceType *RT =
2815 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002816 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002817
John McCallfc93cf92009-10-22 22:37:11 +00002818 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2819
Bill Wendling3708c182007-05-27 10:15:43 +00002820 // If the referencee type isn't canonical, this won't be a canonical type
2821 // either, so fill in the canonical type field.
2822 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002823 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2824 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2825 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002826
Bill Wendling3708c182007-05-27 10:15:43 +00002827 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002828 LValueReferenceType *NewIP =
2829 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002830 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002831 }
2832
John McCall90d1c2d2009-09-24 23:30:46 +00002833 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002834 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2835 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002836 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002837 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002838
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002839 return QualType(New, 0);
2840}
2841
2842/// getRValueReferenceType - Return the uniqued reference to the type for an
2843/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002844QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002845 // Unique pointers, to guarantee there is only one pointer of a particular
2846 // structure.
2847 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002848 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002849
Craig Topper36250ad2014-05-12 05:36:57 +00002850 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002851 if (RValueReferenceType *RT =
2852 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2853 return QualType(RT, 0);
2854
John McCallfc93cf92009-10-22 22:37:11 +00002855 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2856
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002857 // If the referencee type isn't canonical, this won't be a canonical type
2858 // either, so fill in the canonical type field.
2859 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002860 if (InnerRef || !T.isCanonical()) {
2861 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2862 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002863
2864 // Get the new insert position for the node we care about.
2865 RValueReferenceType *NewIP =
2866 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002867 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002868 }
2869
John McCall90d1c2d2009-09-24 23:30:46 +00002870 RValueReferenceType *New
2871 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002872 Types.push_back(New);
2873 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002874 return QualType(New, 0);
2875}
2876
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002877/// getMemberPointerType - Return the uniqued reference to the type for a
2878/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002879QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002880 // Unique pointers, to guarantee there is only one pointer of a particular
2881 // structure.
2882 llvm::FoldingSetNodeID ID;
2883 MemberPointerType::Profile(ID, T, Cls);
2884
Craig Topper36250ad2014-05-12 05:36:57 +00002885 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002886 if (MemberPointerType *PT =
2887 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2888 return QualType(PT, 0);
2889
2890 // If the pointee or class type isn't canonical, this won't be a canonical
2891 // type either, so fill in the canonical type field.
2892 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002893 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002894 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2895
2896 // Get the new insert position for the node we care about.
2897 MemberPointerType *NewIP =
2898 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002899 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002900 }
John McCall90d1c2d2009-09-24 23:30:46 +00002901 MemberPointerType *New
2902 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002903 Types.push_back(New);
2904 MemberPointerTypes.InsertNode(New, InsertPos);
2905 return QualType(New, 0);
2906}
2907
Mike Stump11289f42009-09-09 15:08:12 +00002908/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002909/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002910QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002911 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002912 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002913 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002914 assert((EltTy->isDependentType() ||
2915 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002916 "Constant array of VLAs is illegal!");
2917
Chris Lattnere2df3f92009-05-13 04:12:56 +00002918 // Convert the array size into a canonical width matching the pointer size for
2919 // the target.
2920 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00002921 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00002922
Chris Lattner23b7eb62007-06-15 23:05:46 +00002923 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002924 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002925
Craig Topper36250ad2014-05-12 05:36:57 +00002926 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002927 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002928 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002929 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002930
John McCall33ddac02011-01-19 10:06:00 +00002931 // If the element type isn't canonical or has qualifiers, this won't
2932 // be a canonical type either, so fill in the canonical type field.
2933 QualType Canon;
2934 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2935 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002936 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002937 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002938 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002939
Chris Lattner36f8e652007-01-27 08:31:04 +00002940 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002941 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002942 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002943 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002944 }
Mike Stump11289f42009-09-09 15:08:12 +00002945
John McCall90d1c2d2009-09-24 23:30:46 +00002946 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002947 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002948 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002949 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002950 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002951}
2952
John McCall06549462011-01-18 08:40:38 +00002953/// getVariableArrayDecayedType - Turns the given type, which may be
2954/// variably-modified, into the corresponding type with all the known
2955/// sizes replaced with [*].
2956QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2957 // Vastly most common case.
2958 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002959
John McCall06549462011-01-18 08:40:38 +00002960 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002961
John McCall06549462011-01-18 08:40:38 +00002962 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002963 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002964 switch (ty->getTypeClass()) {
2965#define TYPE(Class, Base)
2966#define ABSTRACT_TYPE(Class, Base)
2967#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2968#include "clang/AST/TypeNodes.def"
2969 llvm_unreachable("didn't desugar past all non-canonical types?");
2970
2971 // These types should never be variably-modified.
2972 case Type::Builtin:
2973 case Type::Complex:
2974 case Type::Vector:
2975 case Type::ExtVector:
2976 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002977 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00002978 case Type::ObjCObject:
2979 case Type::ObjCInterface:
2980 case Type::ObjCObjectPointer:
2981 case Type::Record:
2982 case Type::Enum:
2983 case Type::UnresolvedUsing:
2984 case Type::TypeOfExpr:
2985 case Type::TypeOf:
2986 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002987 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002988 case Type::DependentName:
2989 case Type::InjectedClassName:
2990 case Type::TemplateSpecialization:
2991 case Type::DependentTemplateSpecialization:
2992 case Type::TemplateTypeParm:
2993 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002994 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002995 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00002996 case Type::PackExpansion:
2997 llvm_unreachable("type should never be variably-modified");
2998
2999 // These types can be variably-modified but should never need to
3000 // further decay.
3001 case Type::FunctionNoProto:
3002 case Type::FunctionProto:
3003 case Type::BlockPointer:
3004 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003005 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003006 return type;
3007
3008 // These types can be variably-modified. All these modifications
3009 // preserve structure except as noted by comments.
3010 // TODO: if we ever care about optimizing VLAs, there are no-op
3011 // optimizations available here.
3012 case Type::Pointer:
3013 result = getPointerType(getVariableArrayDecayedType(
3014 cast<PointerType>(ty)->getPointeeType()));
3015 break;
3016
3017 case Type::LValueReference: {
3018 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
3019 result = getLValueReferenceType(
3020 getVariableArrayDecayedType(lv->getPointeeType()),
3021 lv->isSpelledAsLValue());
3022 break;
3023 }
3024
3025 case Type::RValueReference: {
3026 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
3027 result = getRValueReferenceType(
3028 getVariableArrayDecayedType(lv->getPointeeType()));
3029 break;
3030 }
3031
Eli Friedman0dfb8892011-10-06 23:00:33 +00003032 case Type::Atomic: {
3033 const AtomicType *at = cast<AtomicType>(ty);
3034 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3035 break;
3036 }
3037
John McCall06549462011-01-18 08:40:38 +00003038 case Type::ConstantArray: {
3039 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
3040 result = getConstantArrayType(
3041 getVariableArrayDecayedType(cat->getElementType()),
3042 cat->getSize(),
3043 cat->getSizeModifier(),
3044 cat->getIndexTypeCVRQualifiers());
3045 break;
3046 }
3047
3048 case Type::DependentSizedArray: {
3049 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
3050 result = getDependentSizedArrayType(
3051 getVariableArrayDecayedType(dat->getElementType()),
3052 dat->getSizeExpr(),
3053 dat->getSizeModifier(),
3054 dat->getIndexTypeCVRQualifiers(),
3055 dat->getBracketsRange());
3056 break;
3057 }
3058
3059 // Turn incomplete types into [*] types.
3060 case Type::IncompleteArray: {
3061 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
3062 result = getVariableArrayType(
3063 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003064 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003065 ArrayType::Normal,
3066 iat->getIndexTypeCVRQualifiers(),
3067 SourceRange());
3068 break;
3069 }
3070
3071 // Turn VLA types into [*] types.
3072 case Type::VariableArray: {
3073 const VariableArrayType *vat = cast<VariableArrayType>(ty);
3074 result = getVariableArrayType(
3075 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003076 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003077 ArrayType::Star,
3078 vat->getIndexTypeCVRQualifiers(),
3079 vat->getBracketsRange());
3080 break;
3081 }
3082 }
3083
3084 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003085 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003086}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003087
Steve Naroffcadebd02007-08-30 18:14:25 +00003088/// getVariableArrayType - Returns a non-unique reference to the type for a
3089/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003090QualType ASTContext::getVariableArrayType(QualType EltTy,
3091 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003092 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003093 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003094 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003095 // Since we don't unique expressions, it isn't possible to unique VLA's
3096 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003097 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003098
John McCall33ddac02011-01-19 10:06:00 +00003099 // Be sure to pull qualifiers off the element type.
3100 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3101 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003102 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003103 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003104 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003105 }
3106
John McCall90d1c2d2009-09-24 23:30:46 +00003107 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003108 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003109
3110 VariableArrayTypes.push_back(New);
3111 Types.push_back(New);
3112 return QualType(New, 0);
3113}
3114
Douglas Gregor4619e432008-12-05 23:32:09 +00003115/// getDependentSizedArrayType - Returns a non-unique reference to
3116/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003117/// type.
John McCall33ddac02011-01-19 10:06:00 +00003118QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3119 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003120 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003121 unsigned elementTypeQuals,
3122 SourceRange brackets) const {
3123 assert((!numElements || numElements->isTypeDependent() ||
3124 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003125 "Size must be type- or value-dependent!");
3126
John McCall33ddac02011-01-19 10:06:00 +00003127 // Dependently-sized array types that do not have a specified number
3128 // of elements will have their sizes deduced from a dependent
3129 // initializer. We do no canonicalization here at all, which is okay
3130 // because they can't be used in most locations.
3131 if (!numElements) {
3132 DependentSizedArrayType *newType
3133 = new (*this, TypeAlignment)
3134 DependentSizedArrayType(*this, elementType, QualType(),
3135 numElements, ASM, elementTypeQuals,
3136 brackets);
3137 Types.push_back(newType);
3138 return QualType(newType, 0);
3139 }
3140
3141 // Otherwise, we actually build a new type every time, but we
3142 // also build a canonical type.
3143
3144 SplitQualType canonElementType = getCanonicalType(elementType).split();
3145
Craig Topper36250ad2014-05-12 05:36:57 +00003146 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003147 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003148 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003149 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003150 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003151
John McCall33ddac02011-01-19 10:06:00 +00003152 // Look for an existing type with these properties.
3153 DependentSizedArrayType *canonTy =
3154 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003155
John McCall33ddac02011-01-19 10:06:00 +00003156 // If we don't have one, build one.
3157 if (!canonTy) {
3158 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003159 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003160 QualType(), numElements, ASM, elementTypeQuals,
3161 brackets);
3162 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3163 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003164 }
3165
John McCall33ddac02011-01-19 10:06:00 +00003166 // Apply qualifiers from the element type to the array.
3167 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003168 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003169
David Majnemer16a74702015-07-24 05:54:19 +00003170 // If we didn't need extra canonicalization for the element type or the size
3171 // expression, then just use that as our result.
3172 if (QualType(canonElementType.Ty, 0) == elementType &&
3173 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003174 return canon;
3175
3176 // Otherwise, we need to build a type which follows the spelling
3177 // of the element type.
3178 DependentSizedArrayType *sugaredType
3179 = new (*this, TypeAlignment)
3180 DependentSizedArrayType(*this, elementType, canon, numElements,
3181 ASM, elementTypeQuals, brackets);
3182 Types.push_back(sugaredType);
3183 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003184}
3185
John McCall33ddac02011-01-19 10:06:00 +00003186QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003187 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003188 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003189 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003190 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003191
Craig Topper36250ad2014-05-12 05:36:57 +00003192 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003193 if (IncompleteArrayType *iat =
3194 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3195 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003196
3197 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003198 // either, so fill in the canonical type field. We also have to pull
3199 // qualifiers off the element type.
3200 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003201
John McCall33ddac02011-01-19 10:06:00 +00003202 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3203 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003204 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003205 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003206 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003207
3208 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003209 IncompleteArrayType *existing =
3210 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3211 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003212 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003213
John McCall33ddac02011-01-19 10:06:00 +00003214 IncompleteArrayType *newType = new (*this, TypeAlignment)
3215 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003216
John McCall33ddac02011-01-19 10:06:00 +00003217 IncompleteArrayTypes.InsertNode(newType, insertPos);
3218 Types.push_back(newType);
3219 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003220}
3221
Steve Naroff91fcddb2007-07-18 18:00:27 +00003222/// getVectorType - Return the unique reference to a vector type of
3223/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003224QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003225 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003226 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003227
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003228 // Check if we've already instantiated a vector of this type.
3229 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003230 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003231
Craig Topper36250ad2014-05-12 05:36:57 +00003232 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003233 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3234 return QualType(VTP, 0);
3235
3236 // If the element type isn't canonical, this won't be a canonical type either,
3237 // so fill in the canonical type field.
3238 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003239 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003240 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003241
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003242 // Get the new insert position for the node we care about.
3243 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003244 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003245 }
John McCall90d1c2d2009-09-24 23:30:46 +00003246 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003247 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003248 VectorTypes.InsertNode(New, InsertPos);
3249 Types.push_back(New);
3250 return QualType(New, 0);
3251}
3252
Nate Begemance4d7fc2008-04-18 23:10:10 +00003253/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003254/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003255QualType
3256ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003257 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003258
Steve Naroff91fcddb2007-07-18 18:00:27 +00003259 // Check if we've already instantiated a vector of this type.
3260 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003261 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003262 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003263 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003264 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3265 return QualType(VTP, 0);
3266
3267 // If the element type isn't canonical, this won't be a canonical type either,
3268 // so fill in the canonical type field.
3269 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003270 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003271 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003272
Steve Naroff91fcddb2007-07-18 18:00:27 +00003273 // Get the new insert position for the node we care about.
3274 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003275 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003276 }
John McCall90d1c2d2009-09-24 23:30:46 +00003277 ExtVectorType *New = new (*this, TypeAlignment)
3278 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003279 VectorTypes.InsertNode(New, InsertPos);
3280 Types.push_back(New);
3281 return QualType(New, 0);
3282}
3283
Jay Foad39c79802011-01-12 09:06:06 +00003284QualType
3285ASTContext::getDependentSizedExtVectorType(QualType vecType,
3286 Expr *SizeExpr,
3287 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003288 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003289 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003290 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003291
Craig Topper36250ad2014-05-12 05:36:57 +00003292 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003293 DependentSizedExtVectorType *Canon
3294 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3295 DependentSizedExtVectorType *New;
3296 if (Canon) {
3297 // We already have a canonical version of this array type; use it as
3298 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003299 New = new (*this, TypeAlignment)
3300 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3301 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003302 } else {
3303 QualType CanonVecTy = getCanonicalType(vecType);
3304 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003305 New = new (*this, TypeAlignment)
3306 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3307 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003308
3309 DependentSizedExtVectorType *CanonCheck
3310 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3311 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3312 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003313 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3314 } else {
3315 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3316 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003317 New = new (*this, TypeAlignment)
3318 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003319 }
3320 }
Mike Stump11289f42009-09-09 15:08:12 +00003321
Douglas Gregor758a8692009-06-17 21:51:59 +00003322 Types.push_back(New);
3323 return QualType(New, 0);
3324}
3325
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003326QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3327 Expr *AddrSpaceExpr,
3328 SourceLocation AttrLoc) const {
3329 assert(AddrSpaceExpr->isInstantiationDependent());
3330
3331 QualType canonPointeeType = getCanonicalType(PointeeType);
3332
3333 void *insertPos = nullptr;
3334 llvm::FoldingSetNodeID ID;
3335 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3336 AddrSpaceExpr);
3337
3338 DependentAddressSpaceType *canonTy =
3339 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3340
3341 if (!canonTy) {
3342 canonTy = new (*this, TypeAlignment)
3343 DependentAddressSpaceType(*this, canonPointeeType,
3344 QualType(), AddrSpaceExpr, AttrLoc);
3345 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3346 Types.push_back(canonTy);
3347 }
3348
3349 if (canonPointeeType == PointeeType &&
3350 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
3351 return QualType(canonTy, 0);
3352
3353 DependentAddressSpaceType *sugaredType
3354 = new (*this, TypeAlignment)
3355 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
3356 AddrSpaceExpr, AttrLoc);
3357 Types.push_back(sugaredType);
3358 return QualType(sugaredType, 0);
3359}
3360
John McCall18afab72016-03-01 00:49:02 +00003361/// \brief Determine whether \p T is canonical as the result type of a function.
3362static bool isCanonicalResultType(QualType T) {
3363 return T.isCanonical() &&
3364 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3365 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3366}
3367
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003368/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003369QualType
3370ASTContext::getFunctionNoProtoType(QualType ResultTy,
3371 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003372 // Unique functions, to guarantee there is only one function of a particular
3373 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003374 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003375 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003376
Craig Topper36250ad2014-05-12 05:36:57 +00003377 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003378 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003379 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003380 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003381
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003382 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003383 if (!isCanonicalResultType(ResultTy)) {
3384 Canonical =
3385 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003386
Chris Lattner47955de2007-01-27 08:37:20 +00003387 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003388 FunctionNoProtoType *NewIP =
3389 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003390 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003391 }
Mike Stump11289f42009-09-09 15:08:12 +00003392
John McCall90d1c2d2009-09-24 23:30:46 +00003393 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003394 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003395 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003396 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003397 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003398}
3399
Douglas Gregora602a152015-10-01 20:20:47 +00003400CanQualType
3401ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3402 CanQualType CanResultType = getCanonicalType(ResultType);
3403
3404 // Canonical result types do not have ARC lifetime qualifiers.
3405 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3406 Qualifiers Qs = CanResultType.getQualifiers();
3407 Qs.removeObjCLifetime();
3408 return CanQualType::CreateUnsafe(
3409 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3410 }
3411
3412 return CanResultType;
3413}
3414
Richard Smith3c4f8d22016-10-16 17:54:23 +00003415static bool isCanonicalExceptionSpecification(
3416 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3417 if (ESI.Type == EST_None)
3418 return true;
3419 if (!NoexceptInType)
3420 return false;
3421
3422 // C++17 onwards: exception specification is part of the type, as a simple
3423 // boolean "can this function type throw".
3424 if (ESI.Type == EST_BasicNoexcept)
3425 return true;
3426
3427 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003428 // expansions (so we can't tell whether it's non-throwing) and all its
3429 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003430 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003431 bool AnyPackExpansions = false;
3432 for (QualType ET : ESI.Exceptions) {
3433 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003434 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003435 if (ET->getAs<PackExpansionType>())
3436 AnyPackExpansions = true;
3437 }
3438 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003439 }
3440
Richard Smith2a2cda52016-10-18 19:29:18 +00003441 // A noexcept(expr) specification is (possibly) canonical if expr is
3442 // value-dependent.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003443 if (ESI.Type == EST_ComputedNoexcept)
3444 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3445
3446 return false;
3447}
3448
Richard Smith304b1242016-10-18 20:13:25 +00003449QualType ASTContext::getFunctionTypeInternal(
3450 QualType ResultTy, ArrayRef<QualType> ArgArray,
3451 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003452 size_t NumArgs = ArgArray.size();
3453
Richard Smith2a2cda52016-10-18 19:29:18 +00003454 // Unique functions, to guarantee there is only one function of a particular
3455 // structure.
3456 llvm::FoldingSetNodeID ID;
3457 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3458 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003459
Richard Smith2a2cda52016-10-18 19:29:18 +00003460 QualType Canonical;
3461 bool Unique = false;
3462
3463 void *InsertPos = nullptr;
3464 if (FunctionProtoType *FPT =
3465 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3466 QualType Existing = QualType(FPT, 0);
3467
3468 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3469 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003470 // noexcept expression, or we're just looking for a canonical type.
3471 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003472 // sugar node to hold the concrete expression.
Richard Smith304b1242016-10-18 20:13:25 +00003473 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003474 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3475 return Existing;
3476
3477 // We need a new type sugar node for this one, to hold the new noexcept
3478 // expression. We do no canonicalization here, but that's OK since we don't
3479 // expect to see the same noexcept expression much more than once.
3480 Canonical = getCanonicalType(Existing);
3481 Unique = true;
3482 }
3483
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003484 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003485 bool IsCanonicalExceptionSpec =
3486 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3487
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003488 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003489 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003490 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003491 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003492 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003493 isCanonical = false;
3494
Richard Smith304b1242016-10-18 20:13:25 +00003495 if (OnlyWantCanonical)
3496 assert(isCanonical &&
3497 "given non-canonical parameters constructing canonical type");
3498
Richard Smith2a2cda52016-10-18 19:29:18 +00003499 // If this type isn't canonical, get the canonical version of it if we don't
3500 // already have it. The exception spec is only partially part of the
3501 // canonical type, and only in C++17 onwards.
3502 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003503 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003504 CanonicalArgs.reserve(NumArgs);
3505 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003506 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003507
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003508 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003509 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003510 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003511
3512 if (IsCanonicalExceptionSpec) {
3513 // Exception spec is already OK.
3514 } else if (NoexceptInType) {
3515 switch (EPI.ExceptionSpec.Type) {
3516 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3517 // We don't know yet. It shouldn't matter what we pick here; no-one
3518 // should ever look at this.
3519 LLVM_FALLTHROUGH;
Richard Smith2a2cda52016-10-18 19:29:18 +00003520 case EST_None: case EST_MSAny:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003521 CanonicalEPI.ExceptionSpec.Type = EST_None;
3522 break;
3523
Richard Smith2a2cda52016-10-18 19:29:18 +00003524 // A dynamic exception specification is almost always "not noexcept",
3525 // with the exception that a pack expansion might expand to no types.
3526 case EST_Dynamic: {
3527 bool AnyPacks = false;
3528 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3529 if (ET->getAs<PackExpansionType>())
3530 AnyPacks = true;
3531 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3532 }
3533 if (!AnyPacks)
3534 CanonicalEPI.ExceptionSpec.Type = EST_None;
3535 else {
3536 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3537 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3538 }
3539 break;
3540 }
3541
Richard Smith3c4f8d22016-10-16 17:54:23 +00003542 case EST_DynamicNone: case EST_BasicNoexcept:
3543 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3544 break;
3545
3546 case EST_ComputedNoexcept:
3547 llvm::APSInt Value(1);
3548 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3549 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3550 /*IsEvaluated*/false)) {
3551 // This noexcept specification is invalid.
3552 // FIXME: Should this be able to happen?
3553 CanonicalEPI.ExceptionSpec.Type = EST_None;
3554 break;
3555 }
3556
3557 CanonicalEPI.ExceptionSpec.Type =
3558 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3559 break;
3560 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003561 } else {
3562 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3563 }
John McCalldb40c7f2010-12-14 08:05:40 +00003564
Douglas Gregora602a152015-10-01 20:20:47 +00003565 // Adjust the canonical function result type.
3566 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003567 Canonical =
3568 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003569
Chris Lattnerfd4de792007-01-27 01:15:32 +00003570 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003571 FunctionProtoType *NewIP =
3572 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003573 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003574 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003575
John McCall31168b02011-06-15 23:02:42 +00003576 // FunctionProtoType objects are allocated with extra bytes after
3577 // them for three variable size arrays at the end:
3578 // - parameter types
3579 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003580 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003581 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003582 // expression, or information used to resolve the exception
3583 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003584 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003585 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003586
Richard Smith8acb4282014-07-31 21:57:55 +00003587 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3588 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3589 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003590 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003591 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003592 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003593 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003594 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003595 }
John McCall18afab72016-03-01 00:49:02 +00003596
3597 // Put the ExtParameterInfos last. If all were equal, it would make
3598 // more sense to put these before the exception specification, because
3599 // it's much easier to skip past them compared to the elaborate switch
3600 // required to skip the exception specification. However, all is not
3601 // equal; ExtParameterInfos are used to model very uncommon features,
3602 // and it's better not to burden the more common paths.
3603 if (EPI.ExtParameterInfos) {
3604 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3605 }
John McCall31168b02011-06-15 23:02:42 +00003606
John McCalldb40c7f2010-12-14 08:05:40 +00003607 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003608 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003609 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003610 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003611 if (!Unique)
3612 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003613 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003614}
Chris Lattneref51c202006-11-10 07:17:23 +00003615
Joey Goulye3c85de2016-12-01 11:30:49 +00003616QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003617 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003618 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003619
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003620 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003621 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003622 return QualType(PT, 0);
3623
3624 // If the pipe element type isn't canonical, this won't be a canonical type
3625 // either, so fill in the canonical type field.
3626 QualType Canonical;
3627 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003628 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003629
3630 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003631 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003632 assert(!NewIP && "Shouldn't be in the map!");
3633 (void)NewIP;
3634 }
Joey Goulye3c85de2016-12-01 11:30:49 +00003635 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003636 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003637 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003638 return QualType(New, 0);
3639}
3640
Joey Goulye3c85de2016-12-01 11:30:49 +00003641QualType ASTContext::getReadPipeType(QualType T) const {
3642 return getPipeType(T, true);
3643}
3644
Joey Gouly5788b782016-11-18 14:10:54 +00003645QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003646 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003647}
3648
John McCalle78aac42010-03-10 03:28:59 +00003649#ifndef NDEBUG
3650static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3651 if (!isa<CXXRecordDecl>(D)) return false;
3652 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3653 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3654 return true;
3655 if (RD->getDescribedClassTemplate() &&
3656 !isa<ClassTemplateSpecializationDecl>(RD))
3657 return true;
3658 return false;
3659}
3660#endif
3661
3662/// getInjectedClassNameType - Return the unique reference to the
3663/// injected class name type for the specified templated declaration.
3664QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003665 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003666 assert(NeedsInjectedClassNameType(Decl));
3667 if (Decl->TypeForDecl) {
3668 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003669 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003670 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3671 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3672 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3673 } else {
John McCall424cec92011-01-19 06:33:43 +00003674 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003675 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003676 Decl->TypeForDecl = newType;
3677 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003678 }
3679 return QualType(Decl->TypeForDecl, 0);
3680}
3681
Douglas Gregor83a586e2008-04-13 21:07:44 +00003682/// getTypeDeclType - Return the unique reference to the type for the
3683/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003684QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003685 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003686 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003687
Richard Smithdda56e42011-04-15 14:24:37 +00003688 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003689 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003690
John McCall96f0b5f2010-03-10 06:48:02 +00003691 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3692 "Template type parameter types are always available.");
3693
John McCall81e38502010-02-16 03:57:14 +00003694 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003695 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003696 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003697 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003698 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003699 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003700 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003701 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003702 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003703 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3704 Decl->TypeForDecl = newType;
3705 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003706 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003707 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003708
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003709 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003710}
3711
Chris Lattner32d920b2007-01-26 02:01:53 +00003712/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003713/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003714QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003715ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3716 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003717 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003718
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003719 if (Canonical.isNull())
3720 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003721 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003722 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003723 Decl->TypeForDecl = newType;
3724 Types.push_back(newType);
3725 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003726}
3727
Jay Foad39c79802011-01-12 09:06:06 +00003728QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003729 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3730
Douglas Gregorec9fd132012-01-14 16:38:05 +00003731 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003732 if (PrevDecl->TypeForDecl)
3733 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3734
John McCall424cec92011-01-19 06:33:43 +00003735 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3736 Decl->TypeForDecl = newType;
3737 Types.push_back(newType);
3738 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003739}
3740
Jay Foad39c79802011-01-12 09:06:06 +00003741QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003742 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3743
Douglas Gregorec9fd132012-01-14 16:38:05 +00003744 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003745 if (PrevDecl->TypeForDecl)
3746 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3747
John McCall424cec92011-01-19 06:33:43 +00003748 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3749 Decl->TypeForDecl = newType;
3750 Types.push_back(newType);
3751 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003752}
3753
John McCall81904512011-01-06 01:58:22 +00003754QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3755 QualType modifiedType,
3756 QualType equivalentType) {
3757 llvm::FoldingSetNodeID id;
3758 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3759
Craig Topper36250ad2014-05-12 05:36:57 +00003760 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003761 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3762 if (type) return QualType(type, 0);
3763
3764 QualType canon = getCanonicalType(equivalentType);
3765 type = new (*this, TypeAlignment)
3766 AttributedType(canon, attrKind, modifiedType, equivalentType);
3767
3768 Types.push_back(type);
3769 AttributedTypes.InsertNode(type, insertPos);
3770
3771 return QualType(type, 0);
3772}
3773
John McCallcebee162009-10-18 09:09:24 +00003774/// \brief Retrieve a substitution-result type.
3775QualType
3776ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003777 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003778 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003779 && "replacement types must always be canonical");
3780
3781 llvm::FoldingSetNodeID ID;
3782 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003783 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003784 SubstTemplateTypeParmType *SubstParm
3785 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3786
3787 if (!SubstParm) {
3788 SubstParm = new (*this, TypeAlignment)
3789 SubstTemplateTypeParmType(Parm, Replacement);
3790 Types.push_back(SubstParm);
3791 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3792 }
3793
3794 return QualType(SubstParm, 0);
3795}
3796
Douglas Gregorada4b792011-01-14 02:55:32 +00003797/// \brief Retrieve a
3798QualType ASTContext::getSubstTemplateTypeParmPackType(
3799 const TemplateTypeParmType *Parm,
3800 const TemplateArgument &ArgPack) {
3801#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003802 for (const auto &P : ArgPack.pack_elements()) {
3803 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3804 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003805 }
3806#endif
3807
3808 llvm::FoldingSetNodeID ID;
3809 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003810 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003811 if (SubstTemplateTypeParmPackType *SubstParm
3812 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3813 return QualType(SubstParm, 0);
3814
3815 QualType Canon;
3816 if (!Parm->isCanonicalUnqualified()) {
3817 Canon = getCanonicalType(QualType(Parm, 0));
3818 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3819 ArgPack);
3820 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3821 }
3822
3823 SubstTemplateTypeParmPackType *SubstParm
3824 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3825 ArgPack);
3826 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00003827 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Douglas Gregorada4b792011-01-14 02:55:32 +00003828 return QualType(SubstParm, 0);
3829}
3830
Douglas Gregoreff93e02009-02-05 23:33:38 +00003831/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003832/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003833/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003834QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003835 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003836 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003837 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003838 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003839 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003840 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003841 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3842
3843 if (TypeParm)
3844 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003845
Chandler Carruth08836322011-05-01 00:51:33 +00003846 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003847 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003848 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003849
3850 TemplateTypeParmType *TypeCheck
3851 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3852 assert(!TypeCheck && "Template type parameter canonical type broken");
3853 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003854 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003855 TypeParm = new (*this, TypeAlignment)
3856 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003857
3858 Types.push_back(TypeParm);
3859 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3860
3861 return QualType(TypeParm, 0);
3862}
3863
John McCalle78aac42010-03-10 03:28:59 +00003864TypeSourceInfo *
3865ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3866 SourceLocation NameLoc,
3867 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003868 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003869 assert(!Name.getAsDependentTemplateName() &&
3870 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003871 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003872
3873 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003874 TemplateSpecializationTypeLoc TL =
3875 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003876 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003877 TL.setTemplateNameLoc(NameLoc);
3878 TL.setLAngleLoc(Args.getLAngleLoc());
3879 TL.setRAngleLoc(Args.getRAngleLoc());
3880 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3881 TL.setArgLocInfo(i, Args[i].getLocInfo());
3882 return DI;
3883}
3884
Mike Stump11289f42009-09-09 15:08:12 +00003885QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003886ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003887 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003888 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003889 assert(!Template.getAsDependentTemplateName() &&
3890 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003891
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003892 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003893 ArgVec.reserve(Args.size());
3894 for (const TemplateArgumentLoc &Arg : Args.arguments())
3895 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003896
David Majnemer6fbeee32016-07-07 04:43:07 +00003897 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003898}
3899
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003900#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003901static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3902 for (const TemplateArgument &Arg : Args)
3903 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003904 return true;
3905
3906 return true;
3907}
3908#endif
3909
John McCall0ad16662009-10-29 08:12:44 +00003910QualType
3911ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003912 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003913 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003914 assert(!Template.getAsDependentTemplateName() &&
3915 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003916 // Look through qualified template names.
3917 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3918 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003919
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003920 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003921 Template.getAsTemplateDecl() &&
3922 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003923 QualType CanonType;
3924 if (!Underlying.isNull())
3925 CanonType = getCanonicalType(Underlying);
3926 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003927 // We can get here with an alias template when the specialization contains
3928 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003929 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003930 "Caller must compute aliased type");
3931 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003932 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003933 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003934
Douglas Gregora8e02e72009-07-28 23:00:59 +00003935 // Allocate the (non-canonical) template specialization type, but don't
3936 // try to unique it: these types typically have location information that
3937 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003938 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003939 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003940 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003941 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003942 TemplateSpecializationType *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003943 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003944 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003945
Douglas Gregor8bf42052009-02-09 18:46:07 +00003946 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003947 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003948}
3949
David Majnemer6fbeee32016-07-07 04:43:07 +00003950QualType ASTContext::getCanonicalTemplateSpecializationType(
3951 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003952 assert(!Template.getAsDependentTemplateName() &&
3953 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003954
Douglas Gregore29139c2011-03-03 17:04:51 +00003955 // Look through qualified template names.
3956 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3957 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003958
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003959 // Build the canonical template specialization type.
3960 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003961 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003962 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003963 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003964 for (const TemplateArgument &Arg : Args)
3965 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003966
3967 // Determine whether this canonical template specialization type already
3968 // exists.
3969 llvm::FoldingSetNodeID ID;
3970 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003971 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003972
Craig Topper36250ad2014-05-12 05:36:57 +00003973 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003974 TemplateSpecializationType *Spec
3975 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3976
3977 if (!Spec) {
3978 // Allocate a new canonical template specialization type.
3979 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3980 sizeof(TemplateArgument) * NumArgs),
3981 TypeAlignment);
3982 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003983 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003984 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003985 Types.push_back(Spec);
3986 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3987 }
3988
3989 assert(Spec->isDependentType() &&
3990 "Non-dependent template-id type must have a canonical type");
3991 return QualType(Spec, 0);
3992}
3993
3994QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003995ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3996 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003997 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003998 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003999 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00004000
Craig Topper36250ad2014-05-12 05:36:57 +00004001 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004002 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004003 if (T)
4004 return QualType(T, 0);
4005
Douglas Gregorc42075a2010-02-04 18:10:26 +00004006 QualType Canon = NamedType;
4007 if (!Canon.isCanonical()) {
4008 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004009 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4010 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004011 (void)CheckT;
4012 }
4013
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004014 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00004015 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004016 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004017 return QualType(T, 0);
4018}
4019
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004020QualType
Jay Foad39c79802011-01-12 09:06:06 +00004021ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004022 llvm::FoldingSetNodeID ID;
4023 ParenType::Profile(ID, InnerType);
4024
Craig Topper36250ad2014-05-12 05:36:57 +00004025 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004026 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4027 if (T)
4028 return QualType(T, 0);
4029
4030 QualType Canon = InnerType;
4031 if (!Canon.isCanonical()) {
4032 Canon = getCanonicalType(InnerType);
4033 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4034 assert(!CheckT && "Paren canonical type broken");
4035 (void)CheckT;
4036 }
4037
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004038 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004039 Types.push_back(T);
4040 ParenTypes.InsertNode(T, InsertPos);
4041 return QualType(T, 0);
4042}
4043
Douglas Gregor02085352010-03-31 20:19:30 +00004044QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4045 NestedNameSpecifier *NNS,
4046 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004047 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004048 if (Canon.isNull()) {
4049 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004050 if (CanonNNS != NNS)
4051 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004052 }
4053
4054 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004055 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004056
Craig Topper36250ad2014-05-12 05:36:57 +00004057 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004058 DependentNameType *T
4059 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004060 if (T)
4061 return QualType(T, 0);
4062
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004063 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004064 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004065 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004066 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004067}
4068
Mike Stump11289f42009-09-09 15:08:12 +00004069QualType
John McCallc392f372010-06-11 00:33:02 +00004070ASTContext::getDependentTemplateSpecializationType(
4071 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004072 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004073 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004074 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004075 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004076 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004077 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4078 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004079 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004080}
4081
4082QualType
4083ASTContext::getDependentTemplateSpecializationType(
4084 ElaboratedTypeKeyword Keyword,
4085 NestedNameSpecifier *NNS,
4086 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004087 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00004088 assert((!NNS || NNS->isDependent()) &&
4089 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004090
Douglas Gregorc42075a2010-02-04 18:10:26 +00004091 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004092 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004093 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004094
Craig Topper36250ad2014-05-12 05:36:57 +00004095 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004096 DependentTemplateSpecializationType *T
4097 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004098 if (T)
4099 return QualType(T, 0);
4100
John McCallc392f372010-06-11 00:33:02 +00004101 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004102
John McCallc392f372010-06-11 00:33:02 +00004103 ElaboratedTypeKeyword CanonKeyword = Keyword;
4104 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4105
4106 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004107 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004108 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004109 for (unsigned I = 0; I != NumArgs; ++I) {
4110 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4111 if (!CanonArgs[I].structurallyEquals(Args[I]))
4112 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004113 }
4114
John McCallc392f372010-06-11 00:33:02 +00004115 QualType Canon;
4116 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4117 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004118 Name,
4119 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004120
4121 // Find the insert position again.
4122 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4123 }
4124
4125 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4126 sizeof(TemplateArgument) * NumArgs),
4127 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004128 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004129 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004130 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004131 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004132 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004133}
4134
Richard Smith32918772017-02-14 00:25:28 +00004135TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4136 TemplateArgument Arg;
4137 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4138 QualType ArgType = getTypeDeclType(TTP);
4139 if (TTP->isParameterPack())
4140 ArgType = getPackExpansionType(ArgType, None);
4141
4142 Arg = TemplateArgument(ArgType);
4143 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4144 Expr *E = new (*this) DeclRefExpr(
4145 NTTP, /*enclosing*/false,
4146 NTTP->getType().getNonLValueExprType(*this),
4147 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4148
4149 if (NTTP->isParameterPack())
4150 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4151 None);
4152 Arg = TemplateArgument(E);
4153 } else {
4154 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4155 if (TTP->isParameterPack())
4156 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4157 else
4158 Arg = TemplateArgument(TemplateName(TTP));
4159 }
4160
4161 if (Param->isTemplateParameterPack())
4162 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4163
4164 return Arg;
4165}
4166
Richard Smith43e14d22016-12-23 02:10:11 +00004167void
4168ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4169 SmallVectorImpl<TemplateArgument> &Args) {
4170 Args.reserve(Args.size() + Params->size());
4171
Richard Smith32918772017-02-14 00:25:28 +00004172 for (NamedDecl *Param : *Params)
4173 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004174}
4175
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004176QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004177 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004178 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004179 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004180
4181 assert(Pattern->containsUnexpandedParameterPack() &&
4182 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004183 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004184 PackExpansionType *T
4185 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4186 if (T)
4187 return QualType(T, 0);
4188
4189 QualType Canon;
4190 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004191 Canon = getCanonicalType(Pattern);
4192 // The canonical type might not contain an unexpanded parameter pack, if it
4193 // contains an alias template specialization which ignores one of its
4194 // parameters.
4195 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004196 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004197
Richard Smith68eea502012-07-16 00:20:35 +00004198 // Find the insert position again, in case we inserted an element into
4199 // PackExpansionTypes and invalidated our insert position.
4200 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4201 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004202 }
4203
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004204 T = new (*this, TypeAlignment)
4205 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004206 Types.push_back(T);
4207 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004208 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004209}
4210
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004211/// CmpProtocolNames - Comparison predicate for sorting protocols
4212/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004213static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4214 ObjCProtocolDecl *const *RHS) {
4215 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004216}
4217
Craig Topper1f26d5b2016-01-03 19:43:23 +00004218static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4219 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004220
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004221 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4222 return false;
4223
Craig Topper1f26d5b2016-01-03 19:43:23 +00004224 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004225 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004226 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004227 return false;
4228 return true;
4229}
4230
Craig Topper6a8c1512015-10-22 01:56:18 +00004231static void
4232SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004233 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004234 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004235
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004236 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004237 for (ObjCProtocolDecl *&P : Protocols)
4238 P = P->getCanonicalDecl();
4239
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004240 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004241 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4242 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004243}
4244
John McCall8b07ec22010-05-15 11:32:37 +00004245QualType ASTContext::getObjCObjectType(QualType BaseType,
4246 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004247 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004248 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004249 llvm::makeArrayRef(Protocols, NumProtocols),
4250 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004251}
4252
4253QualType ASTContext::getObjCObjectType(
4254 QualType baseType,
4255 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004256 ArrayRef<ObjCProtocolDecl *> protocols,
4257 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004258 // If the base type is an interface and there aren't any protocols or
4259 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004260 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4261 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004262 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004263
4264 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004265 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004266 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004267 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004268 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4269 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004270
Douglas Gregore9d95f12015-07-07 03:57:35 +00004271 // Determine the type arguments to be used for canonicalization,
4272 // which may be explicitly specified here or written on the base
4273 // type.
4274 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4275 if (effectiveTypeArgs.empty()) {
4276 if (auto baseObject = baseType->getAs<ObjCObjectType>())
4277 effectiveTypeArgs = baseObject->getTypeArgs();
4278 }
John McCallfc93cf92009-10-22 22:37:11 +00004279
Douglas Gregore9d95f12015-07-07 03:57:35 +00004280 // Build the canonical type, which has the canonical base type and a
4281 // sorted-and-uniqued list of protocols and the type arguments
4282 // canonicalized.
4283 QualType canonical;
4284 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4285 effectiveTypeArgs.end(),
4286 [&](QualType type) {
4287 return type.isCanonical();
4288 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004289 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004290 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4291 // Determine the canonical type arguments.
4292 ArrayRef<QualType> canonTypeArgs;
4293 SmallVector<QualType, 4> canonTypeArgsVec;
4294 if (!typeArgsAreCanonical) {
4295 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4296 for (auto typeArg : effectiveTypeArgs)
4297 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4298 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004299 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004300 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004301 }
4302
Douglas Gregore9d95f12015-07-07 03:57:35 +00004303 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4304 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4305 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004306 canonProtocolsVec.append(protocols.begin(), protocols.end());
4307 SortAndUniqueProtocols(canonProtocolsVec);
4308 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004309 } else {
4310 canonProtocols = protocols;
4311 }
4312
4313 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004314 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004315
John McCallfc93cf92009-10-22 22:37:11 +00004316 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004317 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4318 }
4319
Douglas Gregore9d95f12015-07-07 03:57:35 +00004320 unsigned size = sizeof(ObjCObjectTypeImpl);
4321 size += typeArgs.size() * sizeof(QualType);
4322 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4323 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00004324 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004325 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4326 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004327
4328 Types.push_back(T);
4329 ObjCObjectTypes.InsertNode(T, InsertPos);
4330 return QualType(T, 0);
4331}
4332
Manman Ren3569eb52016-09-13 17:03:12 +00004333/// Apply Objective-C protocol qualifiers to the given type.
4334/// If this is for the canonical type of a type parameter, we can apply
4335/// protocol qualifiers on the ObjCObjectPointerType.
4336QualType
4337ASTContext::applyObjCProtocolQualifiers(QualType type,
4338 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4339 bool allowOnPointerType) const {
4340 hasError = false;
4341
Manman Renc5705ba2016-09-13 17:41:05 +00004342 if (const ObjCTypeParamType *objT =
4343 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4344 return getObjCTypeParamType(objT->getDecl(), protocols);
4345 }
4346
Manman Ren3569eb52016-09-13 17:03:12 +00004347 // Apply protocol qualifiers to ObjCObjectPointerType.
4348 if (allowOnPointerType) {
4349 if (const ObjCObjectPointerType *objPtr =
4350 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4351 const ObjCObjectType *objT = objPtr->getObjectType();
4352 // Merge protocol lists and construct ObjCObjectType.
4353 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4354 protocolsVec.append(objT->qual_begin(),
4355 objT->qual_end());
4356 protocolsVec.append(protocols.begin(), protocols.end());
4357 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4358 type = getObjCObjectType(
4359 objT->getBaseType(),
4360 objT->getTypeArgsAsWritten(),
4361 protocols,
4362 objT->isKindOfTypeAsWritten());
4363 return getObjCObjectPointerType(type);
4364 }
4365 }
4366
4367 // Apply protocol qualifiers to ObjCObjectType.
4368 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4369 // FIXME: Check for protocols to which the class type is already
4370 // known to conform.
4371
4372 return getObjCObjectType(objT->getBaseType(),
4373 objT->getTypeArgsAsWritten(),
4374 protocols,
4375 objT->isKindOfTypeAsWritten());
4376 }
4377
4378 // If the canonical type is ObjCObjectType, ...
4379 if (type->isObjCObjectType()) {
4380 // Silently overwrite any existing protocol qualifiers.
4381 // TODO: determine whether that's the right thing to do.
4382
4383 // FIXME: Check for protocols to which the class type is already
4384 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004385 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004386 }
4387
4388 // id<protocol-list>
4389 if (type->isObjCIdType()) {
4390 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004391 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004392 objPtr->isKindOfType());
4393 return getObjCObjectPointerType(type);
4394 }
4395
4396 // Class<protocol-list>
4397 if (type->isObjCClassType()) {
4398 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004399 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004400 objPtr->isKindOfType());
4401 return getObjCObjectPointerType(type);
4402 }
4403
4404 hasError = true;
4405 return type;
4406}
4407
Manman Rene6be26c2016-09-13 17:25:08 +00004408QualType
4409ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4410 ArrayRef<ObjCProtocolDecl *> protocols,
4411 QualType Canonical) const {
4412 // Look in the folding set for an existing type.
4413 llvm::FoldingSetNodeID ID;
4414 ObjCTypeParamType::Profile(ID, Decl, protocols);
4415 void *InsertPos = nullptr;
4416 if (ObjCTypeParamType *TypeParam =
4417 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4418 return QualType(TypeParam, 0);
4419
4420 if (Canonical.isNull()) {
4421 // We canonicalize to the underlying type.
4422 Canonical = getCanonicalType(Decl->getUnderlyingType());
4423 if (!protocols.empty()) {
4424 // Apply the protocol qualifers.
4425 bool hasError;
4426 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4427 true/*allowOnPointerType*/);
4428 assert(!hasError && "Error when apply protocol qualifier to bound type");
4429 }
4430 }
4431
4432 unsigned size = sizeof(ObjCTypeParamType);
4433 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4434 void *mem = Allocate(size, TypeAlignment);
4435 ObjCTypeParamType *newType = new (mem)
4436 ObjCTypeParamType(Decl, Canonical, protocols);
4437
4438 Types.push_back(newType);
4439 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4440 return QualType(newType, 0);
4441}
4442
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004443/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4444/// protocol list adopt all protocols in QT's qualified-id protocol
4445/// list.
4446bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4447 ObjCInterfaceDecl *IC) {
4448 if (!QT->isObjCQualifiedIdType())
4449 return false;
4450
4451 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4452 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004453 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004454 if (!IC->ClassImplementsProtocol(Proto, false))
4455 return false;
4456 }
4457 return true;
4458 }
4459 return false;
4460}
4461
4462/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4463/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4464/// of protocols.
4465bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4466 ObjCInterfaceDecl *IDecl) {
4467 if (!QT->isObjCQualifiedIdType())
4468 return false;
4469 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4470 if (!OPT)
4471 return false;
4472 if (!IDecl->hasDefinition())
4473 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004474 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4475 CollectInheritedProtocols(IDecl, InheritedProtocols);
4476 if (InheritedProtocols.empty())
4477 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004478 // Check that if every protocol in list of id<plist> conforms to a protcol
4479 // of IDecl's, then bridge casting is ok.
4480 bool Conforms = false;
4481 for (auto *Proto : OPT->quals()) {
4482 Conforms = false;
4483 for (auto *PI : InheritedProtocols) {
4484 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4485 Conforms = true;
4486 break;
4487 }
4488 }
4489 if (!Conforms)
4490 break;
4491 }
4492 if (Conforms)
4493 return true;
4494
Aaron Ballman83731462014-03-17 16:14:00 +00004495 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004496 // If both the right and left sides have qualifiers.
4497 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004498 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004499 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004500 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004501 break;
4502 }
4503 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004504 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004505 }
4506 return true;
4507}
4508
John McCall8b07ec22010-05-15 11:32:37 +00004509/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4510/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004511QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004512 llvm::FoldingSetNodeID ID;
4513 ObjCObjectPointerType::Profile(ID, ObjectT);
4514
Craig Topper36250ad2014-05-12 05:36:57 +00004515 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004516 if (ObjCObjectPointerType *QT =
4517 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4518 return QualType(QT, 0);
4519
4520 // Find the canonical object type.
4521 QualType Canonical;
4522 if (!ObjectT.isCanonical()) {
4523 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4524
4525 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004526 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4527 }
4528
Douglas Gregorf85bee62010-02-08 22:59:26 +00004529 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004530 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4531 ObjCObjectPointerType *QType =
4532 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004533
Steve Narofffb4330f2009-06-17 22:40:22 +00004534 Types.push_back(QType);
4535 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004536 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004537}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004538
Douglas Gregor1c283312010-08-11 12:19:30 +00004539/// getObjCInterfaceType - Return the unique reference to the type for the
4540/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004541QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4542 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004543 if (Decl->TypeForDecl)
4544 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004545
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004546 if (PrevDecl) {
4547 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4548 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4549 return QualType(PrevDecl->TypeForDecl, 0);
4550 }
4551
Douglas Gregor7671e532011-12-16 16:34:57 +00004552 // Prefer the definition, if there is one.
4553 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4554 Decl = Def;
4555
Douglas Gregor1c283312010-08-11 12:19:30 +00004556 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4557 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4558 Decl->TypeForDecl = T;
4559 Types.push_back(T);
4560 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004561}
4562
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004563/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4564/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004565/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004566/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004567/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004568QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004569 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004570 if (tofExpr->isTypeDependent()) {
4571 llvm::FoldingSetNodeID ID;
4572 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004573
Craig Topper36250ad2014-05-12 05:36:57 +00004574 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004575 DependentTypeOfExprType *Canon
4576 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4577 if (Canon) {
4578 // We already have a "canonical" version of an identical, dependent
4579 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004580 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004581 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004582 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004583 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004584 Canon
4585 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004586 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4587 toe = Canon;
4588 }
4589 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004590 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004591 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004592 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004593 Types.push_back(toe);
4594 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004595}
4596
Steve Naroffa773cd52007-08-01 18:02:17 +00004597/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004598/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004599/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004600/// an issue. This doesn't affect the type checker, since it operates
4601/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004602QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004603 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00004604 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004605 Types.push_back(tot);
4606 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004607}
4608
Richard Smith8eb1d322014-06-05 20:13:13 +00004609/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4610/// nodes. This would never be helpful, since each such type has its own
4611/// expression, and would not give a significant memory saving, since there
4612/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004613QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004614 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004615
4616 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004617 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004618 // unique dependent type. Two such decltype-specifiers refer to the same
4619 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004620 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004621 llvm::FoldingSetNodeID ID;
4622 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004623
Craig Topper36250ad2014-05-12 05:36:57 +00004624 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004625 DependentDecltypeType *Canon
4626 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004627 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004628 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004629 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004630 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004631 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004632 dt = new (*this, TypeAlignment)
4633 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004634 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004635 dt = new (*this, TypeAlignment)
4636 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004637 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004638 Types.push_back(dt);
4639 return QualType(dt, 0);
4640}
4641
Alexis Hunte852b102011-05-24 22:41:36 +00004642/// getUnaryTransformationType - We don't unique these, since the memory
4643/// savings are minimal and these are rare.
4644QualType ASTContext::getUnaryTransformType(QualType BaseType,
4645 QualType UnderlyingType,
4646 UnaryTransformType::UTTKind Kind)
4647 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004648 UnaryTransformType *ut = nullptr;
4649
4650 if (BaseType->isDependentType()) {
4651 // Look in the folding set for an existing type.
4652 llvm::FoldingSetNodeID ID;
4653 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4654
4655 void *InsertPos = nullptr;
4656 DependentUnaryTransformType *Canon
4657 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4658
4659 if (!Canon) {
4660 // Build a new, canonical __underlying_type(type) type.
4661 Canon = new (*this, TypeAlignment)
4662 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4663 Kind);
4664 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4665 }
4666 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4667 QualType(), Kind,
4668 QualType(Canon, 0));
4669 } else {
4670 QualType CanonType = getCanonicalType(UnderlyingType);
4671 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4672 UnderlyingType, Kind,
4673 CanonType);
4674 }
4675 Types.push_back(ut);
4676 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004677}
4678
Richard Smith2a7d4812013-05-04 07:00:32 +00004679/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4680/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4681/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004682QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004683 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004684 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004685 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004686
Richard Smith2a7d4812013-05-04 07:00:32 +00004687 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004688 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004689 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004690 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004691 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4692 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004693
Richard Smith74aeef52013-04-26 16:15:35 +00004694 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004695 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004696 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004697 Types.push_back(AT);
4698 if (InsertPos)
4699 AutoTypes.InsertNode(AT, InsertPos);
4700 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004701}
4702
Richard Smith600b5262017-01-26 20:40:47 +00004703/// Return the uniqued reference to the deduced template specialization type
4704/// which has been deduced to the given type, or to the canonical undeduced
4705/// such type, or the canonical deduced-but-dependent such type.
4706QualType ASTContext::getDeducedTemplateSpecializationType(
4707 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4708 // Look in the folding set for an existing type.
4709 void *InsertPos = nullptr;
4710 llvm::FoldingSetNodeID ID;
4711 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4712 IsDependent);
4713 if (DeducedTemplateSpecializationType *DTST =
4714 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4715 return QualType(DTST, 0);
4716
4717 DeducedTemplateSpecializationType *DTST = new (*this, TypeAlignment)
4718 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4719 Types.push_back(DTST);
4720 if (InsertPos)
4721 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4722 return QualType(DTST, 0);
4723}
4724
Eli Friedman0dfb8892011-10-06 23:00:33 +00004725/// getAtomicType - Return the uniqued reference to the atomic type for
4726/// the given value type.
4727QualType ASTContext::getAtomicType(QualType T) const {
4728 // Unique pointers, to guarantee there is only one pointer of a particular
4729 // structure.
4730 llvm::FoldingSetNodeID ID;
4731 AtomicType::Profile(ID, T);
4732
Craig Topper36250ad2014-05-12 05:36:57 +00004733 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004734 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4735 return QualType(AT, 0);
4736
4737 // If the atomic value type isn't canonical, this won't be a canonical type
4738 // either, so fill in the canonical type field.
4739 QualType Canonical;
4740 if (!T.isCanonical()) {
4741 Canonical = getAtomicType(getCanonicalType(T));
4742
4743 // Get the new insert position for the node we care about.
4744 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004745 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004746 }
4747 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4748 Types.push_back(New);
4749 AtomicTypes.InsertNode(New, InsertPos);
4750 return QualType(New, 0);
4751}
4752
Richard Smith02e85f32011-04-14 22:09:26 +00004753/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4754QualType ASTContext::getAutoDeductType() const {
4755 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004756 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004757 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004758 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004759 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004760 return AutoDeductTy;
4761}
4762
4763/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4764QualType ASTContext::getAutoRRefDeductType() const {
4765 if (AutoRRefDeductTy.isNull())
4766 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4767 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4768 return AutoRRefDeductTy;
4769}
4770
Chris Lattnerfb072462007-01-23 05:45:31 +00004771/// getTagDeclType - Return the unique reference to the type for the
4772/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004773QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004774 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004775 // FIXME: What is the design on getTagDeclType when it requires casting
4776 // away const? mutable?
4777 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004778}
4779
Mike Stump11289f42009-09-09 15:08:12 +00004780/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4781/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4782/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004783CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004784 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004785}
Chris Lattnerfb072462007-01-23 05:45:31 +00004786
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004787/// Return the unique signed counterpart of the integer type
4788/// corresponding to size_t.
4789CanQualType ASTContext::getSignedSizeType() const {
4790 return getFromTargetType(Target->getSignedSizeType());
4791}
4792
Hans Wennborg27541db2011-10-27 08:29:09 +00004793/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4794CanQualType ASTContext::getIntMaxType() const {
4795 return getFromTargetType(Target->getIntMaxType());
4796}
4797
4798/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4799CanQualType ASTContext::getUIntMaxType() const {
4800 return getFromTargetType(Target->getUIntMaxType());
4801}
4802
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004803/// getSignedWCharType - Return the type of "signed wchar_t".
4804/// Used when in C++, as a GCC extension.
4805QualType ASTContext::getSignedWCharType() const {
4806 // FIXME: derive from "Target" ?
4807 return WCharTy;
4808}
4809
4810/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4811/// Used when in C++, as a GCC extension.
4812QualType ASTContext::getUnsignedWCharType() const {
4813 // FIXME: derive from "Target" ?
4814 return UnsignedIntTy;
4815}
4816
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004817QualType ASTContext::getIntPtrType() const {
4818 return getFromTargetType(Target->getIntPtrType());
4819}
4820
4821QualType ASTContext::getUIntPtrType() const {
4822 return getCorrespondingUnsignedType(getIntPtrType());
4823}
4824
Hans Wennborg27541db2011-10-27 08:29:09 +00004825/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004826/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4827QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004828 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004829}
4830
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00004831/// \brief Return the unique unsigned counterpart of "ptrdiff_t"
4832/// integer type. The standard (C11 7.21.6.1p7) refers to this type
4833/// in the definition of %tu format specifier.
4834QualType ASTContext::getUnsignedPointerDiffType() const {
4835 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
4836}
4837
Eli Friedman4e91899e2012-11-27 02:58:24 +00004838/// \brief Return the unique type for "pid_t" defined in
4839/// <sys/types.h>. We need this to compute the correct type for vfork().
4840QualType ASTContext::getProcessIDType() const {
4841 return getFromTargetType(Target->getProcessIDType());
4842}
4843
Chris Lattnera21ad802008-04-02 05:18:44 +00004844//===----------------------------------------------------------------------===//
4845// Type Operators
4846//===----------------------------------------------------------------------===//
4847
Jay Foad39c79802011-01-12 09:06:06 +00004848CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004849 // Push qualifiers into arrays, and then discard any remaining
4850 // qualifiers.
4851 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004852 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004853 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004854 QualType Result;
4855 if (isa<ArrayType>(Ty)) {
4856 Result = getArrayDecayedType(QualType(Ty,0));
4857 } else if (isa<FunctionType>(Ty)) {
4858 Result = getPointerType(QualType(Ty, 0));
4859 } else {
4860 Result = QualType(Ty, 0);
4861 }
4862
4863 return CanQualType::CreateUnsafe(Result);
4864}
4865
John McCall6c9dd522011-01-18 07:41:22 +00004866QualType ASTContext::getUnqualifiedArrayType(QualType type,
4867 Qualifiers &quals) {
4868 SplitQualType splitType = type.getSplitUnqualifiedType();
4869
4870 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4871 // the unqualified desugared type and then drops it on the floor.
4872 // We then have to strip that sugar back off with
4873 // getUnqualifiedDesugaredType(), which is silly.
4874 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004875 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004876
4877 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004878 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004879 quals = splitType.Quals;
4880 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004881 }
4882
John McCall6c9dd522011-01-18 07:41:22 +00004883 // Otherwise, recurse on the array's element type.
4884 QualType elementType = AT->getElementType();
4885 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4886
4887 // If that didn't change the element type, AT has no qualifiers, so we
4888 // can just use the results in splitType.
4889 if (elementType == unqualElementType) {
4890 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004891 quals = splitType.Quals;
4892 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004893 }
4894
4895 // Otherwise, add in the qualifiers from the outermost type, then
4896 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004897 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004898
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004899 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004900 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004901 CAT->getSizeModifier(), 0);
4902 }
4903
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004904 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004905 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004906 }
4907
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004908 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004909 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004910 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004911 VAT->getSizeModifier(),
4912 VAT->getIndexTypeCVRQualifiers(),
4913 VAT->getBracketsRange());
4914 }
4915
4916 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004917 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004918 DSAT->getSizeModifier(), 0,
4919 SourceRange());
4920}
4921
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004922/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4923/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4924/// they point to and return true. If T1 and T2 aren't pointer types
4925/// or pointer-to-member types, or if they are not similar at this
4926/// level, returns false and leaves T1 and T2 unchanged. Top-level
4927/// qualifiers on T1 and T2 are ignored. This function will typically
4928/// be called in a loop that successively "unwraps" pointer and
4929/// pointer-to-member types to compare them at each level.
4930bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4931 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4932 *T2PtrType = T2->getAs<PointerType>();
4933 if (T1PtrType && T2PtrType) {
4934 T1 = T1PtrType->getPointeeType();
4935 T2 = T2PtrType->getPointeeType();
4936 return true;
4937 }
4938
4939 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4940 *T2MPType = T2->getAs<MemberPointerType>();
4941 if (T1MPType && T2MPType &&
4942 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4943 QualType(T2MPType->getClass(), 0))) {
4944 T1 = T1MPType->getPointeeType();
4945 T2 = T2MPType->getPointeeType();
4946 return true;
4947 }
4948
David Blaikiebbafb8a2012-03-11 07:00:24 +00004949 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004950 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4951 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4952 if (T1OPType && T2OPType) {
4953 T1 = T1OPType->getPointeeType();
4954 T2 = T2OPType->getPointeeType();
4955 return true;
4956 }
4957 }
4958
4959 // FIXME: Block pointers, too?
4960
4961 return false;
4962}
4963
Jay Foad39c79802011-01-12 09:06:06 +00004964DeclarationNameInfo
4965ASTContext::getNameForTemplate(TemplateName Name,
4966 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004967 switch (Name.getKind()) {
4968 case TemplateName::QualifiedTemplate:
4969 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004970 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004971 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4972 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004973
John McCalld9dfe3a2011-06-30 08:33:18 +00004974 case TemplateName::OverloadedTemplate: {
4975 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4976 // DNInfo work in progress: CHECKME: what about DNLoc?
4977 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4978 }
4979
4980 case TemplateName::DependentTemplate: {
4981 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004982 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004983 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004984 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4985 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004986 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004987 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4988 // DNInfo work in progress: FIXME: source locations?
4989 DeclarationNameLoc DNLoc;
4990 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4991 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4992 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004993 }
4994 }
4995
John McCalld9dfe3a2011-06-30 08:33:18 +00004996 case TemplateName::SubstTemplateTemplateParm: {
4997 SubstTemplateTemplateParmStorage *subst
4998 = Name.getAsSubstTemplateTemplateParm();
4999 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5000 NameLoc);
5001 }
5002
5003 case TemplateName::SubstTemplateTemplateParmPack: {
5004 SubstTemplateTemplateParmPackStorage *subst
5005 = Name.getAsSubstTemplateTemplateParmPack();
5006 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5007 NameLoc);
5008 }
5009 }
5010
5011 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005012}
5013
Jay Foad39c79802011-01-12 09:06:06 +00005014TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005015 switch (Name.getKind()) {
5016 case TemplateName::QualifiedTemplate:
5017 case TemplateName::Template: {
5018 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005019 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00005020 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005021 Template = getCanonicalTemplateTemplateParmDecl(TTP);
5022
5023 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005024 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005025 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005026
John McCalld9dfe3a2011-06-30 08:33:18 +00005027 case TemplateName::OverloadedTemplate:
5028 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00005029
John McCalld9dfe3a2011-06-30 08:33:18 +00005030 case TemplateName::DependentTemplate: {
5031 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5032 assert(DTN && "Non-dependent template names must refer to template decls.");
5033 return DTN->CanonicalTemplateName;
5034 }
5035
5036 case TemplateName::SubstTemplateTemplateParm: {
5037 SubstTemplateTemplateParmStorage *subst
5038 = Name.getAsSubstTemplateTemplateParm();
5039 return getCanonicalTemplateName(subst->getReplacement());
5040 }
5041
5042 case TemplateName::SubstTemplateTemplateParmPack: {
5043 SubstTemplateTemplateParmPackStorage *subst
5044 = Name.getAsSubstTemplateTemplateParmPack();
5045 TemplateTemplateParmDecl *canonParameter
5046 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5047 TemplateArgument canonArgPack
5048 = getCanonicalTemplateArgument(subst->getArgumentPack());
5049 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5050 }
5051 }
5052
5053 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005054}
5055
Douglas Gregoradee3e32009-11-11 23:06:43 +00005056bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5057 X = getCanonicalTemplateName(X);
5058 Y = getCanonicalTemplateName(Y);
5059 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5060}
5061
Mike Stump11289f42009-09-09 15:08:12 +00005062TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005063ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005064 switch (Arg.getKind()) {
5065 case TemplateArgument::Null:
5066 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005067
Douglas Gregora8e02e72009-07-28 23:00:59 +00005068 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005069 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005070
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005071 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00005072 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005073 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005074 }
Mike Stump11289f42009-09-09 15:08:12 +00005075
Eli Friedmanb826a002012-09-26 02:36:12 +00005076 case TemplateArgument::NullPtr:
5077 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5078 /*isNullPtr*/true);
5079
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005080 case TemplateArgument::Template:
5081 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005082
5083 case TemplateArgument::TemplateExpansion:
5084 return TemplateArgument(getCanonicalTemplateName(
5085 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005086 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005087
Douglas Gregora8e02e72009-07-28 23:00:59 +00005088 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005089 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005090
Douglas Gregora8e02e72009-07-28 23:00:59 +00005091 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005092 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005093
Douglas Gregora8e02e72009-07-28 23:00:59 +00005094 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005095 if (Arg.pack_size() == 0)
5096 return Arg;
5097
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005098 TemplateArgument *CanonArgs
5099 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005100 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005101 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005102 AEnd = Arg.pack_end();
5103 A != AEnd; (void)++A, ++Idx)
5104 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005105
Benjamin Kramercce63472015-08-05 09:40:22 +00005106 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005107 }
5108 }
5109
5110 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005111 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005112}
5113
Douglas Gregor333489b2009-03-27 23:10:48 +00005114NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005115ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005116 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005117 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005118
5119 switch (NNS->getKind()) {
5120 case NestedNameSpecifier::Identifier:
5121 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005122 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005123 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5124 NNS->getAsIdentifier());
5125
5126 case NestedNameSpecifier::Namespace:
5127 // A namespace is canonical; build a nested-name-specifier with
5128 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005129 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005130 NNS->getAsNamespace()->getOriginalNamespace());
5131
5132 case NestedNameSpecifier::NamespaceAlias:
5133 // A namespace is canonical; build a nested-name-specifier with
5134 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005135 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005136 NNS->getAsNamespaceAlias()->getNamespace()
5137 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005138
5139 case NestedNameSpecifier::TypeSpec:
5140 case NestedNameSpecifier::TypeSpecWithTemplate: {
5141 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005142
5143 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5144 // break it apart into its prefix and identifier, then reconsititute those
5145 // as the canonical nested-name-specifier. This is required to canonicalize
5146 // a dependent nested-name-specifier involving typedefs of dependent-name
5147 // types, e.g.,
5148 // typedef typename T::type T1;
5149 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00005150 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
5151 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005152 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005153
Eli Friedman5358a0a2012-03-03 04:09:56 +00005154 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5155 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5156 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005157 return NestedNameSpecifier::Create(*this, nullptr, false,
5158 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005159 }
5160
5161 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005162 case NestedNameSpecifier::Super:
5163 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005164 return NNS;
5165 }
5166
David Blaikie8a40f702012-01-17 06:56:22 +00005167 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005168}
5169
Jay Foad39c79802011-01-12 09:06:06 +00005170const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005171 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005172 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005173 // Handle the common positive case fast.
5174 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
5175 return AT;
5176 }
Mike Stump11289f42009-09-09 15:08:12 +00005177
John McCall8ccfcb52009-09-24 19:53:00 +00005178 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005179 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005180 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005181
John McCall8ccfcb52009-09-24 19:53:00 +00005182 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005183 // implements C99 6.7.3p8: "If the specification of an array type includes
5184 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005185
Chris Lattner7adf0762008-08-04 07:31:14 +00005186 // If we get here, we either have type qualifiers on the type, or we have
5187 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005188 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005189
John McCall33ddac02011-01-19 10:06:00 +00005190 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005191 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005192
Chris Lattner7adf0762008-08-04 07:31:14 +00005193 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00005194 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005195 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005196 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005197
Chris Lattner7adf0762008-08-04 07:31:14 +00005198 // Otherwise, we have an array and we have qualifiers on it. Push the
5199 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005200 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005201
Chris Lattner7adf0762008-08-04 07:31:14 +00005202 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
5203 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5204 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005205 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00005206 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
5207 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5208 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005209 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005210
Mike Stump11289f42009-09-09 15:08:12 +00005211 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00005212 = dyn_cast<DependentSizedArrayType>(ATy))
5213 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005214 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005215 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005216 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005217 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005218 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005219
Chris Lattner7adf0762008-08-04 07:31:14 +00005220 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005221 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005222 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005223 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005224 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005225 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005226}
5227
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005228QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005229 if (T->isArrayType() || T->isFunctionType())
5230 return getDecayedType(T);
5231 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005232}
5233
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005234QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005235 T = getVariableArrayDecayedType(T);
5236 T = getAdjustedParameterType(T);
5237 return T.getUnqualifiedType();
5238}
5239
David Majnemerd09a51c2015-03-03 01:50:05 +00005240QualType ASTContext::getExceptionObjectType(QualType T) const {
5241 // C++ [except.throw]p3:
5242 // A throw-expression initializes a temporary object, called the exception
5243 // object, the type of which is determined by removing any top-level
5244 // cv-qualifiers from the static type of the operand of throw and adjusting
5245 // the type from "array of T" or "function returning T" to "pointer to T"
5246 // or "pointer to function returning T", [...]
5247 T = getVariableArrayDecayedType(T);
5248 if (T->isArrayType() || T->isFunctionType())
5249 T = getDecayedType(T);
5250 return T.getUnqualifiedType();
5251}
5252
Chris Lattnera21ad802008-04-02 05:18:44 +00005253/// getArrayDecayedType - Return the properly qualified result of decaying the
5254/// specified array type to a pointer. This operation is non-trivial when
5255/// handling typedefs etc. The canonical type of "T" must be an array type,
5256/// this returns a pointer to a properly qualified element of the array.
5257///
5258/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005259QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005260 // Get the element type with 'getAsArrayType' so that we don't lose any
5261 // typedefs in the element type of the array. This also handles propagation
5262 // of type qualifiers from the array type into the element type if present
5263 // (C99 6.7.3p8).
5264 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5265 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005266
Chris Lattner7adf0762008-08-04 07:31:14 +00005267 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005268
5269 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005270 QualType Result = getQualifiedType(PtrTy,
5271 PrettyArrayType->getIndexTypeQualifiers());
5272
5273 // int x[_Nullable] -> int * _Nullable
5274 if (auto Nullability = Ty->getNullability(*this)) {
5275 Result = const_cast<ASTContext *>(this)->getAttributedType(
5276 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5277 }
5278 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005279}
5280
John McCall33ddac02011-01-19 10:06:00 +00005281QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5282 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005283}
5284
John McCall33ddac02011-01-19 10:06:00 +00005285QualType ASTContext::getBaseElementType(QualType type) const {
5286 Qualifiers qs;
5287 while (true) {
5288 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005289 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005290 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005291
John McCall33ddac02011-01-19 10:06:00 +00005292 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005293 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005294 }
Mike Stump11289f42009-09-09 15:08:12 +00005295
John McCall33ddac02011-01-19 10:06:00 +00005296 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005297}
5298
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005299/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005300uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005301ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5302 uint64_t ElementCount = 1;
5303 do {
5304 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005305 CA = dyn_cast_or_null<ConstantArrayType>(
5306 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005307 } while (CA);
5308 return ElementCount;
5309}
5310
Steve Naroff0af91202007-04-27 21:51:21 +00005311/// getFloatingRank - Return a relative rank for floating point types.
5312/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005313static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00005314 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005315 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005316
John McCall9dd450b2009-09-21 23:43:11 +00005317 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5318 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005319 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005320 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005321 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005322 case BuiltinType::Float: return FloatRank;
5323 case BuiltinType::Double: return DoubleRank;
5324 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005325 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005326 }
5327}
5328
Mike Stump11289f42009-09-09 15:08:12 +00005329/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5330/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005331/// 'typeDomain' is a real floating point or complex type.
5332/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005333QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5334 QualType Domain) const {
5335 FloatingRank EltRank = getFloatingRank(Size);
5336 if (Domain->isComplexType()) {
5337 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005338 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005339 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005340 case FloatRank: return FloatComplexTy;
5341 case DoubleRank: return DoubleComplexTy;
5342 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005343 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005344 }
Steve Naroff0af91202007-04-27 21:51:21 +00005345 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005346
5347 assert(Domain->isRealFloatingType() && "Unknown domain!");
5348 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005349 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005350 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005351 case FloatRank: return FloatTy;
5352 case DoubleRank: return DoubleTy;
5353 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005354 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005355 }
David Blaikief47fa302012-01-17 02:30:50 +00005356 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005357}
5358
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005359/// getFloatingTypeOrder - Compare the rank of the two specified floating
5360/// point types, ignoring the domain of the type (i.e. 'double' ==
5361/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005362/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005363int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005364 FloatingRank LHSR = getFloatingRank(LHS);
5365 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005366
Chris Lattnerb90739d2008-04-06 23:38:49 +00005367 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005368 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005369 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005370 return 1;
5371 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005372}
5373
Chris Lattner76a00cf2008-04-06 22:59:24 +00005374/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5375/// routine will assert if passed a built-in type that isn't an integer or enum,
5376/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005377unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005378 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005379
Chris Lattner76a00cf2008-04-06 22:59:24 +00005380 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005381 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005382 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005383 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005384 case BuiltinType::Char_S:
5385 case BuiltinType::Char_U:
5386 case BuiltinType::SChar:
5387 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005388 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005389 case BuiltinType::Short:
5390 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005391 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005392 case BuiltinType::Int:
5393 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005394 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005395 case BuiltinType::Long:
5396 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005397 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005398 case BuiltinType::LongLong:
5399 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005400 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005401 case BuiltinType::Int128:
5402 case BuiltinType::UInt128:
5403 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005404 }
5405}
5406
Eli Friedman629ffb92009-08-20 04:21:42 +00005407/// \brief Whether this is a promotable bitfield reference according
5408/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5409///
5410/// \returns the type this bit-field will promote to, or NULL if no
5411/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005412QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005413 if (E->isTypeDependent() || E->isValueDependent())
5414 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00005415
5416 // FIXME: We should not do this unless E->refersToBitField() is true. This
5417 // matters in C where getSourceBitField() will find bit-fields for various
5418 // cases where the source expression is not a bit-field designator.
5419
John McCalld25db7e2013-05-06 21:39:12 +00005420 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005421 if (!Field)
5422 return QualType();
5423
5424 QualType FT = Field->getType();
5425
Richard Smithcaf33902011-10-10 18:28:20 +00005426 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005427 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005428 // C++ [conv.prom]p5:
5429 // A prvalue for an integral bit-field can be converted to a prvalue of type
5430 // int if int can represent all the values of the bit-field; otherwise, it
5431 // can be converted to unsigned int if unsigned int can represent all the
5432 // values of the bit-field. If the bit-field is larger yet, no integral
5433 // promotion applies to it.
5434 // C11 6.3.1.1/2:
5435 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5436 // If an int can represent all values of the original type (as restricted by
5437 // the width, for a bit-field), the value is converted to an int; otherwise,
5438 // it is converted to an unsigned int.
5439 //
5440 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5441 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00005442 if (BitWidth < IntSize)
5443 return IntTy;
5444
5445 if (BitWidth == IntSize)
5446 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5447
5448 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005449 // like the base type. GCC has some weird bugs in this area that we
5450 // deliberately do not follow (GCC follows a pre-standard resolution to
5451 // C's DR315 which treats bit-width as being part of the type, and this leaks
5452 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00005453 return QualType();
5454}
5455
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005456/// getPromotedIntegerType - Returns the type that Promotable will
5457/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5458/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005459QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005460 assert(!Promotable.isNull());
5461 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00005462 if (const EnumType *ET = Promotable->getAs<EnumType>())
5463 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005464
5465 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5466 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5467 // (3.9.1) can be converted to a prvalue of the first of the following
5468 // types that can represent all the values of its underlying type:
5469 // int, unsigned int, long int, unsigned long int, long long int, or
5470 // unsigned long long int [...]
5471 // FIXME: Is there some better way to compute this?
5472 if (BT->getKind() == BuiltinType::WChar_S ||
5473 BT->getKind() == BuiltinType::WChar_U ||
5474 BT->getKind() == BuiltinType::Char16 ||
5475 BT->getKind() == BuiltinType::Char32) {
5476 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5477 uint64_t FromSize = getTypeSize(BT);
5478 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5479 LongLongTy, UnsignedLongLongTy };
5480 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5481 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5482 if (FromSize < ToSize ||
5483 (FromSize == ToSize &&
5484 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5485 return PromoteTypes[Idx];
5486 }
5487 llvm_unreachable("char type should fit into long long");
5488 }
5489 }
5490
5491 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005492 if (Promotable->isSignedIntegerType())
5493 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005494 uint64_t PromotableSize = getIntWidth(Promotable);
5495 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005496 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5497 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5498}
5499
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005500/// \brief Recurses in pointer/array types until it finds an objc retainable
5501/// type and returns its ownership.
5502Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5503 while (!T.isNull()) {
5504 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5505 return T.getObjCLifetime();
5506 if (T->isArrayType())
5507 T = getBaseElementType(T);
5508 else if (const PointerType *PT = T->getAs<PointerType>())
5509 T = PT->getPointeeType();
5510 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005511 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005512 else
5513 break;
5514 }
5515
5516 return Qualifiers::OCL_None;
5517}
5518
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005519static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5520 // Incomplete enum types are not treated as integer types.
5521 // FIXME: In C++, enum types are never integer types.
5522 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5523 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005524 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005525}
5526
Mike Stump11289f42009-09-09 15:08:12 +00005527/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005528/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005529/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005530int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005531 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5532 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005533
5534 // Unwrap enums to their underlying type.
5535 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5536 LHSC = getIntegerTypeForEnum(ET);
5537 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5538 RHSC = getIntegerTypeForEnum(ET);
5539
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005540 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005541
Chris Lattner76a00cf2008-04-06 22:59:24 +00005542 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5543 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005544
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005545 unsigned LHSRank = getIntegerRank(LHSC);
5546 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005547
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005548 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5549 if (LHSRank == RHSRank) return 0;
5550 return LHSRank > RHSRank ? 1 : -1;
5551 }
Mike Stump11289f42009-09-09 15:08:12 +00005552
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005553 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5554 if (LHSUnsigned) {
5555 // If the unsigned [LHS] type is larger, return it.
5556 if (LHSRank >= RHSRank)
5557 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005558
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005559 // If the signed type can represent all values of the unsigned type, it
5560 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005561 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005562 return -1;
5563 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005564
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005565 // If the unsigned [RHS] type is larger, return it.
5566 if (RHSRank >= LHSRank)
5567 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005568
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005569 // If the signed type can represent all values of the unsigned type, it
5570 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005571 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005572 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005573}
Anders Carlsson98f07902007-08-17 05:31:46 +00005574
Ben Langmuirf5416742016-02-04 00:55:24 +00005575TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005576 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005577 assert(!CFConstantStringTagDecl &&
5578 "tag and typedef should be initialized together");
5579 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5580 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005581
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005582 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005583 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005584
Anders Carlsson98f07902007-08-17 05:31:46 +00005585 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005586 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005587 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005588 // int flags;
5589 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005590 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005591 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005592 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005593 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005594 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005595 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005596 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005597
Anders Carlsson98f07902007-08-17 05:31:46 +00005598 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005599 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005600 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005601 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005602 SourceLocation(),
5603 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005604 FieldTypes[i], /*TInfo=*/nullptr,
5605 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005606 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005607 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005608 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005609 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005610 }
5611
Ben Langmuirf5416742016-02-04 00:55:24 +00005612 CFConstantStringTagDecl->completeDefinition();
5613 // This type is designed to be compatible with NSConstantString, but cannot
5614 // use the same name, since NSConstantString is an interface.
5615 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5616 CFConstantStringTypeDecl =
5617 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005618 }
Mike Stump11289f42009-09-09 15:08:12 +00005619
Quentin Colombet043406b2016-02-03 22:41:00 +00005620 return CFConstantStringTypeDecl;
5621}
5622
Ben Langmuirf5416742016-02-04 00:55:24 +00005623RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5624 if (!CFConstantStringTagDecl)
5625 getCFConstantStringDecl(); // Build the tag and the typedef.
5626 return CFConstantStringTagDecl;
5627}
5628
Quentin Colombet043406b2016-02-03 22:41:00 +00005629// getCFConstantStringType - Return the type used for constant CFStrings.
5630QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005631 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005632}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005633
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005634QualType ASTContext::getObjCSuperType() const {
5635 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005636 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005637 TUDecl->addDecl(ObjCSuperTypeDecl);
5638 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5639 }
5640 return ObjCSuperType;
5641}
5642
Douglas Gregor512b0772009-04-23 22:29:11 +00005643void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005644 const TypedefType *TD = T->getAs<TypedefType>();
5645 assert(TD && "Invalid CFConstantStringType");
5646 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5647 auto TagType =
5648 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5649 assert(TagType && "Invalid CFConstantStringType");
5650 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005651}
5652
Jay Foad39c79802011-01-12 09:06:06 +00005653QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005654 if (BlockDescriptorType)
5655 return getTagDeclType(BlockDescriptorType);
5656
Alp Toker2dea15b2013-12-17 01:22:38 +00005657 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005658 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005659 RD = buildImplicitRecord("__block_descriptor");
5660 RD->startDefinition();
5661
Mike Stumpd0153282009-10-20 02:12:22 +00005662 QualType FieldTypes[] = {
5663 UnsignedLongTy,
5664 UnsignedLongTy,
5665 };
5666
Craig Topperd6d31ac2013-07-15 08:24:27 +00005667 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005668 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005669 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005670 };
5671
5672 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005673 FieldDecl *Field = FieldDecl::Create(
5674 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005675 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5676 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005677 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005678 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005679 }
5680
Alp Toker2dea15b2013-12-17 01:22:38 +00005681 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005682
Alp Toker2dea15b2013-12-17 01:22:38 +00005683 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005684
5685 return getTagDeclType(BlockDescriptorType);
5686}
5687
Jay Foad39c79802011-01-12 09:06:06 +00005688QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005689 if (BlockDescriptorExtendedType)
5690 return getTagDeclType(BlockDescriptorExtendedType);
5691
Alp Toker2dea15b2013-12-17 01:22:38 +00005692 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005693 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005694 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5695 RD->startDefinition();
5696
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005697 QualType FieldTypes[] = {
5698 UnsignedLongTy,
5699 UnsignedLongTy,
5700 getPointerType(VoidPtrTy),
5701 getPointerType(VoidPtrTy)
5702 };
5703
Craig Topperd6d31ac2013-07-15 08:24:27 +00005704 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005705 "reserved",
5706 "Size",
5707 "CopyFuncPtr",
5708 "DestroyFuncPtr"
5709 };
5710
5711 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005712 FieldDecl *Field = FieldDecl::Create(
5713 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005714 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5715 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005716 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005717 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005718 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005719 }
5720
Alp Toker2dea15b2013-12-17 01:22:38 +00005721 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005722
Alp Toker2dea15b2013-12-17 01:22:38 +00005723 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005724 return getTagDeclType(BlockDescriptorExtendedType);
5725}
5726
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00005727TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
5728 auto BT = dyn_cast<BuiltinType>(T);
5729
5730 if (!BT) {
5731 if (isa<PipeType>(T))
5732 return TargetInfo::OCLTK_Pipe;
5733
5734 return TargetInfo::OCLTK_Default;
5735 }
5736
5737 switch (BT->getKind()) {
5738#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5739 case BuiltinType::Id: \
5740 return TargetInfo::OCLTK_Image;
5741#include "clang/Basic/OpenCLImageTypes.def"
5742
5743 case BuiltinType::OCLClkEvent:
5744 return TargetInfo::OCLTK_ClkEvent;
5745
5746 case BuiltinType::OCLEvent:
5747 return TargetInfo::OCLTK_Event;
5748
5749 case BuiltinType::OCLQueue:
5750 return TargetInfo::OCLTK_Queue;
5751
5752 case BuiltinType::OCLReserveID:
5753 return TargetInfo::OCLTK_ReserveID;
5754
5755 case BuiltinType::OCLSampler:
5756 return TargetInfo::OCLTK_Sampler;
5757
5758 default:
5759 return TargetInfo::OCLTK_Default;
5760 }
5761}
5762
5763LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
5764 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
5765}
5766
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005767/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5768/// requires copy/dispose. Note that this must match the logic
5769/// in buildByrefHelpers.
5770bool ASTContext::BlockRequiresCopying(QualType Ty,
5771 const VarDecl *D) {
5772 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5773 const Expr *copyExpr = getBlockVarCopyInits(D);
5774 if (!copyExpr && record->hasTrivialDestructor()) return false;
5775
Mike Stump94967902009-10-21 18:16:27 +00005776 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005777 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005778
Akira Hatanaka7275da02018-02-28 07:15:55 +00005779 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
5780 // move or destroy.
5781 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
5782 return true;
5783
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005784 if (!Ty->isObjCRetainableType()) return false;
5785
5786 Qualifiers qs = Ty.getQualifiers();
5787
5788 // If we have lifetime, that dominates.
5789 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005790 switch (lifetime) {
5791 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5792
5793 // These are just bits as far as the runtime is concerned.
5794 case Qualifiers::OCL_ExplicitNone:
5795 case Qualifiers::OCL_Autoreleasing:
5796 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00005797
5798 // These cases should have been taken care of when checking the type's
5799 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005800 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005801 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00005802 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005803 }
5804 llvm_unreachable("fell out of lifetime switch!");
5805 }
5806 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5807 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005808}
5809
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005810bool ASTContext::getByrefLifetime(QualType Ty,
5811 Qualifiers::ObjCLifetime &LifeTime,
5812 bool &HasByrefExtendedLayout) const {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005813 if (!getLangOpts().ObjC1 ||
5814 getLangOpts().getGC() != LangOptions::NonGC)
5815 return false;
5816
5817 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005818 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005819 HasByrefExtendedLayout = true;
5820 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005821 } else if ((LifeTime = Ty.getObjCLifetime())) {
5822 // Honor the ARC qualifiers.
5823 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5824 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005825 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005826 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005827 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005828 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005829 return true;
5830}
5831
Douglas Gregorbab8a962011-09-08 01:46:34 +00005832TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5833 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005834 ObjCInstanceTypeDecl =
5835 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005836 return ObjCInstanceTypeDecl;
5837}
5838
Anders Carlsson18acd442007-10-29 06:33:42 +00005839// This returns true if a type has been typedefed to BOOL:
5840// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005841static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005842 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005843 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5844 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005845
Anders Carlssond8499822007-10-29 05:01:08 +00005846 return false;
5847}
5848
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005849/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005850/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005851CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005852 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5853 return CharUnits::Zero();
5854
Ken Dyck40775002010-01-11 17:06:35 +00005855 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005856
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005857 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005858 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005859 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005860 // Treat arrays as pointers, since that's how they're passed in.
5861 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005862 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005863 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005864}
5865
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005866bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005867 return getTargetInfo().getCXXABI().isMicrosoft() &&
5868 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00005869 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00005870 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005871}
5872
Richard Smithd9b90092016-07-02 01:32:16 +00005873ASTContext::InlineVariableDefinitionKind
5874ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5875 if (!VD->isInline())
5876 return InlineVariableDefinitionKind::None;
5877
5878 // In almost all cases, it's a weak definition.
5879 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00005880 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00005881 return InlineVariableDefinitionKind::Weak;
5882
5883 // If there's a file-context declaration in this translation unit, it's a
5884 // non-discardable definition.
5885 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00005886 if (D->getLexicalDeclContext()->isFileContext() &&
5887 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00005888 return InlineVariableDefinitionKind::Strong;
5889
5890 // If we've not seen one yet, we don't know.
5891 return InlineVariableDefinitionKind::WeakUnknown;
5892}
5893
Ken Dyck40775002010-01-11 17:06:35 +00005894static inline
5895std::string charUnitsToString(const CharUnits &CU) {
5896 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005897}
5898
John McCall351762c2011-02-07 10:33:21 +00005899/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005900/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005901std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5902 std::string S;
5903
David Chisnall950a9512009-11-17 19:33:30 +00005904 const BlockDecl *Decl = Expr->getBlockDecl();
5905 QualType BlockTy =
5906 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5907 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005908 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005909 getObjCEncodingForMethodParameter(
5910 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5911 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005912 else
Alp Toker314cc812014-01-25 16:55:45 +00005913 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005914 // Compute size of all parameters.
5915 // Start with computing size of a pointer in number of bytes.
5916 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00005917 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5918 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005919 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005920 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005921 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005922 if (sz.isZero())
5923 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00005924 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005925 ParmOffset += sz;
5926 }
5927 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005928 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005929 // Block pointer and offset.
5930 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005931
5932 // Argument types.
5933 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005934 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005935 QualType PType = PVDecl->getOriginalType();
5936 if (const ArrayType *AT =
5937 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5938 // Use array's original type only if it has known number of
5939 // elements.
5940 if (!isa<ConstantArrayType>(AT))
5941 PType = PVDecl->getType();
5942 } else if (PType->isFunctionType())
5943 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005944 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005945 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5946 S, true /*Extended*/);
5947 else
5948 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005949 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005950 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005951 }
John McCall351762c2011-02-07 10:33:21 +00005952
5953 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005954}
5955
John McCall843dfcc2016-11-29 21:57:00 +00005956std::string
5957ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5958 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005959 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005960 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005961 CharUnits ParmOffset;
5962 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005963 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005964 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005965 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005966 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005967 continue;
5968
John McCall843dfcc2016-11-29 21:57:00 +00005969 assert(sz.isPositive() &&
5970 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005971 ParmOffset += sz;
5972 }
5973 S += charUnitsToString(ParmOffset);
5974 ParmOffset = CharUnits::Zero();
5975
5976 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005977 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005978 QualType PType = PVDecl->getOriginalType();
5979 if (const ArrayType *AT =
5980 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5981 // Use array's original type only if it has known number of
5982 // elements.
5983 if (!isa<ConstantArrayType>(AT))
5984 PType = PVDecl->getType();
5985 } else if (PType->isFunctionType())
5986 PType = PVDecl->getType();
5987 getObjCEncodingForType(PType, S);
5988 S += charUnitsToString(ParmOffset);
5989 ParmOffset += getObjCEncodingTypeSize(PType);
5990 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005991
John McCall843dfcc2016-11-29 21:57:00 +00005992 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005993}
5994
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005995/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5996/// method parameter or return type. If Extended, include class names and
5997/// block object types.
5998void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5999 QualType T, std::string& S,
6000 bool Extended) const {
6001 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6002 getObjCEncodingForTypeQualifier(QT, S);
6003 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00006004 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006005 true /*OutermostType*/,
6006 false /*EncodingProperty*/,
6007 false /*StructField*/,
6008 Extended /*EncodeBlockParameters*/,
6009 Extended /*EncodeClassNames*/);
6010}
6011
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006012/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006013/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006014std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6015 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006016 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006017 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006018 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006019 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6020 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006021 // Compute size of all parameters.
6022 // Start with computing size of a pointer in number of bytes.
6023 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006024 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006025 // The first two arguments (self and _cmd) are pointers; account for
6026 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006027 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006028 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006029 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006030 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006031 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006032 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006033 continue;
6034
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006035 assert(sz.isPositive() &&
6036 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006037 ParmOffset += sz;
6038 }
Ken Dyck40775002010-01-11 17:06:35 +00006039 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006040 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006041 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006042
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006043 // Argument types.
6044 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006045 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006046 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006047 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006048 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00006049 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00006050 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6051 // Use array's original type only if it has known number of
6052 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006053 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006054 PType = PVDecl->getType();
6055 } else if (PType->isFunctionType())
6056 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006057 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
6058 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006059 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006060 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006061 }
Douglas Gregora9d84932011-05-27 01:19:52 +00006062
John McCall843dfcc2016-11-29 21:57:00 +00006063 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006064}
6065
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006066ObjCPropertyImplDecl *
6067ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6068 const ObjCPropertyDecl *PD,
6069 const Decl *Container) const {
6070 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006071 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006072 if (const ObjCCategoryImplDecl *CID =
6073 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006074 for (auto *PID : CID->property_impls())
6075 if (PID->getPropertyDecl() == PD)
6076 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006077 } else {
6078 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
6079 for (auto *PID : OID->property_impls())
6080 if (PID->getPropertyDecl() == PD)
6081 return PID;
6082 }
6083 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006084}
6085
Daniel Dunbar4932b362008-08-28 04:38:10 +00006086/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006087/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006088/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6089/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006090/// Property attributes are stored as a comma-delimited C string. The simple
6091/// attributes readonly and bycopy are encoded as single characters. The
6092/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6093/// encoded as single characters, followed by an identifier. Property types
6094/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006095/// these attributes are defined by the following enumeration:
6096/// @code
6097/// enum PropertyAttributes {
6098/// kPropertyReadOnly = 'R', // property is read-only.
6099/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6100/// kPropertyByref = '&', // property is a reference to the value last assigned
6101/// kPropertyDynamic = 'D', // property is dynamic
6102/// kPropertyGetter = 'G', // followed by getter selector name
6103/// kPropertySetter = 'S', // followed by setter selector name
6104/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006105/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006106/// kPropertyWeak = 'W' // 'weak' property
6107/// kPropertyStrong = 'P' // property GC'able
6108/// kPropertyNonAtomic = 'N' // property non-atomic
6109/// };
6110/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006111std::string
6112ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6113 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006114 // Collect information from the property implementation decl(s).
6115 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006116 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006117
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006118 if (ObjCPropertyImplDecl *PropertyImpDecl =
6119 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6120 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6121 Dynamic = true;
6122 else
6123 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006124 }
6125
6126 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006127 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006128
6129 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006130 // GCC has some special rules regarding encoding of properties which
6131 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006132 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006133
6134 if (PD->isReadOnly()) {
6135 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006136 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6137 S += ",C";
6138 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6139 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006140 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6141 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006142 } else {
6143 switch (PD->getSetterKind()) {
6144 case ObjCPropertyDecl::Assign: break;
6145 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006146 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006147 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006148 }
6149 }
6150
6151 // It really isn't clear at all what this means, since properties
6152 // are "dynamic by default".
6153 if (Dynamic)
6154 S += ",D";
6155
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006156 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6157 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006158
Daniel Dunbar4932b362008-08-28 04:38:10 +00006159 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6160 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006161 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006162 }
6163
6164 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6165 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006166 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006167 }
6168
6169 if (SynthesizePID) {
6170 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6171 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006172 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006173 }
6174
6175 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006176 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006177}
6178
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006179/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006180/// Another legacy compatibility encoding: 32-bit longs are encoded as
6181/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006182/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006183void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006184 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00006185 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006186 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006187 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006188 else
Jay Foad39c79802011-01-12 09:06:06 +00006189 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006190 PointeeTy = IntTy;
6191 }
6192 }
6193}
6194
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006195void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006196 const FieldDecl *Field,
6197 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006198 // We follow the behavior of gcc, expanding structures which are
6199 // directly pointed to, and expanding embedded structures. Note that
6200 // these rules are sufficient to prevent recursive encoding of the
6201 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00006202 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006203 true /* outermost type */, false, false,
6204 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006205}
6206
Joe Groff98ac7d22014-07-07 22:25:15 +00006207void ASTContext::getObjCEncodingForPropertyType(QualType T,
6208 std::string& S) const {
6209 // Encode result type.
6210 // GCC has some special rules regarding encoding of properties which
6211 // closely resembles encoding of ivars.
6212 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
6213 true /* outermost type */,
6214 true /* encoding property */);
6215}
6216
John McCall393a78d2012-12-20 02:45:14 +00006217static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6218 BuiltinType::Kind kind) {
6219 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006220 case BuiltinType::Void: return 'v';
6221 case BuiltinType::Bool: return 'B';
6222 case BuiltinType::Char_U:
6223 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006224 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006225 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006226 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006227 case BuiltinType::UInt: return 'I';
6228 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006229 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006230 case BuiltinType::UInt128: return 'T';
6231 case BuiltinType::ULongLong: return 'Q';
6232 case BuiltinType::Char_S:
6233 case BuiltinType::SChar: return 'c';
6234 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006235 case BuiltinType::WChar_S:
6236 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006237 case BuiltinType::Int: return 'i';
6238 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006239 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006240 case BuiltinType::LongLong: return 'q';
6241 case BuiltinType::Int128: return 't';
6242 case BuiltinType::Float: return 'f';
6243 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006244 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006245 case BuiltinType::NullPtr: return '*'; // like char*
6246
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006247 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006248 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006249 case BuiltinType::Half:
6250 // FIXME: potentially need @encodes for these!
6251 return ' ';
6252
6253 case BuiltinType::ObjCId:
6254 case BuiltinType::ObjCClass:
6255 case BuiltinType::ObjCSel:
6256 llvm_unreachable("@encoding ObjC primitive type");
6257
6258 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006259#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6260 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006261#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006262 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006263 case BuiltinType::OCLClkEvent:
6264 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006265 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006266 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006267 case BuiltinType::Dependent:
6268#define BUILTIN_TYPE(KIND, ID)
6269#define PLACEHOLDER_TYPE(KIND, ID) \
6270 case BuiltinType::KIND:
6271#include "clang/AST/BuiltinTypes.def"
6272 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006273 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006274 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006275}
6276
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006277static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6278 EnumDecl *Enum = ET->getDecl();
6279
6280 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6281 if (!Enum->isFixed())
6282 return 'i';
6283
6284 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00006285 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
6286 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006287}
6288
Jay Foad39c79802011-01-12 09:06:06 +00006289static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006290 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006291 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006292 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006293 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6294 // The GNU runtime requires more information; bitfields are encoded as b,
6295 // then the offset (in bits) of the first element, then the type of the
6296 // bitfield, then the size in bits. For example, in this structure:
6297 //
6298 // struct
6299 // {
6300 // int integer;
6301 // int flags:2;
6302 // };
6303 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6304 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6305 // information is not especially sensible, but we're stuck with it for
6306 // compatibility with GCC, although providing it breaks anything that
6307 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006308 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006309 uint64_t Offset;
6310
6311 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6312 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6313 IVD);
6314 } else {
6315 const RecordDecl *RD = FD->getParent();
6316 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6317 Offset = RL.getFieldOffset(FD->getFieldIndex());
6318 }
6319
6320 S += llvm::utostr(Offset);
6321
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006322 if (const EnumType *ET = T->getAs<EnumType>())
6323 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006324 else {
6325 const BuiltinType *BT = T->castAs<BuiltinType>();
6326 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6327 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006328 }
Richard Smithcaf33902011-10-10 18:28:20 +00006329 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006330}
6331
Daniel Dunbar07d07852009-10-18 21:17:35 +00006332// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006333void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6334 bool ExpandPointedToStructures,
6335 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006336 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006337 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006338 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006339 bool StructField,
6340 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006341 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006342 bool EncodePointerToObjCTypedef,
6343 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006344 CanQualType CT = getCanonicalType(T);
6345 switch (CT->getTypeClass()) {
6346 case Type::Builtin:
6347 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006348 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006349 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00006350 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
6351 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6352 else
6353 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006354 return;
Mike Stump11289f42009-09-09 15:08:12 +00006355
John McCall393a78d2012-12-20 02:45:14 +00006356 case Type::Complex: {
6357 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006358 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006359 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006360 return;
6361 }
John McCall393a78d2012-12-20 02:45:14 +00006362
6363 case Type::Atomic: {
6364 const AtomicType *AT = T->castAs<AtomicType>();
6365 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006366 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006367 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006368 }
John McCall393a78d2012-12-20 02:45:14 +00006369
6370 // encoding for pointer or reference types.
6371 case Type::Pointer:
6372 case Type::LValueReference:
6373 case Type::RValueReference: {
6374 QualType PointeeTy;
6375 if (isa<PointerType>(CT)) {
6376 const PointerType *PT = T->castAs<PointerType>();
6377 if (PT->isObjCSelType()) {
6378 S += ':';
6379 return;
6380 }
6381 PointeeTy = PT->getPointeeType();
6382 } else {
6383 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6384 }
6385
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006386 bool isReadOnly = false;
6387 // For historical/compatibility reasons, the read-only qualifier of the
6388 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6389 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006390 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006391 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006392 if (OutermostType && T.isConstQualified()) {
6393 isReadOnly = true;
6394 S += 'r';
6395 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006396 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006397 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006398 while (P->getAs<PointerType>())
6399 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006400 if (P.isConstQualified()) {
6401 isReadOnly = true;
6402 S += 'r';
6403 }
6404 }
6405 if (isReadOnly) {
6406 // Another legacy compatibility encoding. Some ObjC qualifier and type
6407 // combinations need to be rearranged.
6408 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006409 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006410 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006411 }
Mike Stump11289f42009-09-09 15:08:12 +00006412
Anders Carlssond8499822007-10-29 05:01:08 +00006413 if (PointeeTy->isCharType()) {
6414 // char pointer types should be encoded as '*' unless it is a
6415 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006416 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006417 S += '*';
6418 return;
6419 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006420 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006421 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6422 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6423 S += '#';
6424 return;
6425 }
6426 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6427 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6428 S += '@';
6429 return;
6430 }
6431 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006432 }
Anders Carlssond8499822007-10-29 05:01:08 +00006433 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006434 getLegacyIntegralTypeEncoding(PointeeTy);
6435
Mike Stump11289f42009-09-09 15:08:12 +00006436 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006437 nullptr, false, false, false, false, false, false,
6438 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006439 return;
6440 }
John McCall393a78d2012-12-20 02:45:14 +00006441
6442 case Type::ConstantArray:
6443 case Type::IncompleteArray:
6444 case Type::VariableArray: {
6445 const ArrayType *AT = cast<ArrayType>(CT);
6446
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006447 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006448 // Incomplete arrays are encoded as a pointer to the array element.
6449 S += '^';
6450
Mike Stump11289f42009-09-09 15:08:12 +00006451 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006452 false, ExpandStructures, FD);
6453 } else {
6454 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006455
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006456 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6457 S += llvm::utostr(CAT->getSize().getZExtValue());
6458 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006459 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006460 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6461 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006462 S += '0';
6463 }
Mike Stump11289f42009-09-09 15:08:12 +00006464
6465 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006466 false, ExpandStructures, FD,
6467 false, false, false, false, false, false,
6468 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006469 S += ']';
6470 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006471 return;
6472 }
Mike Stump11289f42009-09-09 15:08:12 +00006473
John McCall393a78d2012-12-20 02:45:14 +00006474 case Type::FunctionNoProto:
6475 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006476 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006477 return;
Mike Stump11289f42009-09-09 15:08:12 +00006478
John McCall393a78d2012-12-20 02:45:14 +00006479 case Type::Record: {
6480 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006481 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006482 // Anonymous structures print as '?'
6483 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6484 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006485 if (ClassTemplateSpecializationDecl *Spec
6486 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6487 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006488 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006489 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6490 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006491 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006492 } else {
6493 S += '?';
6494 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006495 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006496 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006497 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006498 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006499 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006500 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006501 if (FD) {
6502 S += '"';
6503 S += Field->getNameAsString();
6504 S += '"';
6505 }
Mike Stump11289f42009-09-09 15:08:12 +00006506
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006507 // Special case bit-fields.
6508 if (Field->isBitField()) {
6509 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006510 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006511 } else {
6512 QualType qt = Field->getType();
6513 getLegacyIntegralTypeEncoding(qt);
6514 getObjCEncodingForTypeImpl(qt, S, false, true,
6515 FD, /*OutermostType*/false,
6516 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006517 /*StructField*/true,
6518 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006519 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006520 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006521 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006522 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006523 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006524 return;
6525 }
Mike Stump11289f42009-09-09 15:08:12 +00006526
John McCall393a78d2012-12-20 02:45:14 +00006527 case Type::BlockPointer: {
6528 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006529 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006530 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00006531 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006532
6533 S += '<';
6534 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006535 getObjCEncodingForTypeImpl(
6536 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6537 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006538 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6539 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006540 // Block self
6541 S += "@?";
6542 // Block parameters
6543 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006544 for (const auto &I : FPT->param_types())
6545 getObjCEncodingForTypeImpl(
6546 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6547 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006548 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6549 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006550 }
6551 S += '>';
6552 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006553 return;
6554 }
Mike Stump11289f42009-09-09 15:08:12 +00006555
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006556 case Type::ObjCObject: {
6557 // hack to match legacy encoding of *id and *Class
6558 QualType Ty = getObjCObjectPointerType(CT);
6559 if (Ty->isObjCIdType()) {
6560 S += "{objc_object=}";
6561 return;
6562 }
6563 else if (Ty->isObjCClassType()) {
6564 S += "{objc_class=}";
6565 return;
6566 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006567 // TODO: Double check to make sure this intentially falls through.
6568 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006569 }
6570
John McCall393a78d2012-12-20 02:45:14 +00006571 case Type::ObjCInterface: {
6572 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006573 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006574 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006575 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006576 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006577 if (ExpandStructures) {
6578 S += '=';
6579 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6580 DeepCollectObjCIvars(OI, true, Ivars);
6581 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006582 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006583 if (Field->isBitField())
6584 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6585 else
6586 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6587 false, false, false, false, false,
6588 EncodePointerToObjCTypedef,
6589 NotEncodedT);
6590 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006591 }
6592 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006593 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006594 }
Mike Stump11289f42009-09-09 15:08:12 +00006595
John McCall393a78d2012-12-20 02:45:14 +00006596 case Type::ObjCObjectPointer: {
6597 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006598 if (OPT->isObjCIdType()) {
6599 S += '@';
6600 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006601 }
Mike Stump11289f42009-09-09 15:08:12 +00006602
Steve Narofff0c86112009-10-28 22:03:49 +00006603 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6604 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6605 // Since this is a binary compatibility issue, need to consult with runtime
6606 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006607 S += '#';
6608 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006609 }
Mike Stump11289f42009-09-09 15:08:12 +00006610
Chris Lattnere7cabb92009-07-13 00:10:46 +00006611 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006612 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006613 ExpandPointedToStructures,
6614 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006615 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006616 // Note that we do extended encoding of protocol qualifer list
6617 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006618 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006619 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006620 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006621 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006622 S += '>';
6623 }
6624 S += '"';
6625 }
6626 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006627 }
Mike Stump11289f42009-09-09 15:08:12 +00006628
Chris Lattnere7cabb92009-07-13 00:10:46 +00006629 QualType PointeeTy = OPT->getPointeeType();
6630 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006631 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6632 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006633 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006634 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006635 // {...};
6636 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006637 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006638 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006639 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6640 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6641 DeepCollectObjCIvars(OI, true, Ivars);
6642 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006643 if (Ivars[i] == FD) {
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006644 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006645 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006646 S += '}';
6647 return;
6648 }
6649 }
6650 }
Mike Stump11289f42009-09-09 15:08:12 +00006651 getObjCEncodingForTypeImpl(PointeeTy, S,
6652 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006653 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006654 false, false, false, false, false,
6655 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006656 return;
6657 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006658
6659 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006660 if (OPT->getInterfaceDecl() &&
6661 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006662 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006663 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006664 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006665 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006666 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006667 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006668 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006669 S += '"';
6670 }
6671 return;
6672 }
Mike Stump11289f42009-09-09 15:08:12 +00006673
John McCalla9e6e8d2010-05-17 23:56:34 +00006674 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006675 // FIXME: we shoul do better than that. 'M' is available.
6676 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006677 // This matches gcc's encoding, even though technically it is insufficient.
6678 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006679 case Type::Vector:
6680 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006681 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006682 if (NotEncodedT)
6683 *NotEncodedT = T;
6684 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006685
6686 // We could see an undeduced auto type here during error recovery.
6687 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006688 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006689 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006690 return;
6691
Xiuli Pan9c14e282016-01-09 12:53:17 +00006692 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006693#define ABSTRACT_TYPE(KIND, BASE)
6694#define TYPE(KIND, BASE)
6695#define DEPENDENT_TYPE(KIND, BASE) \
6696 case Type::KIND:
6697#define NON_CANONICAL_TYPE(KIND, BASE) \
6698 case Type::KIND:
6699#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6700 case Type::KIND:
6701#include "clang/AST/TypeNodes.def"
6702 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006703 }
John McCall393a78d2012-12-20 02:45:14 +00006704 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006705}
6706
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006707void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6708 std::string &S,
6709 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006710 bool includeVBases,
6711 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006712 assert(RDecl && "Expected non-null RecordDecl");
6713 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006714 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006715 return;
6716
6717 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6718 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6719 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6720
6721 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006722 for (const auto &BI : CXXRec->bases()) {
6723 if (!BI.isVirtual()) {
6724 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006725 if (base->isEmpty())
6726 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006727 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006728 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6729 std::make_pair(offs, base));
6730 }
6731 }
6732 }
6733
6734 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006735 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006736 uint64_t offs = layout.getFieldOffset(i);
6737 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006738 std::make_pair(offs, Field));
6739 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006740 }
6741
6742 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006743 for (const auto &BI : CXXRec->vbases()) {
6744 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006745 if (base->isEmpty())
6746 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006747 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006748 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6749 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006750 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6751 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006752 }
6753 }
6754
6755 CharUnits size;
6756 if (CXXRec) {
6757 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6758 } else {
6759 size = layout.getSize();
6760 }
6761
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006762#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006763 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006764#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006765 std::multimap<uint64_t, NamedDecl *>::iterator
6766 CurLayObj = FieldOrBaseOffsets.begin();
6767
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006768 if (CXXRec && CXXRec->isDynamicClass() &&
6769 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006770 if (FD) {
6771 S += "\"_vptr$";
6772 std::string recname = CXXRec->getNameAsString();
6773 if (recname.empty()) recname = "?";
6774 S += recname;
6775 S += '"';
6776 }
6777 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006778#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006779 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006780#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006781 }
6782
6783 if (!RDecl->hasFlexibleArrayMember()) {
6784 // Mark the end of the structure.
6785 uint64_t offs = toBits(size);
6786 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006787 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006788 }
6789
6790 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006791#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006792 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006793 if (CurOffs < CurLayObj->first) {
6794 uint64_t padding = CurLayObj->first - CurOffs;
6795 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6796 // packing/alignment of members is different that normal, in which case
6797 // the encoding will be out-of-sync with the real layout.
6798 // If the runtime switches to just consider the size of types without
6799 // taking into account alignment, we could make padding explicit in the
6800 // encoding (e.g. using arrays of chars). The encoding strings would be
6801 // longer then though.
6802 CurOffs += padding;
6803 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006804#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006805
6806 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006807 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006808 break; // reached end of structure.
6809
6810 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6811 // We expand the bases without their virtual bases since those are going
6812 // in the initial structure. Note that this differs from gcc which
6813 // expands virtual bases each time one is encountered in the hierarchy,
6814 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006815 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6816 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006817 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006818#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006819 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006820#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006821 } else {
6822 FieldDecl *field = cast<FieldDecl>(dcl);
6823 if (FD) {
6824 S += '"';
6825 S += field->getNameAsString();
6826 S += '"';
6827 }
6828
6829 if (field->isBitField()) {
6830 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006831#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006832 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006833#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006834 } else {
6835 QualType qt = field->getType();
6836 getLegacyIntegralTypeEncoding(qt);
6837 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6838 /*OutermostType*/false,
6839 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006840 /*StructField*/true,
6841 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006842#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006843 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006844#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006845 }
6846 }
6847 }
6848}
6849
Mike Stump11289f42009-09-09 15:08:12 +00006850void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006851 std::string& S) const {
6852 if (QT & Decl::OBJC_TQ_In)
6853 S += 'n';
6854 if (QT & Decl::OBJC_TQ_Inout)
6855 S += 'N';
6856 if (QT & Decl::OBJC_TQ_Out)
6857 S += 'o';
6858 if (QT & Decl::OBJC_TQ_Bycopy)
6859 S += 'O';
6860 if (QT & Decl::OBJC_TQ_Byref)
6861 S += 'R';
6862 if (QT & Decl::OBJC_TQ_Oneway)
6863 S += 'V';
6864}
6865
Douglas Gregor3ea72692011-08-12 05:46:01 +00006866TypedefDecl *ASTContext::getObjCIdDecl() const {
6867 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006868 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00006869 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006870 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006871 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006872 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006873}
6874
Douglas Gregor52e02802011-08-12 06:17:30 +00006875TypedefDecl *ASTContext::getObjCSelDecl() const {
6876 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006877 QualType T = getPointerType(ObjCBuiltinSelTy);
6878 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006879 }
6880 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006881}
6882
Douglas Gregor0a586182011-08-12 05:59:41 +00006883TypedefDecl *ASTContext::getObjCClassDecl() const {
6884 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006885 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00006886 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006887 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006888 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006889 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006890}
6891
Douglas Gregord53ae832012-01-17 18:09:05 +00006892ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6893 if (!ObjCProtocolClassDecl) {
6894 ObjCProtocolClassDecl
6895 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6896 SourceLocation(),
6897 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006898 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006899 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006900 SourceLocation(), true);
6901 }
6902
6903 return ObjCProtocolClassDecl;
6904}
6905
Meador Inge5d3fb222012-06-16 03:34:49 +00006906//===----------------------------------------------------------------------===//
6907// __builtin_va_list Construction Functions
6908//===----------------------------------------------------------------------===//
6909
Charles Davisc7d5c942015-09-17 20:55:33 +00006910static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6911 StringRef Name) {
6912 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006913 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006914 return Context->buildImplicitTypedef(T, Name);
6915}
6916
6917static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6918 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6919}
6920
6921static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6922 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006923}
6924
6925static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6926 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006927 QualType T = Context->getPointerType(Context->VoidTy);
6928 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006929}
6930
Tim Northover9bb857a2013-01-31 12:13:10 +00006931static TypedefDecl *
6932CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006933 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006934 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006935 if (Context->getLangOpts().CPlusPlus) {
6936 // namespace std { struct __va_list {
6937 NamespaceDecl *NS;
6938 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6939 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006940 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006941 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006942 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006943 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006944 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006945 }
6946
6947 VaListTagDecl->startDefinition();
6948
6949 const size_t NumFields = 5;
6950 QualType FieldTypes[NumFields];
6951 const char *FieldNames[NumFields];
6952
6953 // void *__stack;
6954 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6955 FieldNames[0] = "__stack";
6956
6957 // void *__gr_top;
6958 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6959 FieldNames[1] = "__gr_top";
6960
6961 // void *__vr_top;
6962 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6963 FieldNames[2] = "__vr_top";
6964
6965 // int __gr_offs;
6966 FieldTypes[3] = Context->IntTy;
6967 FieldNames[3] = "__gr_offs";
6968
6969 // int __vr_offs;
6970 FieldTypes[4] = Context->IntTy;
6971 FieldNames[4] = "__vr_offs";
6972
6973 // Create fields
6974 for (unsigned i = 0; i < NumFields; ++i) {
6975 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6976 VaListTagDecl,
6977 SourceLocation(),
6978 SourceLocation(),
6979 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006980 FieldTypes[i], /*TInfo=*/nullptr,
6981 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006982 /*Mutable=*/false,
6983 ICIS_NoInit);
6984 Field->setAccess(AS_public);
6985 VaListTagDecl->addDecl(Field);
6986 }
6987 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006988 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006989 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006990
6991 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006992 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006993}
6994
Meador Inge5d3fb222012-06-16 03:34:49 +00006995static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6996 // typedef struct __va_list_tag {
6997 RecordDecl *VaListTagDecl;
6998
Alp Toker2dea15b2013-12-17 01:22:38 +00006999 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007000 VaListTagDecl->startDefinition();
7001
7002 const size_t NumFields = 5;
7003 QualType FieldTypes[NumFields];
7004 const char *FieldNames[NumFields];
7005
7006 // unsigned char gpr;
7007 FieldTypes[0] = Context->UnsignedCharTy;
7008 FieldNames[0] = "gpr";
7009
7010 // unsigned char fpr;
7011 FieldTypes[1] = Context->UnsignedCharTy;
7012 FieldNames[1] = "fpr";
7013
7014 // unsigned short reserved;
7015 FieldTypes[2] = Context->UnsignedShortTy;
7016 FieldNames[2] = "reserved";
7017
7018 // void* overflow_arg_area;
7019 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7020 FieldNames[3] = "overflow_arg_area";
7021
7022 // void* reg_save_area;
7023 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7024 FieldNames[4] = "reg_save_area";
7025
7026 // Create fields
7027 for (unsigned i = 0; i < NumFields; ++i) {
7028 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7029 SourceLocation(),
7030 SourceLocation(),
7031 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007032 FieldTypes[i], /*TInfo=*/nullptr,
7033 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007034 /*Mutable=*/false,
7035 ICIS_NoInit);
7036 Field->setAccess(AS_public);
7037 VaListTagDecl->addDecl(Field);
7038 }
7039 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007040 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007041 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7042
7043 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007044 TypedefDecl *VaListTagTypedefDecl =
7045 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7046
Meador Inge5d3fb222012-06-16 03:34:49 +00007047 QualType VaListTagTypedefType =
7048 Context->getTypedefType(VaListTagTypedefDecl);
7049
7050 // typedef __va_list_tag __builtin_va_list[1];
7051 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7052 QualType VaListTagArrayType
7053 = Context->getConstantArrayType(VaListTagTypedefType,
7054 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007055 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007056}
7057
7058static TypedefDecl *
7059CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007060 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007061 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007062 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007063 VaListTagDecl->startDefinition();
7064
7065 const size_t NumFields = 4;
7066 QualType FieldTypes[NumFields];
7067 const char *FieldNames[NumFields];
7068
7069 // unsigned gp_offset;
7070 FieldTypes[0] = Context->UnsignedIntTy;
7071 FieldNames[0] = "gp_offset";
7072
7073 // unsigned fp_offset;
7074 FieldTypes[1] = Context->UnsignedIntTy;
7075 FieldNames[1] = "fp_offset";
7076
7077 // void* overflow_arg_area;
7078 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7079 FieldNames[2] = "overflow_arg_area";
7080
7081 // void* reg_save_area;
7082 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7083 FieldNames[3] = "reg_save_area";
7084
7085 // Create fields
7086 for (unsigned i = 0; i < NumFields; ++i) {
7087 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7088 VaListTagDecl,
7089 SourceLocation(),
7090 SourceLocation(),
7091 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007092 FieldTypes[i], /*TInfo=*/nullptr,
7093 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007094 /*Mutable=*/false,
7095 ICIS_NoInit);
7096 Field->setAccess(AS_public);
7097 VaListTagDecl->addDecl(Field);
7098 }
7099 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007100 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007101 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7102
Richard Smith9b88a4c2015-07-27 05:40:23 +00007103 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007104
Richard Smith9b88a4c2015-07-27 05:40:23 +00007105 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007106 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007107 QualType VaListTagArrayType =
7108 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007109 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007110}
7111
7112static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7113 // typedef int __builtin_va_list[4];
7114 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007115 QualType IntArrayType =
7116 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007117 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007118}
7119
Logan Chien57086ce2012-10-10 06:56:20 +00007120static TypedefDecl *
7121CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007122 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007123 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007124 if (Context->getLangOpts().CPlusPlus) {
7125 // namespace std { struct __va_list {
7126 NamespaceDecl *NS;
7127 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7128 Context->getTranslationUnitDecl(),
7129 /*Inline*/false, SourceLocation(),
7130 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007131 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007132 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007133 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007134 }
7135
7136 VaListDecl->startDefinition();
7137
7138 // void * __ap;
7139 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7140 VaListDecl,
7141 SourceLocation(),
7142 SourceLocation(),
7143 &Context->Idents.get("__ap"),
7144 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007145 /*TInfo=*/nullptr,
7146 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007147 /*Mutable=*/false,
7148 ICIS_NoInit);
7149 Field->setAccess(AS_public);
7150 VaListDecl->addDecl(Field);
7151
7152 // };
7153 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007154 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007155
7156 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007157 QualType T = Context->getRecordType(VaListDecl);
7158 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007159}
7160
Ulrich Weigand47445072013-05-06 16:26:41 +00007161static TypedefDecl *
7162CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007163 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007164 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007165 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007166 VaListTagDecl->startDefinition();
7167
7168 const size_t NumFields = 4;
7169 QualType FieldTypes[NumFields];
7170 const char *FieldNames[NumFields];
7171
7172 // long __gpr;
7173 FieldTypes[0] = Context->LongTy;
7174 FieldNames[0] = "__gpr";
7175
7176 // long __fpr;
7177 FieldTypes[1] = Context->LongTy;
7178 FieldNames[1] = "__fpr";
7179
7180 // void *__overflow_arg_area;
7181 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7182 FieldNames[2] = "__overflow_arg_area";
7183
7184 // void *__reg_save_area;
7185 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7186 FieldNames[3] = "__reg_save_area";
7187
7188 // Create fields
7189 for (unsigned i = 0; i < NumFields; ++i) {
7190 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7191 VaListTagDecl,
7192 SourceLocation(),
7193 SourceLocation(),
7194 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007195 FieldTypes[i], /*TInfo=*/nullptr,
7196 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007197 /*Mutable=*/false,
7198 ICIS_NoInit);
7199 Field->setAccess(AS_public);
7200 VaListTagDecl->addDecl(Field);
7201 }
7202 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007203 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007204 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007205
Richard Smith9b88a4c2015-07-27 05:40:23 +00007206 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007207
7208 // typedef __va_list_tag __builtin_va_list[1];
7209 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007210 QualType VaListTagArrayType =
7211 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007212
Alp Toker56b5cc92013-12-15 10:36:26 +00007213 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007214}
7215
Meador Inge5d3fb222012-06-16 03:34:49 +00007216static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7217 TargetInfo::BuiltinVaListKind Kind) {
7218 switch (Kind) {
7219 case TargetInfo::CharPtrBuiltinVaList:
7220 return CreateCharPtrBuiltinVaListDecl(Context);
7221 case TargetInfo::VoidPtrBuiltinVaList:
7222 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007223 case TargetInfo::AArch64ABIBuiltinVaList:
7224 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007225 case TargetInfo::PowerABIBuiltinVaList:
7226 return CreatePowerABIBuiltinVaListDecl(Context);
7227 case TargetInfo::X86_64ABIBuiltinVaList:
7228 return CreateX86_64ABIBuiltinVaListDecl(Context);
7229 case TargetInfo::PNaClABIBuiltinVaList:
7230 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007231 case TargetInfo::AAPCSABIBuiltinVaList:
7232 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007233 case TargetInfo::SystemZBuiltinVaList:
7234 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007235 }
7236
7237 llvm_unreachable("Unhandled __builtin_va_list type kind");
7238}
7239
7240TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007241 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007242 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007243 assert(BuiltinVaListDecl->isImplicit());
7244 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007245
7246 return BuiltinVaListDecl;
7247}
7248
Richard Smith9b88a4c2015-07-27 05:40:23 +00007249Decl *ASTContext::getVaListTagDecl() const {
7250 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007251 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007252 if (!VaListTagDecl)
7253 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007254
Richard Smith9b88a4c2015-07-27 05:40:23 +00007255 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007256}
7257
Charles Davisc7d5c942015-09-17 20:55:33 +00007258TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7259 if (!BuiltinMSVaListDecl)
7260 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7261
7262 return BuiltinMSVaListDecl;
7263}
7264
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007265void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007266 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007267 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007268
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007269 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007270}
7271
John McCalld28ae272009-12-02 08:04:21 +00007272/// \brief Retrieve the template name that corresponds to a non-empty
7273/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007274TemplateName
7275ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7276 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007277 unsigned size = End - Begin;
7278 assert(size > 1 && "set is not overloaded!");
7279
7280 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7281 size * sizeof(FunctionTemplateDecl*));
7282 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
7283
7284 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007285 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007286 NamedDecl *D = *I;
7287 assert(isa<FunctionTemplateDecl>(D) ||
7288 (isa<UsingShadowDecl>(D) &&
7289 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7290 *Storage++ = D;
7291 }
7292
7293 return TemplateName(OT);
7294}
7295
Douglas Gregordc572a32009-03-30 22:58:21 +00007296/// \brief Retrieve the template name that represents a qualified
7297/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007298TemplateName
7299ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7300 bool TemplateKeyword,
7301 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007302 assert(NNS && "Missing nested-name-specifier in qualified template name");
7303
Douglas Gregorc42075a2010-02-04 18:10:26 +00007304 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007305 llvm::FoldingSetNodeID ID;
7306 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7307
Craig Topper36250ad2014-05-12 05:36:57 +00007308 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007309 QualifiedTemplateName *QTN =
7310 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7311 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007312 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007313 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007314 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7315 }
7316
7317 return TemplateName(QTN);
7318}
7319
7320/// \brief Retrieve the template name that represents a dependent
7321/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007322TemplateName
7323ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7324 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007325 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007326 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007327
7328 llvm::FoldingSetNodeID ID;
7329 DependentTemplateName::Profile(ID, NNS, Name);
7330
Craig Topper36250ad2014-05-12 05:36:57 +00007331 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007332 DependentTemplateName *QTN =
7333 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7334
7335 if (QTN)
7336 return TemplateName(QTN);
7337
7338 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7339 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007340 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007341 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007342 } else {
7343 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007344 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007345 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007346 DependentTemplateName *CheckQTN =
7347 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7348 assert(!CheckQTN && "Dependent type name canonicalization broken");
7349 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007350 }
7351
7352 DependentTemplateNames.InsertNode(QTN, InsertPos);
7353 return TemplateName(QTN);
7354}
7355
Douglas Gregor71395fa2009-11-04 00:56:37 +00007356/// \brief Retrieve the template name that represents a dependent
7357/// template name such as \c MetaFun::template operator+.
7358TemplateName
7359ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007360 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007361 assert((!NNS || NNS->isDependent()) &&
7362 "Nested name specifier must be dependent");
7363
7364 llvm::FoldingSetNodeID ID;
7365 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007366
7367 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007368 DependentTemplateName *QTN
7369 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007370
7371 if (QTN)
7372 return TemplateName(QTN);
7373
7374 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7375 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007376 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007377 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007378 } else {
7379 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007380 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007381 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007382
Douglas Gregorc42075a2010-02-04 18:10:26 +00007383 DependentTemplateName *CheckQTN
7384 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7385 assert(!CheckQTN && "Dependent template name canonicalization broken");
7386 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007387 }
7388
7389 DependentTemplateNames.InsertNode(QTN, InsertPos);
7390 return TemplateName(QTN);
7391}
7392
Douglas Gregor5590be02011-01-15 06:45:20 +00007393TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007394ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7395 TemplateName replacement) const {
7396 llvm::FoldingSetNodeID ID;
7397 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007398
7399 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007400 SubstTemplateTemplateParmStorage *subst
7401 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7402
7403 if (!subst) {
7404 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7405 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7406 }
7407
7408 return TemplateName(subst);
7409}
7410
7411TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007412ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7413 const TemplateArgument &ArgPack) const {
7414 ASTContext &Self = const_cast<ASTContext &>(*this);
7415 llvm::FoldingSetNodeID ID;
7416 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007417
7418 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007419 SubstTemplateTemplateParmPackStorage *Subst
7420 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7421
7422 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00007423 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007424 ArgPack.pack_size(),
7425 ArgPack.pack_begin());
7426 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7427 }
7428
7429 return TemplateName(Subst);
7430}
7431
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007432/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007433/// TargetInfo, produce the corresponding type. The unsigned @p Type
7434/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007435CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007436 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00007437 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007438 case TargetInfo::SignedChar: return SignedCharTy;
7439 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007440 case TargetInfo::SignedShort: return ShortTy;
7441 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7442 case TargetInfo::SignedInt: return IntTy;
7443 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7444 case TargetInfo::SignedLong: return LongTy;
7445 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7446 case TargetInfo::SignedLongLong: return LongLongTy;
7447 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7448 }
7449
David Blaikie83d382b2011-09-23 05:06:16 +00007450 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007451}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007452
7453//===----------------------------------------------------------------------===//
7454// Type Predicates.
7455//===----------------------------------------------------------------------===//
7456
Fariborz Jahanian96207692009-02-18 21:49:28 +00007457/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7458/// garbage collection attribute.
7459///
John McCall553d45a2011-01-12 00:34:59 +00007460Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007461 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007462 return Qualifiers::GCNone;
7463
David Blaikiebbafb8a2012-03-11 07:00:24 +00007464 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007465 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7466
7467 // Default behaviour under objective-C's gc is for ObjC pointers
7468 // (or pointers to them) be treated as though they were declared
7469 // as __strong.
7470 if (GCAttrs == Qualifiers::GCNone) {
7471 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7472 return Qualifiers::Strong;
7473 else if (Ty->isPointerType())
7474 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7475 } else {
7476 // It's not valid to set GC attributes on anything that isn't a
7477 // pointer.
7478#ifndef NDEBUG
7479 QualType CT = Ty->getCanonicalTypeInternal();
7480 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7481 CT = AT->getElementType();
7482 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7483#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007484 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007485 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007486}
7487
Chris Lattner49af6a42008-04-07 06:51:04 +00007488//===----------------------------------------------------------------------===//
7489// Type Compatibility Testing
7490//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007491
Mike Stump11289f42009-09-09 15:08:12 +00007492/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007493/// compatible.
7494static bool areCompatVectorTypes(const VectorType *LHS,
7495 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007496 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007497 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007498 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007499}
7500
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007501bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7502 QualType SecondVec) {
7503 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7504 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7505
7506 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7507 return true;
7508
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007509 // Treat Neon vector types and most AltiVec vector types as if they are the
7510 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007511 const VectorType *First = FirstVec->getAs<VectorType>();
7512 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007513 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007514 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007515 First->getVectorKind() != VectorType::AltiVecPixel &&
7516 First->getVectorKind() != VectorType::AltiVecBool &&
7517 Second->getVectorKind() != VectorType::AltiVecPixel &&
7518 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007519 return true;
7520
7521 return false;
7522}
7523
Steve Naroff8e6aee52009-07-23 01:01:38 +00007524//===----------------------------------------------------------------------===//
7525// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7526//===----------------------------------------------------------------------===//
7527
7528/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7529/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007530bool
7531ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7532 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007533 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007534 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007535 for (auto *PI : rProto->protocols())
7536 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007537 return true;
7538 return false;
7539}
7540
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007541/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7542/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007543bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7544 QualType rhs) {
7545 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7546 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007547 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007548
Aaron Ballman83731462014-03-17 16:14:00 +00007549 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007550 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007551 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007552 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7553 match = true;
7554 break;
7555 }
7556 }
7557 if (!match)
7558 return false;
7559 }
7560 return true;
7561}
7562
Steve Naroff8e6aee52009-07-23 01:01:38 +00007563/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7564/// ObjCQualifiedIDType.
7565bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7566 bool compare) {
7567 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007568 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007569 lhs->isObjCIdType() || lhs->isObjCClassType())
7570 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007571 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007572 rhs->isObjCIdType() || rhs->isObjCClassType())
7573 return true;
7574
7575 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00007576 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007577
Steve Naroff8e6aee52009-07-23 01:01:38 +00007578 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007579
Steve Naroff8e6aee52009-07-23 01:01:38 +00007580 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007581 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007582 // make sure we check the class hierarchy.
7583 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007584 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007585 // when comparing an id<P> on lhs with a static type on rhs,
7586 // see if static class implements all of id's protocols, directly or
7587 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007588 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007589 return false;
7590 }
7591 }
7592 // If there are no qualifiers and no interface, we have an 'id'.
7593 return true;
7594 }
Mike Stump11289f42009-09-09 15:08:12 +00007595 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007596 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007597 bool match = false;
7598
7599 // when comparing an id<P> on lhs with a static type on rhs,
7600 // see if static class implements all of id's protocols, directly or
7601 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007602 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007603 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7604 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7605 match = true;
7606 break;
7607 }
7608 }
Mike Stump11289f42009-09-09 15:08:12 +00007609 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007610 // make sure we check the class hierarchy.
7611 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007612 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007613 // when comparing an id<P> on lhs with a static type on rhs,
7614 // see if static class implements all of id's protocols, directly or
7615 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007616 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007617 match = true;
7618 break;
7619 }
7620 }
7621 }
7622 if (!match)
7623 return false;
7624 }
Mike Stump11289f42009-09-09 15:08:12 +00007625
Steve Naroff8e6aee52009-07-23 01:01:38 +00007626 return true;
7627 }
Mike Stump11289f42009-09-09 15:08:12 +00007628
Steve Naroff8e6aee52009-07-23 01:01:38 +00007629 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7630 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7631
Mike Stump11289f42009-09-09 15:08:12 +00007632 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007633 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007634 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007635 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007636 bool match = false;
7637
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007638 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007639 // see if static class implements all of id's protocols, directly or
7640 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007641 // First, lhs protocols in the qualifier list must be found, direct
7642 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007643 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007644 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7645 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7646 match = true;
7647 break;
7648 }
7649 }
7650 if (!match)
7651 return false;
7652 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007653
7654 // Static class's protocols, or its super class or category protocols
7655 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7656 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7657 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7658 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7659 // This is rather dubious but matches gcc's behavior. If lhs has
7660 // no type qualifier and its class has no static protocol(s)
7661 // assume that it is mismatch.
7662 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7663 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007664 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007665 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007666 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007667 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7668 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7669 match = true;
7670 break;
7671 }
7672 }
7673 if (!match)
7674 return false;
7675 }
7676 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007677 return true;
7678 }
7679 return false;
7680}
7681
Eli Friedman47f77112008-08-22 00:56:42 +00007682/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007683/// compatible for assignment from RHS to LHS. This handles validation of any
7684/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007685bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7686 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007687 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7688 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7689
Steve Naroff1329fa02009-07-15 18:40:39 +00007690 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007691 if (LHS->isObjCUnqualifiedIdOrClass() ||
7692 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007693 return true;
7694
Douglas Gregorab209d82015-07-07 03:58:42 +00007695 // Function object that propagates a successful result or handles
7696 // __kindof types.
7697 auto finish = [&](bool succeeded) -> bool {
7698 if (succeeded)
7699 return true;
7700
7701 if (!RHS->isKindOfType())
7702 return false;
7703
7704 // Strip off __kindof and protocol qualifiers, then check whether
7705 // we can assign the other way.
7706 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7707 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7708 };
7709
7710 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7711 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7712 QualType(RHSOPT,0),
7713 false));
7714 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007715
Douglas Gregorab209d82015-07-07 03:58:42 +00007716 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7717 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7718 QualType(RHSOPT,0)));
7719 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007720
John McCall8b07ec22010-05-15 11:32:37 +00007721 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007722 if (LHS->getInterface() && RHS->getInterface()) {
7723 return finish(canAssignObjCInterfaces(LHS, RHS));
7724 }
Mike Stump11289f42009-09-09 15:08:12 +00007725
Steve Naroff8e6aee52009-07-23 01:01:38 +00007726 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007727}
7728
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007729/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007730/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007731/// arguments in block literals. When passed as arguments, passing 'A*' where
7732/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7733/// not OK. For the return type, the opposite is not OK.
7734bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7735 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007736 const ObjCObjectPointerType *RHSOPT,
7737 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007738
7739 // Function object that propagates a successful result or handles
7740 // __kindof types.
7741 auto finish = [&](bool succeeded) -> bool {
7742 if (succeeded)
7743 return true;
7744
7745 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7746 if (!Expected->isKindOfType())
7747 return false;
7748
7749 // Strip off __kindof and protocol qualifiers, then check whether
7750 // we can assign the other way.
7751 return canAssignObjCInterfacesInBlockPointer(
7752 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7753 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7754 BlockReturnType);
7755 };
7756
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007757 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007758 return true;
7759
7760 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007761 return finish(RHSOPT->isObjCBuiltinType() ||
7762 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007763 }
7764
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007765 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007766 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7767 QualType(RHSOPT,0),
7768 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007769
7770 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7771 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7772 if (LHS && RHS) { // We have 2 user-defined types.
7773 if (LHS != RHS) {
7774 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007775 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007776 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007777 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007778 }
7779 else
7780 return true;
7781 }
7782 return false;
7783}
7784
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007785/// Comparison routine for Objective-C protocols to be used with
7786/// llvm::array_pod_sort.
7787static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7788 ObjCProtocolDecl * const *rhs) {
7789 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007790}
7791
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007792/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007793/// of protocols inherited from two distinct objective-c pointer objects with
7794/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007795/// It is used to build composite qualifier list of the composite type of
7796/// the conditional expression involving two objective-c pointer objects.
7797static
7798void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007799 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007800 const ObjCObjectPointerType *LHSOPT,
7801 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007802 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007803
John McCall8b07ec22010-05-15 11:32:37 +00007804 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7805 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7806 assert(LHS->getInterface() && "LHS must have an interface base");
7807 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007808
7809 // Add all of the protocols for the LHS.
7810 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7811
7812 // Start with the protocol qualifiers.
7813 for (auto proto : LHS->quals()) {
7814 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007815 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007816
7817 // Also add the protocols associated with the LHS interface.
7818 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7819
7820 // Add all of the protocls for the RHS.
7821 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7822
7823 // Start with the protocol qualifiers.
7824 for (auto proto : RHS->quals()) {
7825 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007826 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007827
7828 // Also add the protocols associated with the RHS interface.
7829 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7830
7831 // Compute the intersection of the collected protocol sets.
7832 for (auto proto : LHSProtocolSet) {
7833 if (RHSProtocolSet.count(proto))
7834 IntersectionSet.push_back(proto);
7835 }
7836
7837 // Compute the set of protocols that is implied by either the common type or
7838 // the protocols within the intersection.
7839 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7840 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7841
7842 // Remove any implied protocols from the list of inherited protocols.
7843 if (!ImpliedProtocols.empty()) {
7844 IntersectionSet.erase(
7845 std::remove_if(IntersectionSet.begin(),
7846 IntersectionSet.end(),
7847 [&](ObjCProtocolDecl *proto) -> bool {
7848 return ImpliedProtocols.count(proto) > 0;
7849 }),
7850 IntersectionSet.end());
7851 }
7852
7853 // Sort the remaining protocols by name.
7854 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7855 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007856}
7857
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007858/// Determine whether the first type is a subtype of the second.
7859static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7860 QualType rhs) {
7861 // Common case: two object pointers.
7862 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7863 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7864 if (lhsOPT && rhsOPT)
7865 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7866
7867 // Two block pointers.
7868 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7869 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7870 if (lhsBlock && rhsBlock)
7871 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7872
7873 // If either is an unqualified 'id' and the other is a block, it's
7874 // acceptable.
7875 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7876 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7877 return true;
7878
7879 return false;
7880}
7881
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007882// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007883static bool sameObjCTypeArgs(ASTContext &ctx,
7884 const ObjCInterfaceDecl *iface,
7885 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007886 ArrayRef<QualType> rhsArgs,
7887 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007888 if (lhsArgs.size() != rhsArgs.size())
7889 return false;
7890
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007891 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007892 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007893 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7894 continue;
7895
7896 switch (typeParams->begin()[i]->getVariance()) {
7897 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007898 if (!stripKindOf ||
7899 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7900 rhsArgs[i].stripObjCKindOfType(ctx))) {
7901 return false;
7902 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007903 break;
7904
7905 case ObjCTypeParamVariance::Covariant:
7906 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7907 return false;
7908 break;
7909
7910 case ObjCTypeParamVariance::Contravariant:
7911 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7912 return false;
7913 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007914 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007915 }
7916
7917 return true;
7918}
7919
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007920QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007921 const ObjCObjectPointerType *Lptr,
7922 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007923 const ObjCObjectType *LHS = Lptr->getObjectType();
7924 const ObjCObjectType *RHS = Rptr->getObjectType();
7925 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7926 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007927
7928 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007929 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007930
Manman Renc46f7d12016-05-06 19:35:02 +00007931 // When either LHS or RHS is a kindof type, we should return a kindof type.
7932 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7933 // kindof(A).
7934 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7935
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007936 // Follow the left-hand side up the class hierarchy until we either hit a
7937 // root or find the RHS. Record the ancestors in case we don't find it.
7938 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7939 LHSAncestors;
7940 while (true) {
7941 // Record this ancestor. We'll need this if the common type isn't in the
7942 // path from the LHS to the root.
7943 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007944
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007945 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7946 // Get the type arguments.
7947 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7948 bool anyChanges = false;
7949 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7950 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007951 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7952 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007953 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007954 return QualType();
7955 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7956 // If only one has type arguments, the result will not have type
7957 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007958 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007959 anyChanges = true;
7960 }
7961
7962 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007963 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007964 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7965 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007966 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007967 anyChanges = true;
7968
7969 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007970 // If we need to return a kindof type but LHS is not a kindof type, we
7971 // build a new result type.
7972 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007973 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007974 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007975 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007976 return getObjCObjectPointerType(Result);
7977 }
7978
7979 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007980 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007981
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007982 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007983 QualType LHSSuperType = LHS->getSuperClassType();
7984 if (LHSSuperType.isNull())
7985 break;
7986
7987 LHS = LHSSuperType->castAs<ObjCObjectType>();
7988 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007989
7990 // We didn't find anything by following the LHS to its root; now check
7991 // the RHS against the cached set of ancestors.
7992 while (true) {
7993 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7994 if (KnownLHS != LHSAncestors.end()) {
7995 LHS = KnownLHS->second;
7996
7997 // Get the type arguments.
7998 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7999 bool anyChanges = false;
8000 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8001 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008002 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8003 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008004 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008005 return QualType();
8006 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8007 // If only one has type arguments, the result will not have type
8008 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008009 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008010 anyChanges = true;
8011 }
8012
8013 // Compute the intersection of protocols.
8014 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8015 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8016 Protocols);
8017 if (!Protocols.empty())
8018 anyChanges = true;
8019
Manman Renc46f7d12016-05-06 19:35:02 +00008020 // If we need to return a kindof type but RHS is not a kindof type, we
8021 // build a new result type.
8022 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008023 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008024 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008025 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008026 return getObjCObjectPointerType(Result);
8027 }
8028
8029 return getObjCObjectPointerType(QualType(RHS, 0));
8030 }
8031
8032 // Find the superclass of the RHS.
8033 QualType RHSSuperType = RHS->getSuperClassType();
8034 if (RHSSuperType.isNull())
8035 break;
8036
8037 RHS = RHSSuperType->castAs<ObjCObjectType>();
8038 }
8039
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008040 return QualType();
8041}
8042
John McCall8b07ec22010-05-15 11:32:37 +00008043bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8044 const ObjCObjectType *RHS) {
8045 assert(LHS->getInterface() && "LHS is not an interface type");
8046 assert(RHS->getInterface() && "RHS is not an interface type");
8047
Chris Lattner49af6a42008-04-07 06:51:04 +00008048 // Verify that the base decls are compatible: the RHS must be a subclass of
8049 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008050 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8051 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8052 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008053 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008054
Douglas Gregore83b9562015-07-07 03:57:53 +00008055 // If the LHS has protocol qualifiers, determine whether all of them are
8056 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8057 // LHS).
8058 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008059 // OK if conversion of LHS to SuperClass results in narrowing of types
8060 // ; i.e., SuperClass may implement at least one of the protocols
8061 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8062 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8063 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8064 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8065 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8066 // qualifiers.
8067 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008068 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008069 // If there is no protocols associated with RHS, it is not a match.
8070 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008071 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008072
8073 for (const auto *LHSProto : LHS->quals()) {
8074 bool SuperImplementsProtocol = false;
8075 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8076 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8077 SuperImplementsProtocol = true;
8078 break;
8079 }
8080 if (!SuperImplementsProtocol)
8081 return false;
8082 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008083 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008084
8085 // If the LHS is specialized, we may need to check type arguments.
8086 if (LHS->isSpecialized()) {
8087 // Follow the superclass chain until we've matched the LHS class in the
8088 // hierarchy. This substitutes type arguments through.
8089 const ObjCObjectType *RHSSuper = RHS;
8090 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8091 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8092
8093 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008094 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008095 !sameObjCTypeArgs(*this, LHS->getInterface(),
8096 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008097 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008098 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008099 }
8100 }
8101
8102 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008103}
8104
Steve Naroffb7605152009-02-12 17:52:19 +00008105bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8106 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00008107 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8108 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008109
Steve Naroff7cae42b2009-07-10 23:34:53 +00008110 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008111 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008112
8113 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8114 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008115}
8116
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008117bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8118 return canAssignObjCInterfaces(
8119 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8120 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8121}
8122
Mike Stump11289f42009-09-09 15:08:12 +00008123/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008124/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008125/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008126/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008127bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8128 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008129 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008130 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008131
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008132 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008133}
8134
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008135bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008136 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008137}
8138
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008139bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8140 return !mergeTypes(LHS, RHS, true).isNull();
8141}
8142
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008143/// mergeTransparentUnionType - if T is a transparent union type and a member
8144/// of T is compatible with SubType, return the merged type, else return
8145/// QualType()
8146QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8147 bool OfBlockPointer,
8148 bool Unqualified) {
8149 if (const RecordType *UT = T->getAsUnionType()) {
8150 RecordDecl *UD = UT->getDecl();
8151 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008152 for (const auto *I : UD->fields()) {
8153 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008154 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8155 if (!MT.isNull())
8156 return MT;
8157 }
8158 }
8159 }
8160
8161 return QualType();
8162}
8163
Alp Toker9cacbab2014-01-20 20:26:09 +00008164/// mergeFunctionParameterTypes - merge two types which appear as function
8165/// parameter types
8166QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8167 bool OfBlockPointer,
8168 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008169 // GNU extension: two types are compatible if they appear as a function
8170 // argument, one of the types is a transparent union type and the other
8171 // type is compatible with a union member
8172 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8173 Unqualified);
8174 if (!lmerge.isNull())
8175 return lmerge;
8176
8177 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8178 Unqualified);
8179 if (!rmerge.isNull())
8180 return rmerge;
8181
8182 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8183}
8184
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008185QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008186 bool OfBlockPointer,
8187 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00008188 const FunctionType *lbase = lhs->getAs<FunctionType>();
8189 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008190 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
8191 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008192 bool allLTypes = true;
8193 bool allRTypes = true;
8194
8195 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008196 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008197 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008198 QualType RHS = rbase->getReturnType();
8199 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008200 bool UnqualifiedResult = Unqualified;
8201 if (!UnqualifiedResult)
8202 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008203 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008204 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008205 else
Alp Toker314cc812014-01-25 16:55:45 +00008206 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008207 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008208 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008209
8210 if (Unqualified)
8211 retType = retType.getUnqualifiedType();
8212
Alp Toker314cc812014-01-25 16:55:45 +00008213 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8214 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008215 if (Unqualified) {
8216 LRetType = LRetType.getUnqualifiedType();
8217 RRetType = RRetType.getUnqualifiedType();
8218 }
8219
8220 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008221 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008222 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008223 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008224
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008225 // FIXME: double check this
8226 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8227 // rbase->getRegParmAttr() != 0 &&
8228 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008229 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8230 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008231
Douglas Gregor8c940862010-01-18 17:14:39 +00008232 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008233 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00008234 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00008235
John McCall8c6b56f2010-12-15 01:06:38 +00008236 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008237 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
8238 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00008239 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
8240 return QualType();
8241
John McCall31168b02011-06-15 23:02:42 +00008242 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
8243 return QualType();
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008244 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
8245 return QualType();
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008246 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
8247 return QualType();
John McCall31168b02011-06-15 23:02:42 +00008248
John McCall8c6b56f2010-12-15 01:06:38 +00008249 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8250 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008251
Rafael Espindola8778c282012-11-29 16:09:03 +00008252 if (lbaseInfo.getNoReturn() != NoReturn)
8253 allLTypes = false;
8254 if (rbaseInfo.getNoReturn() != NoReturn)
8255 allRTypes = false;
8256
John McCall31168b02011-06-15 23:02:42 +00008257 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008258
Eli Friedman47f77112008-08-22 00:56:42 +00008259 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008260 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8261 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008262 // Compatible functions must have the same number of parameters
8263 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00008264 return QualType();
8265
8266 // Variadic and non-variadic functions aren't compatible
8267 if (lproto->isVariadic() != rproto->isVariadic())
8268 return QualType();
8269
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008270 if (lproto->getTypeQuals() != rproto->getTypeQuals())
8271 return QualType();
8272
Akira Hatanaka98a49332017-09-22 00:41:05 +00008273 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8274 bool canUseLeft, canUseRight;
8275 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8276 newParamInfos))
Fariborz Jahanian97676972011-09-28 21:52:05 +00008277 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00008278
Akira Hatanaka98a49332017-09-22 00:41:05 +00008279 if (!canUseLeft)
8280 allLTypes = false;
8281 if (!canUseRight)
8282 allRTypes = false;
8283
Alp Toker601b22c2014-01-21 23:35:24 +00008284 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008285 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008286 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8287 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8288 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8289 QualType paramType = mergeFunctionParameterTypes(
8290 lParamType, rParamType, OfBlockPointer, Unqualified);
8291 if (paramType.isNull())
8292 return QualType();
8293
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008294 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008295 paramType = paramType.getUnqualifiedType();
8296
8297 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008298 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008299 lParamType = lParamType.getUnqualifiedType();
8300 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008301 }
Alp Toker601b22c2014-01-21 23:35:24 +00008302
8303 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008304 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008305 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008306 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008307 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008308
Eli Friedman47f77112008-08-22 00:56:42 +00008309 if (allLTypes) return lhs;
8310 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008311
8312 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8313 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008314 EPI.ExtParameterInfos =
8315 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008316 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008317 }
8318
8319 if (lproto) allRTypes = false;
8320 if (rproto) allLTypes = false;
8321
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008322 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008323 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008324 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00008325 if (proto->isVariadic()) return QualType();
8326 // Check that the types are compatible with the types that
8327 // would result from default argument promotions (C99 6.7.5.3p15).
8328 // The only types actually affected are promotable integer
8329 // types and floats, which would be passed as a different
8330 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008331 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8332 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008333
Eli Friedman448ce402012-08-30 00:44:15 +00008334 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008335 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00008336 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
8337 paramTy = Enum->getDecl()->getIntegerType();
8338 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00008339 return QualType();
8340 }
Alp Toker601b22c2014-01-21 23:35:24 +00008341
8342 if (paramTy->isPromotableIntegerType() ||
8343 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00008344 return QualType();
8345 }
8346
8347 if (allLTypes) return lhs;
8348 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008349
8350 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8351 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008352 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008353 }
8354
8355 if (allLTypes) return lhs;
8356 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008357 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008358}
8359
John McCall433c2e62013-03-21 00:10:07 +00008360/// Given that we have an enum type and a non-enum type, try to merge them.
8361static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8362 QualType other, bool isBlockReturnType) {
8363 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8364 // a signed integer type, or an unsigned integer type.
8365 // Compatibility is based on the underlying type, not the promotion
8366 // type.
8367 QualType underlyingType = ET->getDecl()->getIntegerType();
8368 if (underlyingType.isNull()) return QualType();
8369 if (Context.hasSameType(underlyingType, other))
8370 return other;
8371
8372 // In block return types, we're more permissive and accept any
8373 // integral type of the same size.
8374 if (isBlockReturnType && other->isIntegerType() &&
8375 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8376 return other;
8377
8378 return QualType();
8379}
8380
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008381QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008382 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008383 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008384 // C++ [expr]: If an expression initially has the type "reference to T", the
8385 // type is adjusted to "T" prior to any further analysis, the expression
8386 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008387 // expression is an lvalue unless the reference is an rvalue reference and
8388 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008389 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8390 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008391
8392 if (Unqualified) {
8393 LHS = LHS.getUnqualifiedType();
8394 RHS = RHS.getUnqualifiedType();
8395 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00008396
Eli Friedman47f77112008-08-22 00:56:42 +00008397 QualType LHSCan = getCanonicalType(LHS),
8398 RHSCan = getCanonicalType(RHS);
8399
8400 // If two types are identical, they are compatible.
8401 if (LHSCan == RHSCan)
8402 return LHS;
8403
John McCall8ccfcb52009-09-24 19:53:00 +00008404 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008405 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8406 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008407 if (LQuals != RQuals) {
8408 // If any of these qualifiers are different, we have a type
8409 // mismatch.
8410 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008411 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008412 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8413 LQuals.hasUnaligned() != RQuals.hasUnaligned())
John McCall8ccfcb52009-09-24 19:53:00 +00008414 return QualType();
8415
8416 // Exactly one GC qualifier difference is allowed: __strong is
8417 // okay if the other type has no GC qualifier but is an Objective
8418 // C object pointer (i.e. implicitly strong by default). We fix
8419 // this by pretending that the unqualified type was actually
8420 // qualified __strong.
8421 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8422 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8423 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8424
8425 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8426 return QualType();
8427
8428 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8429 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8430 }
8431 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8432 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8433 }
Eli Friedman47f77112008-08-22 00:56:42 +00008434 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00008435 }
8436
8437 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008438
Eli Friedmandcca6332009-06-01 01:22:52 +00008439 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8440 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008441
Chris Lattnerfd652912008-01-14 05:45:46 +00008442 // We want to consider the two function types to be the same for these
8443 // comparisons, just force one to the other.
8444 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8445 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008446
8447 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008448 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8449 LHSClass = Type::ConstantArray;
8450 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8451 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008452
John McCall8b07ec22010-05-15 11:32:37 +00008453 // ObjCInterfaces are just specialized ObjCObjects.
8454 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8455 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8456
Nate Begemance4d7fc2008-04-18 23:10:10 +00008457 // Canonicalize ExtVector -> Vector.
8458 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8459 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008460
Chris Lattner95554662008-04-07 05:43:21 +00008461 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008462 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008463 // Note that we only have special rules for turning block enum
8464 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00008465 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008466 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008467 }
John McCall9dd450b2009-09-21 23:43:11 +00008468 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008469 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008470 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008471 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008472 if (OfBlockPointer && !BlockReturnType) {
8473 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8474 return LHS;
8475 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8476 return RHS;
8477 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008478
Eli Friedman47f77112008-08-22 00:56:42 +00008479 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00008480 }
Eli Friedman47f77112008-08-22 00:56:42 +00008481
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008482 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008483 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008484#define TYPE(Class, Base)
8485#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008486#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008487#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8488#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8489#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008490 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008491
Richard Smith27d807c2013-04-30 13:56:41 +00008492 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008493 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008494 case Type::LValueReference:
8495 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008496 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008497 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008498
John McCall8b07ec22010-05-15 11:32:37 +00008499 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008500 case Type::IncompleteArray:
8501 case Type::VariableArray:
8502 case Type::FunctionProto:
8503 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008504 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008505
Chris Lattnerfd652912008-01-14 05:45:46 +00008506 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008507 {
8508 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008509 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8510 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008511 if (Unqualified) {
8512 LHSPointee = LHSPointee.getUnqualifiedType();
8513 RHSPointee = RHSPointee.getUnqualifiedType();
8514 }
8515 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8516 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008517 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00008518 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008519 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008520 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008521 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008522 return getPointerType(ResultType);
8523 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008524 case Type::BlockPointer:
8525 {
8526 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008527 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8528 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008529 if (Unqualified) {
8530 LHSPointee = LHSPointee.getUnqualifiedType();
8531 RHSPointee = RHSPointee.getUnqualifiedType();
8532 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008533 if (getLangOpts().OpenCL) {
8534 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8535 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8536 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8537 // 6.12.5) thus the following check is asymmetric.
8538 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
8539 return QualType();
8540 LHSPteeQual.removeAddressSpace();
8541 RHSPteeQual.removeAddressSpace();
8542 LHSPointee =
8543 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8544 RHSPointee =
8545 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8546 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008547 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8548 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00008549 if (ResultType.isNull()) return QualType();
8550 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8551 return LHS;
8552 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8553 return RHS;
8554 return getBlockPointerType(ResultType);
8555 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008556 case Type::Atomic:
8557 {
8558 // Merge two pointer types, while trying to preserve typedef info
8559 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8560 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8561 if (Unqualified) {
8562 LHSValue = LHSValue.getUnqualifiedType();
8563 RHSValue = RHSValue.getUnqualifiedType();
8564 }
8565 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8566 Unqualified);
8567 if (ResultType.isNull()) return QualType();
8568 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8569 return LHS;
8570 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8571 return RHS;
8572 return getAtomicType(ResultType);
8573 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008574 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008575 {
8576 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8577 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8578 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8579 return QualType();
8580
8581 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8582 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008583 if (Unqualified) {
8584 LHSElem = LHSElem.getUnqualifiedType();
8585 RHSElem = RHSElem.getUnqualifiedType();
8586 }
8587
8588 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008589 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00008590 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8591 return LHS;
8592 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8593 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008594 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8595 ArrayType::ArraySizeModifier(), 0);
8596 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8597 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008598 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8599 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00008600 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8601 return LHS;
8602 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8603 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008604 if (LVAT) {
8605 // FIXME: This isn't correct! But tricky to implement because
8606 // the array's size has to be the size of LHS, but the type
8607 // has to be different.
8608 return LHS;
8609 }
8610 if (RVAT) {
8611 // FIXME: This isn't correct! But tricky to implement because
8612 // the array's size has to be the size of RHS, but the type
8613 // has to be different.
8614 return RHS;
8615 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008616 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8617 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008618 return getIncompleteArrayType(ResultType,
8619 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008620 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008621 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008622 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008623 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008624 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00008625 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00008626 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008627 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00008628 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00008629 case Type::Complex:
8630 // Distinct complex types are incompatible.
8631 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008632 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008633 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008634 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8635 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008636 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00008637 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00008638 case Type::ObjCObject: {
8639 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008640 // FIXME: This should be type compatibility, e.g. whether
8641 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00008642 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8643 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8644 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008645 return LHS;
8646
Eli Friedman47f77112008-08-22 00:56:42 +00008647 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00008648 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008649 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008650 if (OfBlockPointer) {
8651 if (canAssignObjCInterfacesInBlockPointer(
8652 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008653 RHS->getAs<ObjCObjectPointerType>(),
8654 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008655 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008656 return QualType();
8657 }
John McCall9dd450b2009-09-21 23:43:11 +00008658 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8659 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008660 return LHS;
8661
Steve Naroffc68cfcf2008-12-10 22:14:21 +00008662 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00008663 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00008664 assert(LHS != RHS &&
8665 "Equivalent pipe types should have already been handled!");
8666 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00008667 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008668
David Blaikie8a40f702012-01-17 06:56:22 +00008669 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008670}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008671
Akira Hatanaka98a49332017-09-22 00:41:05 +00008672bool ASTContext::mergeExtParameterInfo(
8673 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
8674 bool &CanUseFirst, bool &CanUseSecond,
8675 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
8676 assert(NewParamInfos.empty() && "param info list not empty");
8677 CanUseFirst = CanUseSecond = true;
8678 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
8679 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
8680
John McCall18afab72016-03-01 00:49:02 +00008681 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00008682 // we match if and only if the second type also doesn't have them.
8683 if (!FirstHasInfo && !SecondHasInfo)
8684 return true;
John McCall18afab72016-03-01 00:49:02 +00008685
Akira Hatanaka98a49332017-09-22 00:41:05 +00008686 bool NeedParamInfo = false;
8687 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
8688 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00008689
Akira Hatanaka98a49332017-09-22 00:41:05 +00008690 for (size_t I = 0; I < E; ++I) {
8691 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
8692 if (FirstHasInfo)
8693 FirstParam = FirstFnType->getExtParameterInfo(I);
8694 if (SecondHasInfo)
8695 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00008696
Akira Hatanaka98a49332017-09-22 00:41:05 +00008697 // Cannot merge unless everything except the noescape flag matches.
8698 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00008699 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008700
8701 bool FirstNoEscape = FirstParam.isNoEscape();
8702 bool SecondNoEscape = SecondParam.isNoEscape();
8703 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
8704 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
8705 if (NewParamInfos.back().getOpaqueValue())
8706 NeedParamInfo = true;
8707 if (FirstNoEscape != IsNoEscape)
8708 CanUseFirst = false;
8709 if (SecondNoEscape != IsNoEscape)
8710 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00008711 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00008712
8713 if (!NeedParamInfo)
8714 NewParamInfos.clear();
8715
Fariborz Jahanian97676972011-09-28 21:52:05 +00008716 return true;
8717}
8718
Chandler Carruth21c90602015-12-30 03:24:14 +00008719void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8720 ObjCLayouts[CD] = nullptr;
8721}
8722
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008723/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8724/// 'RHS' attributes and returns the merged version; including for function
8725/// return types.
8726QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8727 QualType LHSCan = getCanonicalType(LHS),
8728 RHSCan = getCanonicalType(RHS);
8729 // If two types are identical, they are compatible.
8730 if (LHSCan == RHSCan)
8731 return LHS;
8732 if (RHSCan->isFunctionType()) {
8733 if (!LHSCan->isFunctionType())
8734 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008735 QualType OldReturnType =
8736 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008737 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008738 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008739 QualType ResReturnType =
8740 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8741 if (ResReturnType.isNull())
8742 return QualType();
8743 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8744 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8745 // In either case, use OldReturnType to build the new function type.
8746 const FunctionType *F = LHS->getAs<FunctionType>();
8747 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008748 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8749 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008750 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008751 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008752 return ResultType;
8753 }
8754 }
8755 return QualType();
8756 }
8757
8758 // If the qualifiers are different, the types can still be merged.
8759 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8760 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8761 if (LQuals != RQuals) {
8762 // If any of these qualifiers are different, we have a type mismatch.
8763 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8764 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8765 return QualType();
8766
8767 // Exactly one GC qualifier difference is allowed: __strong is
8768 // okay if the other type has no GC qualifier but is an Objective
8769 // C object pointer (i.e. implicitly strong by default). We fix
8770 // this by pretending that the unqualified type was actually
8771 // qualified __strong.
8772 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8773 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8774 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8775
8776 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8777 return QualType();
8778
8779 if (GC_L == Qualifiers::Strong)
8780 return LHS;
8781 if (GC_R == Qualifiers::Strong)
8782 return RHS;
8783 return QualType();
8784 }
8785
8786 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8787 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8788 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8789 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8790 if (ResQT == LHSBaseQT)
8791 return LHS;
8792 if (ResQT == RHSBaseQT)
8793 return RHS;
8794 }
8795 return QualType();
8796}
8797
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008798//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008799// Integer Predicates
8800//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008801
Jay Foad39c79802011-01-12 09:06:06 +00008802unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008803 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008804 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008805 if (T->isBooleanType())
8806 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008807 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008808 return (unsigned)getTypeSize(T);
8809}
8810
Abramo Bagnara13640492012-09-09 10:21:24 +00008811QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008812 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008813
8814 // Turn <4 x signed int> -> <4 x unsigned int>
8815 if (const VectorType *VTy = T->getAs<VectorType>())
8816 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008817 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008818
8819 // For enums, we return the unsigned version of the base type.
8820 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008821 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008822
8823 const BuiltinType *BTy = T->getAs<BuiltinType>();
8824 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008825 switch (BTy->getKind()) {
8826 case BuiltinType::Char_S:
8827 case BuiltinType::SChar:
8828 return UnsignedCharTy;
8829 case BuiltinType::Short:
8830 return UnsignedShortTy;
8831 case BuiltinType::Int:
8832 return UnsignedIntTy;
8833 case BuiltinType::Long:
8834 return UnsignedLongTy;
8835 case BuiltinType::LongLong:
8836 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008837 case BuiltinType::Int128:
8838 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008839 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008840 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008841 }
8842}
8843
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008844ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008845
Richard Smith1fa5d642013-05-11 05:45:24 +00008846void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8847 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008848
8849//===----------------------------------------------------------------------===//
8850// Builtin Type Computation
8851//===----------------------------------------------------------------------===//
8852
8853/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008854/// pointer over the consumed characters. This returns the resultant type. If
8855/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8856/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8857/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008858///
8859/// RequiresICE is filled in on return to indicate whether the value is required
8860/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008861static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008862 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008863 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008864 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008865 // Modifiers.
8866 int HowLong = 0;
8867 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008868 RequiresICE = false;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008869
Chris Lattnerdc226c22010-10-01 22:42:38 +00008870 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00008871 bool Done = false;
8872 #ifndef NDEBUG
8873 bool IsSpecialLong = false;
8874 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00008875 while (!Done) {
8876 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008877 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008878 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008879 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008880 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008881 case 'S':
8882 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8883 assert(!Signed && "Can't use 'S' modifier multiple times!");
8884 Signed = true;
8885 break;
8886 case 'U':
8887 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008888 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008889 Unsigned = true;
8890 break;
8891 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008892 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008893 assert(HowLong <= 2 && "Can't have LLLL modifier");
8894 ++HowLong;
8895 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008896 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008897 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
8898 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
8899 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008900 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008901 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008902 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008903 if (Context.getTargetInfo().getLongWidth() == 32)
8904 ++HowLong;
8905 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008906 case 'W':
8907 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008908 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00008909 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008910 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008911 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008912 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00008913 switch (Context.getTargetInfo().getInt64Type()) {
8914 default:
8915 llvm_unreachable("Unexpected integer type");
8916 case TargetInfo::SignedLong:
8917 HowLong = 1;
8918 break;
8919 case TargetInfo::SignedLongLong:
8920 HowLong = 2;
8921 break;
8922 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00008923 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008924 }
8925 }
8926
8927 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008928
Chris Lattnerecd79c62009-06-14 00:45:47 +00008929 // Read the base type.
8930 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008931 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008932 case 'v':
8933 assert(HowLong == 0 && !Signed && !Unsigned &&
8934 "Bad modifiers used with 'v'!");
8935 Type = Context.VoidTy;
8936 break;
Jack Carter24bef982013-08-15 15:16:57 +00008937 case 'h':
8938 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008939 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008940 Type = Context.HalfTy;
8941 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008942 case 'f':
8943 assert(HowLong == 0 && !Signed && !Unsigned &&
8944 "Bad modifiers used with 'f'!");
8945 Type = Context.FloatTy;
8946 break;
8947 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00008948 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00008949 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00008950 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00008951 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00008952 else if (HowLong == 2)
8953 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008954 else
8955 Type = Context.DoubleTy;
8956 break;
8957 case 's':
8958 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8959 if (Unsigned)
8960 Type = Context.UnsignedShortTy;
8961 else
8962 Type = Context.ShortTy;
8963 break;
8964 case 'i':
8965 if (HowLong == 3)
8966 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8967 else if (HowLong == 2)
8968 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8969 else if (HowLong == 1)
8970 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8971 else
8972 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8973 break;
8974 case 'c':
8975 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8976 if (Signed)
8977 Type = Context.SignedCharTy;
8978 else if (Unsigned)
8979 Type = Context.UnsignedCharTy;
8980 else
8981 Type = Context.CharTy;
8982 break;
8983 case 'b': // boolean
8984 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8985 Type = Context.BoolTy;
8986 break;
8987 case 'z': // size_t.
8988 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8989 Type = Context.getSizeType();
8990 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00008991 case 'w': // wchar_t.
8992 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8993 Type = Context.getWideCharType();
8994 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008995 case 'F':
8996 Type = Context.getCFConstantStringType();
8997 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008998 case 'G':
8999 Type = Context.getObjCIdType();
9000 break;
9001 case 'H':
9002 Type = Context.getObjCSelType();
9003 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009004 case 'M':
9005 Type = Context.getObjCSuperType();
9006 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009007 case 'a':
9008 Type = Context.getBuiltinVaListType();
9009 assert(!Type.isNull() && "builtin va list type not initialized!");
9010 break;
9011 case 'A':
9012 // This is a "reference" to a va_list; however, what exactly
9013 // this means depends on how va_list is defined. There are two
9014 // different kinds of va_list: ones passed by value, and ones
9015 // passed by reference. An example of a by-value va_list is
9016 // x86, where va_list is a char*. An example of by-ref va_list
9017 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9018 // we want this argument to be a char*&; for x86-64, we want
9019 // it to be a __va_list_tag*.
9020 Type = Context.getBuiltinVaListType();
9021 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009022 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009023 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009024 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009025 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009026 break;
9027 case 'V': {
9028 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009029 unsigned NumElements = strtoul(Str, &End, 10);
9030 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009031 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009032
Chandler Carruth45bbe012017-03-24 09:11:57 +00009033 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
9034 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009035 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00009036
9037 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009038 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009039 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009040 break;
9041 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009042 case 'E': {
9043 char *End;
9044
9045 unsigned NumElements = strtoul(Str, &End, 10);
9046 assert(End != Str && "Missing vector size");
9047
9048 Str = End;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009049
Douglas Gregorfed66992012-06-07 18:08:25 +00009050 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009051 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009052 Type = Context.getExtVectorType(ElementType, NumElements);
9053 break;
9054 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009055 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009056 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009057 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009058 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009059 Type = Context.getComplexType(ElementType);
9060 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009061 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009062 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009063 Type = Context.getPointerDiffType();
9064 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009065 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009066 Type = Context.getFILEType();
9067 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009068 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009069 return QualType();
9070 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009071 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009072 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009073 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009074 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009075 else
9076 Type = Context.getjmp_bufType();
9077
Mike Stump2adb4da2009-07-28 23:47:15 +00009078 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009079 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00009080 return QualType();
9081 }
9082 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009083 case 'K':
9084 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9085 Type = Context.getucontext_tType();
9086
9087 if (Type.isNull()) {
9088 Error = ASTContext::GE_Missing_ucontext;
9089 return QualType();
9090 }
9091 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009092 case 'p':
9093 Type = Context.getProcessIDType();
9094 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009095 }
Mike Stump11289f42009-09-09 15:08:12 +00009096
Chris Lattnerdc226c22010-10-01 22:42:38 +00009097 // If there are modifiers and if we're allowed to parse them, go for it.
9098 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009099 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009100 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009101 default: Done = true; --Str; break;
9102 case '*':
9103 case '&': {
9104 // Both pointers and references can have their pointee types
9105 // qualified with an address space.
9106 char *End;
9107 unsigned AddrSpace = strtoul(Str, &End, 10);
9108 if (End != Str && AddrSpace != 0) {
Alexander Richardson6d989432017-10-15 18:48:14 +00009109 Type = Context.getAddrSpaceQualType(Type,
9110 getLangASFromTargetAS(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009111 Str = End;
9112 }
9113 if (c == '*')
9114 Type = Context.getPointerType(Type);
9115 else
9116 Type = Context.getLValueReferenceType(Type);
9117 break;
9118 }
9119 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9120 case 'C':
9121 Type = Type.withConst();
9122 break;
9123 case 'D':
9124 Type = Context.getVolatileType(Type);
9125 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009126 case 'R':
9127 Type = Type.withRestrict();
9128 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009129 }
9130 }
Chris Lattner84733392010-10-01 07:13:18 +00009131
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009132 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00009133 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009134
Chris Lattnerecd79c62009-06-14 00:45:47 +00009135 return Type;
9136}
9137
9138/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009139QualType ASTContext::GetBuiltinType(unsigned Id,
9140 GetBuiltinTypeError &Error,
9141 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009142 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00009143
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009144 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009145
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009146 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009147 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009148 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9149 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009150 if (Error != GE_None)
9151 return QualType();
Chandler Carruth45bbe012017-03-24 09:11:57 +00009152
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009153 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Chandler Carruth45bbe012017-03-24 09:11:57 +00009154
Chris Lattnerecd79c62009-06-14 00:45:47 +00009155 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009156 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009157 if (Error != GE_None)
9158 return QualType();
9159
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009160 // If this argument is required to be an IntegerConstantExpression and the
9161 // caller cares, fill in the bitmask we return.
9162 if (RequiresICE && IntegerConstantArgs)
9163 *IntegerConstantArgs |= 1 << ArgTypes.size();
9164
Chris Lattnerecd79c62009-06-14 00:45:47 +00009165 // Do array -> pointer decay. The builtin should use the decayed type.
9166 if (Ty->isArrayType())
9167 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009168
Chris Lattnerecd79c62009-06-14 00:45:47 +00009169 ArgTypes.push_back(Ty);
9170 }
9171
David Majnemerba3e5ec2015-03-13 18:26:17 +00009172 if (Id == Builtin::BI__GetExceptionInfo)
9173 return QualType();
9174
Chris Lattnerecd79c62009-06-14 00:45:47 +00009175 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9176 "'.' should only occur at end of builtin type list!");
9177
Reid Kleckner78af0702013-08-27 23:08:25 +00009178 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00009179 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9180
9181 bool Variadic = (TypeStr[0] == '.');
9182
Richard Smith836de6b2016-12-19 23:59:34 +00009183 // We really shouldn't be making a no-proto type here.
9184 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009185 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009186
John McCalldb40c7f2010-12-14 08:05:40 +00009187 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009188 EPI.ExtInfo = EI;
9189 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009190 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9191 EPI.ExceptionSpec.Type =
9192 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009193
Jordan Rose5c382722013-03-08 21:51:21 +00009194 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009195}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009196
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009197static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9198 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009199 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009200 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009201
Richard Smithe2467b72017-11-16 23:54:56 +00009202 // Non-user-provided functions get emitted as weak definitions with every
9203 // use, no matter whether they've been explicitly instantiated etc.
9204 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
9205 if (!MD->isUserProvided())
9206 return GVA_DiscardableODR;
9207
Yaron Keren4cd211b2017-02-22 14:32:39 +00009208 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009209 switch (FD->getTemplateSpecializationKind()) {
9210 case TSK_Undeclared:
9211 case TSK_ExplicitSpecialization:
9212 External = GVA_StrongExternal;
9213 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009214
Rafael Espindola3ae00052013-05-13 00:12:11 +00009215 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009216 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009217
David Majnemerc3d07332014-05-15 06:25:57 +00009218 // C++11 [temp.explicit]p10:
9219 // [ Note: The intent is that an inline function that is the subject of
9220 // an explicit instantiation declaration will still be implicitly
9221 // instantiated when used so that the body can be considered for
9222 // inlining, but that no out-of-line copy of the inline function would be
9223 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009224 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009225 return GVA_AvailableExternally;
9226
Rafael Espindola3ae00052013-05-13 00:12:11 +00009227 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009228 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009229 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009230 }
9231
9232 if (!FD->isInlined())
9233 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009234
David Majnemer3f021502015-10-08 04:53:31 +00009235 if ((!Context.getLangOpts().CPlusPlus &&
9236 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009237 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009238 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009239 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9240
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009241 // GNU or C99 inline semantics. Determine whether this symbol should be
9242 // externally visible.
9243 if (FD->isInlineDefinitionExternallyVisible())
9244 return External;
9245
9246 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009247 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009248 }
9249
David Majnemer54e3ba52014-04-02 23:17:29 +00009250 // Functions specified with extern and inline in -fms-compatibility mode
9251 // forcibly get emitted. While the body of the function cannot be later
9252 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009253 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009254 return GVA_StrongODR;
9255
David Majnemer27d69db2014-04-28 22:17:59 +00009256 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009257}
9258
Artem Belevichca2b9512016-05-02 20:30:03 +00009259static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009260 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009261 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9262 // dllexport/dllimport on inline functions.
9263 if (D->hasAttr<DLLImportAttr>()) {
9264 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9265 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009266 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009267 if (L == GVA_DiscardableODR)
9268 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009269 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9270 D->hasAttr<CUDAGlobalAttr>()) {
9271 // Device-side functions with __global__ attribute must always be
9272 // visible externally so they can be launched from host.
9273 if (L == GVA_DiscardableODR || L == GVA_Internal)
9274 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009275 }
9276 return L;
9277}
9278
Richard Smitha4653622017-09-06 20:01:14 +00009279/// Adjust the GVALinkage for a declaration based on what an external AST source
9280/// knows about whether there can be other definitions of this declaration.
9281static GVALinkage
9282adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9283 GVALinkage L) {
9284 ExternalASTSource *Source = Ctx.getExternalSource();
9285 if (!Source)
9286 return L;
9287
9288 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009289 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009290 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009291 if (L == GVA_DiscardableODR)
9292 return GVA_StrongODR;
9293 break;
Richard Smitha4653622017-09-06 20:01:14 +00009294
David Blaikie9ffe5a32017-01-30 05:00:26 +00009295 case ExternalASTSource::EK_Always:
9296 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009297
David Blaikie9ffe5a32017-01-30 05:00:26 +00009298 case ExternalASTSource::EK_ReplyHazy:
9299 break;
9300 }
9301 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009302}
9303
Richard Smitha4653622017-09-06 20:01:14 +00009304GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9305 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9306 adjustGVALinkageForAttributes(*this, FD,
9307 basicGVALinkageForFunction(*this, FD)));
9308}
9309
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009310static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9311 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009312 if (!VD->isExternallyVisible())
9313 return GVA_Internal;
9314
David Majnemer27d69db2014-04-28 22:17:59 +00009315 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009316 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9317 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9318 LexicalContext = LexicalContext->getLexicalParent();
9319
David Blaikieeb210012017-01-27 23:11:10 +00009320 // ObjC Blocks can create local variables that don't have a FunctionDecl
9321 // LexicalContext.
9322 if (!LexicalContext)
9323 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009324
David Blaikieeb210012017-01-27 23:11:10 +00009325 // Otherwise, let the static local variable inherit its linkage from the
9326 // nearest enclosing function.
9327 auto StaticLocalLinkage =
9328 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9329
9330 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9331 // be emitted in any object with references to the symbol for the object it
9332 // contains, whether inline or out-of-line."
9333 // Similar behavior is observed with MSVC. An alternative ABI could use
9334 // StrongODR/AvailableExternally to match the function, but none are
9335 // known/supported currently.
9336 if (StaticLocalLinkage == GVA_StrongODR ||
9337 StaticLocalLinkage == GVA_AvailableExternally)
9338 return GVA_DiscardableODR;
9339 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009340 }
9341
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009342 // MSVC treats in-class initialized static data members as definitions.
9343 // By giving them non-strong linkage, out-of-line definitions won't
9344 // cause link errors.
9345 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9346 return GVA_DiscardableODR;
9347
Richard Smithd9b90092016-07-02 01:32:16 +00009348 // Most non-template variables have strong linkage; inline variables are
9349 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9350 GVALinkage StrongLinkage;
9351 switch (Context.getInlineVariableDefinitionKind(VD)) {
9352 case ASTContext::InlineVariableDefinitionKind::None:
9353 StrongLinkage = GVA_StrongExternal;
9354 break;
9355 case ASTContext::InlineVariableDefinitionKind::Weak:
9356 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009357 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009358 break;
9359 case ASTContext::InlineVariableDefinitionKind::Strong:
9360 StrongLinkage = GVA_StrongODR;
9361 break;
9362 }
Richard Smith62f19e72016-06-25 00:15:56 +00009363
Richard Smith8809a0c2013-09-27 20:14:12 +00009364 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009365 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009366 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009367
David Majnemer6d1780c2015-07-17 23:36:49 +00009368 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00009369 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9370 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00009371 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00009372 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009373
Rafael Espindola3ae00052013-05-13 00:12:11 +00009374 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009375 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009376
David Majnemer27d69db2014-04-28 22:17:59 +00009377 case TSK_ExplicitInstantiationDeclaration:
9378 return GVA_AvailableExternally;
9379
Rafael Espindola3ae00052013-05-13 00:12:11 +00009380 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009381 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009382 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009383
9384 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009385}
9386
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009387GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009388 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9389 adjustGVALinkageForAttributes(*this, VD,
9390 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009391}
9392
David Blaikiee6b7c282017-04-11 20:46:34 +00009393bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009394 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9395 if (!VD->isFileVarDecl())
9396 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009397 // Global named register variables (GNU extension) are never emitted.
9398 if (VD->getStorageClass() == SC_Register)
9399 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009400 if (VD->getDescribedVarTemplate() ||
9401 isa<VarTemplatePartialSpecializationDecl>(VD))
9402 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00009403 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9404 // We never need to emit an uninstantiated function template.
9405 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9406 return false;
Nico Weber66220292016-03-02 17:28:48 +00009407 } else if (isa<PragmaCommentDecl>(D))
9408 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009409 else if (isa<OMPThreadPrivateDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009410 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009411 else if (isa<PragmaDetectMismatchDecl>(D))
9412 return true;
Nico Weber66220292016-03-02 17:28:48 +00009413 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009414 return !D->getDeclContext()->isDependentContext();
9415 else if (isa<OMPDeclareReductionDecl>(D))
9416 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009417 else if (isa<ImportDecl>(D))
9418 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009419 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009420 return false;
9421
9422 // If this is a member of a class template, we do not need to emit it.
9423 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009424 return false;
9425
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009426 // Weak references don't produce any output by themselves.
9427 if (D->hasAttr<WeakRefAttr>())
9428 return false;
9429
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009430 // Aliases and used decls are required.
9431 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9432 return true;
9433
9434 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9435 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009436 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009437 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009438
9439 // Constructors and destructors are required.
9440 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9441 return true;
9442
John McCall6bd2a892013-01-25 22:31:03 +00009443 // The key function for a class is required. This rule only comes
9444 // into play when inline functions can be key functions, though.
9445 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
9446 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9447 const CXXRecordDecl *RD = MD->getParent();
9448 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9449 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9450 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9451 return true;
9452 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009453 }
9454 }
9455
David Blaikie9ffe5a32017-01-30 05:00:26 +00009456 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9457
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009458 // static, static inline, always_inline, and extern inline functions can
9459 // always be deferred. Normal inline functions can be deferred in C99/C++.
9460 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009461 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009462 }
Douglas Gregor87d81242011-09-10 00:22:34 +00009463
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009464 const VarDecl *VD = cast<VarDecl>(D);
9465 assert(VD->isFileVarDecl() && "Expected file scoped var");
9466
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009467 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9468 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009469 return false;
9470
Richard Smitha0e5e542012-11-12 21:38:00 +00009471 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009472 auto Linkage = GetGVALinkageForVariable(VD);
9473 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009474 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009475
Richard Smitha4653622017-09-06 20:01:14 +00009476 // We never need to emit a variable that is available in another TU.
9477 if (Linkage == GVA_AvailableExternally)
9478 return false;
9479
Richard Smitha0e5e542012-11-12 21:38:00 +00009480 // Variables that have destruction with side-effects are required.
9481 if (VD->getType().isDestructedType())
9482 return true;
9483
9484 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009485 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009486 // We can get a value-dependent initializer during error recovery.
9487 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009488 return true;
9489
Richard Smithda383632016-08-15 01:33:41 +00009490 // Likewise, variables with tuple-like bindings are required if their
9491 // bindings have side-effects.
9492 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
9493 for (auto *BD : DD->bindings())
9494 if (auto *BindingVD = BD->getHoldingVar())
9495 if (DeclMustBeEmitted(BindingVD))
9496 return true;
9497
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009498 // If the decl is marked as `declare target`, it should be emitted.
Alexey Bataev92327c52018-03-26 16:40:55 +00009499 for (const auto *Decl : D->redecls()) {
9500 if (!Decl->hasAttrs())
9501 continue;
9502 if (const auto *Attr = Decl->getAttr<OMPDeclareTargetDeclAttr>())
9503 if (Attr->getMapType() != OMPDeclareTargetDeclAttr::MT_Link)
9504 return true;
9505 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009506
Richard Smitha0e5e542012-11-12 21:38:00 +00009507 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009508}
Charles Davis53c59df2010-08-16 03:33:14 +00009509
Erich Keane281d20b2018-01-08 21:34:17 +00009510void ASTContext::forEachMultiversionedFunctionVersion(
9511 const FunctionDecl *FD,
9512 llvm::function_ref<void(const FunctionDecl *)> Pred) const {
9513 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
9514 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
9515 FD = FD->getCanonicalDecl();
9516 for (auto *CurDecl :
9517 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
9518 FunctionDecl *CurFD = CurDecl->getAsFunction()->getCanonicalDecl();
9519 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
9520 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
9521 SeenDecls.insert(CurFD);
9522 Pred(CurFD);
9523 }
9524 }
9525}
9526
Reid Kleckner78af0702013-08-27 23:08:25 +00009527CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9528 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009529 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009530 if (IsCXXMethod)
9531 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009532
Alexey Bataeva7547182016-05-18 09:06:38 +00009533 switch (LangOpts.getDefaultCallingConv()) {
9534 case LangOptions::DCC_None:
9535 break;
9536 case LangOptions::DCC_CDecl:
9537 return CC_C;
9538 case LangOptions::DCC_FastCall:
Erich Keane5759fa72017-10-24 23:12:01 +00009539 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
Alexey Bataeva7547182016-05-18 09:06:38 +00009540 return CC_X86FastCall;
9541 break;
9542 case LangOptions::DCC_StdCall:
9543 if (!IsVariadic)
9544 return CC_X86StdCall;
9545 break;
9546 case LangOptions::DCC_VectorCall:
9547 // __vectorcall cannot be applied to variadic functions.
9548 if (!IsVariadic)
9549 return CC_X86VectorCall;
9550 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00009551 case LangOptions::DCC_RegCall:
9552 // __regcall cannot be applied to variadic functions.
9553 if (!IsVariadic)
9554 return CC_X86RegCall;
9555 break;
Alexey Bataeva7547182016-05-18 09:06:38 +00009556 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009557 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009558}
9559
Jay Foad39c79802011-01-12 09:06:06 +00009560bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009561 // Pass through to the C++ ABI object
9562 return ABI->isNearlyEmpty(RD);
9563}
9564
Reid Kleckner96f8f932014-02-05 17:27:08 +00009565VTableContextBase *ASTContext::getVTableContext() {
9566 if (!VTContext.get()) {
9567 if (Target->getCXXABI().isMicrosoft())
9568 VTContext.reset(new MicrosoftVTableContext(*this));
9569 else
9570 VTContext.reset(new ItaniumVTableContext(*this));
9571 }
9572 return VTContext.get();
9573}
9574
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009575MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009576 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009577 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009578 case TargetCXXABI::GenericItanium:
9579 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009580 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009581 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009582 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009583 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009584 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009585 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009586 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009587 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009588 }
David Blaikie83d382b2011-09-23 05:06:16 +00009589 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009590}
9591
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009592CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009593
9594size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009595 return ASTRecordLayouts.getMemorySize() +
9596 llvm::capacity_in_bytes(ObjCLayouts) +
9597 llvm::capacity_in_bytes(KeyFunctions) +
9598 llvm::capacity_in_bytes(ObjCImpls) +
9599 llvm::capacity_in_bytes(BlockVarCopyInits) +
9600 llvm::capacity_in_bytes(DeclAttrs) +
9601 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9602 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9603 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9604 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9605 llvm::capacity_in_bytes(OverriddenMethods) +
9606 llvm::capacity_in_bytes(Types) +
9607 llvm::capacity_in_bytes(VariableArrayTypes) +
9608 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009609}
Ted Kremenek540017e2011-10-06 05:00:56 +00009610
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009611/// getIntTypeForBitwidth -
9612/// sets integer QualTy according to specified details:
9613/// bitwidth, signed/unsigned.
9614/// Returns empty type if there is no appropriate target types.
9615QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9616 unsigned Signed) const {
9617 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9618 CanQualType QualTy = getFromTargetType(Ty);
9619 if (!QualTy && DestWidth == 128)
9620 return Signed ? Int128Ty : UnsignedInt128Ty;
9621 return QualTy;
9622}
9623
9624/// getRealTypeForBitwidth -
9625/// sets floating point QualTy according to specified bitwidth.
9626/// Returns empty type if there is no appropriate target types.
9627QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9628 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9629 switch (Ty) {
9630 case TargetInfo::Float:
9631 return FloatTy;
9632 case TargetInfo::Double:
9633 return DoubleTy;
9634 case TargetInfo::LongDouble:
9635 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009636 case TargetInfo::Float128:
9637 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009638 case TargetInfo::NoFloat:
9639 return QualType();
9640 }
9641
9642 llvm_unreachable("Unhandled TargetInfo::RealType value");
9643}
9644
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009645void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9646 if (Number > 1)
9647 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009648}
9649
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009650unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009651 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009652 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009653}
9654
David Majnemer2206bf52014-03-05 08:57:59 +00009655void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9656 if (Number > 1)
9657 StaticLocalNumbers[VD] = Number;
9658}
9659
9660unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009661 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009662 return I != StaticLocalNumbers.end() ? I->second : 1;
9663}
9664
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009665MangleNumberingContext &
9666ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009667 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009668 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009669 if (!MCtx)
9670 MCtx = createMangleNumberingContext();
9671 return *MCtx;
9672}
9673
Justin Lebar20ebffc2016-10-10 16:26:19 +00009674std::unique_ptr<MangleNumberingContext>
9675ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009676 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009677}
9678
David Majnemere7a818f2015-03-06 18:53:55 +00009679const CXXConstructorDecl *
9680ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9681 return ABI->getCopyConstructorForExceptionObject(
9682 cast<CXXRecordDecl>(RD->getFirstDecl()));
9683}
9684
9685void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9686 CXXConstructorDecl *CD) {
9687 return ABI->addCopyConstructorForExceptionObject(
9688 cast<CXXRecordDecl>(RD->getFirstDecl()),
9689 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9690}
9691
David Majnemer00350522015-08-31 18:48:39 +00009692void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9693 TypedefNameDecl *DD) {
9694 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9695}
9696
9697TypedefNameDecl *
9698ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9699 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9700}
9701
9702void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9703 DeclaratorDecl *DD) {
9704 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9705}
9706
9707DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9708 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9709}
9710
Ted Kremenek540017e2011-10-06 05:00:56 +00009711void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9712 ParamIndices[D] = index;
9713}
9714
9715unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9716 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9717 assert(I != ParamIndices.end() &&
9718 "ParmIndices lacks entry set by ParmVarDecl");
9719 return I->second;
9720}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009721
Richard Smithe6c01442013-06-05 00:46:14 +00009722APValue *
9723ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9724 bool MayCreate) {
9725 assert(E && E->getStorageDuration() == SD_Static &&
9726 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009727 if (MayCreate) {
9728 APValue *&MTVI = MaterializedTemporaryValues[E];
9729 if (!MTVI)
9730 MTVI = new (*this) APValue;
9731 return MTVI;
9732 }
Richard Smithe6c01442013-06-05 00:46:14 +00009733
David Majnemer2dcef9e2015-08-13 23:50:15 +00009734 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009735}
9736
Fariborz Jahanian615de762013-05-28 17:37:39 +00009737bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9738 const llvm::Triple &T = getTargetInfo().getTriple();
9739 if (!T.isOSDarwin())
9740 return false;
9741
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009742 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9743 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9744 return false;
9745
Fariborz Jahanian615de762013-05-28 17:37:39 +00009746 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9747 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9748 uint64_t Size = sizeChars.getQuantity();
9749 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9750 unsigned Align = alignChars.getQuantity();
9751 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9752 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9753}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009754
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009755static ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009756 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009757 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009758 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009759 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009760 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009761 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009762}
9763
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009764namespace {
9765
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009766/// Template specializations to abstract away from pointers and TypeLocs.
9767/// @{
9768template <typename T>
9769ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9770 return ast_type_traits::DynTypedNode::create(*Node);
9771}
9772template <>
9773ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9774 return ast_type_traits::DynTypedNode::create(Node);
9775}
9776template <>
9777ast_type_traits::DynTypedNode
9778createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9779 return ast_type_traits::DynTypedNode::create(Node);
9780}
9781/// @}
9782
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009783 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9784 /// parents as defined by the \c RecursiveASTVisitor.
9785 ///
9786 /// Note that the relationship described here is purely in terms of AST
9787 /// traversal - there are other relationships (for example declaration context)
9788 /// in the AST that are better modeled by special matchers.
9789 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009790 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009791 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009792 public:
9793 /// \brief Builds and returns the translation unit's parent map.
9794 ///
9795 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009796 static std::pair<ASTContext::ParentMapPointers *,
9797 ASTContext::ParentMapOtherNodes *>
9798 buildMap(TranslationUnitDecl &TU) {
9799 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9800 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009801 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009802 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009803 }
9804
9805 private:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009806 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9807
9808 using VisitorBase = RecursiveASTVisitor<ParentMapASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009809
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009810 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9811 ASTContext::ParentMapOtherNodes *OtherParents)
9812 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009813
9814 bool shouldVisitTemplateInstantiations() const {
9815 return true;
9816 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009817
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009818 bool shouldVisitImplicitCode() const {
9819 return true;
9820 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009821
Richard Smith85838722015-11-24 03:09:01 +00009822 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9823 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009824 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009825 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009826 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009827 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009828 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009829 // FIXME: Currently we add the same parent multiple times, but only
9830 // when no memoization data is available for the type.
9831 // For example when we visit all subexpressions of template
9832 // instantiations; this is suboptimal, but benign: the only way to
9833 // visit those is with hasAncestor / hasParent, and those do not create
9834 // new matches.
9835 // The plan is to enable DynTypedNode to be storable in a map or hash
9836 // map. The main problem there is to implement hash functions /
9837 // comparison operators for all types that DynTypedNode supports that
9838 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009839 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009840 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009841 if (const auto *D = ParentStack.back().get<Decl>())
9842 NodeOrVector = D;
9843 else if (const auto *S = ParentStack.back().get<Stmt>())
9844 NodeOrVector = S;
9845 else
9846 NodeOrVector =
9847 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009848 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009849 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9850 auto *Vector = new ASTContext::ParentVector(
9851 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Gabor Horvath10a837a2017-04-19 15:11:10 +00009852 delete NodeOrVector
9853 .template dyn_cast<ast_type_traits::DynTypedNode *>();
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009854 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009855 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009856
9857 auto *Vector =
9858 NodeOrVector.template get<ASTContext::ParentVector *>();
9859 // Skip duplicates for types that have memoization data.
9860 // We must check that the type has memoization data before calling
9861 // std::find() because DynTypedNode::operator== can't compare all
9862 // types.
9863 bool Found = ParentStack.back().getMemoizationData() &&
9864 std::find(Vector->begin(), Vector->end(),
9865 ParentStack.back()) != Vector->end();
9866 if (!Found)
9867 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009868 }
9869 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009870 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009871 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009872 ParentStack.pop_back();
9873 return Result;
9874 }
9875
9876 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009877 return TraverseNode(DeclNode, DeclNode,
9878 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009879 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009880 }
9881
9882 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009883 return TraverseNode(StmtNode, StmtNode,
9884 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009885 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009886 }
9887
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009888 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009889 return TraverseNode(
9890 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9891 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9892 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009893 }
9894
9895 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9896 return TraverseNode(
9897 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009898 [&] {
9899 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9900 },
9901 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009902 }
9903
9904 ASTContext::ParentMapPointers *Parents;
9905 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009906 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009907 };
9908
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009909} // namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009910
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009911template <typename NodeTy, typename MapTy>
9912static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9913 const MapTy &Map) {
9914 auto I = Map.find(Node);
9915 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009916 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009917 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009918 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009919 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009920 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009921 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009922}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009923
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009924ASTContext::DynTypedNodeList
9925ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9926 if (!PointerParents) {
9927 // We always need to run over the whole translation unit, as
9928 // hasAncestor can escape any subtree.
9929 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9930 PointerParents.reset(Maps.first);
9931 OtherParents.reset(Maps.second);
9932 }
9933 if (Node.getNodeKind().hasPointerIdentity())
9934 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9935 return getDynNodeFromMap(Node, *OtherParents);
9936}
9937
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009938bool
9939ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9940 const ObjCMethodDecl *MethodImpl) {
9941 // No point trying to match an unavailable/deprecated mothod.
9942 if (MethodDecl->hasAttr<UnavailableAttr>()
9943 || MethodDecl->hasAttr<DeprecatedAttr>())
9944 return false;
9945 if (MethodDecl->getObjCDeclQualifier() !=
9946 MethodImpl->getObjCDeclQualifier())
9947 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009948 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009949 return false;
9950
9951 if (MethodDecl->param_size() != MethodImpl->param_size())
9952 return false;
9953
9954 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9955 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9956 EF = MethodDecl->param_end();
9957 IM != EM && IF != EF; ++IM, ++IF) {
9958 const ParmVarDecl *DeclVar = (*IF);
9959 const ParmVarDecl *ImplVar = (*IM);
9960 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9961 return false;
9962 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9963 return false;
9964 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009965
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009966 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009967}
Richard Smith053f6c62014-05-16 23:01:30 +00009968
Yaxun Liu402804b2016-12-15 08:09:08 +00009969uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +00009970 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +00009971 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +00009972 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +00009973 else
9974 AS = QT->getPointeeType().getAddressSpace();
9975
9976 return getTargetInfo().getNullPointerValue(AS);
9977}
9978
Alexander Richardson6d989432017-10-15 18:48:14 +00009979unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
9980 if (isTargetAddressSpace(AS))
9981 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +00009982 else
Alexander Richardson6d989432017-10-15 18:48:14 +00009983 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +00009984}
9985
Richard Smith053f6c62014-05-16 23:01:30 +00009986// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9987// doesn't include ASTContext.h
9988template
9989clang::LazyGenerationalUpdatePtr<
9990 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9991clang::LazyGenerationalUpdatePtr<
9992 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9993 const clang::ASTContext &Ctx, Decl *Value);