blob: db8e74ec94cd74ccf14b1163fdfdafd65be0f658 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerddc135e2006-11-10 06:34:16 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the ASTContext interface.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "CXXABI.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000015#include "clang/AST/APValue.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000017#include "clang/AST/ASTTypeTraits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/Attr.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000019#include "clang/AST/AttrIterator.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000020#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/AST/Comment.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000022#include "clang/AST/Decl.h"
23#include "clang/AST/DeclBase.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000024#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000025#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000026#include "clang/AST/DeclObjC.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000027#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000028#include "clang/AST/DeclTemplate.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000029#include "clang/AST/DeclarationName.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000030#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000031#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000032#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000033#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000034#include "clang/AST/MangleNumberingContext.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000035#include "clang/AST/NestedNameSpecifier.h"
36#include "clang/AST/RawCommentList.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000037#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000038#include "clang/AST/RecursiveASTVisitor.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000039#include "clang/AST/Stmt.h"
40#include "clang/AST/TemplateBase.h"
41#include "clang/AST/TemplateName.h"
42#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000043#include "clang/AST/TypeLoc.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000044#include "clang/AST/UnresolvedSet.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000045#include "clang/AST/VTableBuilder.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000046#include "clang/Basic/AddressSpaces.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000047#include "clang/Basic/Builtins.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000048#include "clang/Basic/CommentOptions.h"
Eugene Zelenko7855e772018-04-03 00:11:50 +000049#include "clang/Basic/ExceptionSpecificationType.h"
Leonard Chana6779422018-08-06 16:42:37 +000050#include "clang/Basic/FixedPoint.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000051#include "clang/Basic/IdentifierTable.h"
52#include "clang/Basic/LLVM.h"
53#include "clang/Basic/LangOptions.h"
54#include "clang/Basic/Linkage.h"
55#include "clang/Basic/ObjCRuntime.h"
56#include "clang/Basic/SanitizerBlacklist.h"
57#include "clang/Basic/SourceLocation.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000058#include "clang/Basic/SourceManager.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000059#include "clang/Basic/Specifiers.h"
60#include "clang/Basic/TargetCXXABI.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000061#include "clang/Basic/TargetInfo.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000062#include "clang/Basic/XRayLists.h"
63#include "llvm/ADT/APInt.h"
64#include "llvm/ADT/APSInt.h"
65#include "llvm/ADT/ArrayRef.h"
66#include "llvm/ADT/DenseMap.h"
67#include "llvm/ADT/DenseSet.h"
68#include "llvm/ADT/FoldingSet.h"
69#include "llvm/ADT/None.h"
70#include "llvm/ADT/Optional.h"
71#include "llvm/ADT/PointerUnion.h"
72#include "llvm/ADT/STLExtras.h"
73#include "llvm/ADT/SmallPtrSet.h"
74#include "llvm/ADT/SmallVector.h"
Anders Carlssond8499822007-10-29 05:01:08 +000075#include "llvm/ADT/StringExtras.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000076#include "llvm/ADT/StringRef.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000077#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000078#include "llvm/Support/Capacity.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000079#include "llvm/Support/Casting.h"
80#include "llvm/Support/Compiler.h"
81#include "llvm/Support/ErrorHandling.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000082#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000083#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000084#include <algorithm>
85#include <cassert>
86#include <cstddef>
87#include <cstdint>
88#include <cstdlib>
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000089#include <map>
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000090#include <memory>
91#include <string>
92#include <tuple>
93#include <utility>
Anders Carlssona4267a62009-07-18 21:19:52 +000094
Chris Lattnerddc135e2006-11-10 06:34:16 +000095using namespace clang;
96
Steve Naroff0af91202007-04-27 21:51:21 +000097enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +000098 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +000099};
100
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000101RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000102 assert(D);
103
Jan Korous6644d012019-04-10 20:23:33 +0000104 // If we already tried to load comments but there are none,
105 // we won't find anything.
106 if (CommentsLoaded && Comments.getComments().empty())
107 return nullptr;
108
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000109 // User can not attach documentation to implicit declarations.
110 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +0000111 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000112
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000113 // User can not attach documentation to implicit instantiations.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000114 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000115 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000116 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000117 }
118
Eugene Zelenko7855e772018-04-03 00:11:50 +0000119 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000120 if (VD->isStaticDataMember() &&
121 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000122 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000123 }
124
Eugene Zelenko7855e772018-04-03 00:11:50 +0000125 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000126 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000127 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000128 }
129
Eugene Zelenko7855e772018-04-03 00:11:50 +0000130 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000131 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
132 if (TSK == TSK_ImplicitInstantiation ||
133 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000134 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000135 }
136
Eugene Zelenko7855e772018-04-03 00:11:50 +0000137 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000138 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000139 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000140 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000141 if (const auto *TD = dyn_cast<TagDecl>(D)) {
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000142 // When tag declaration (but not definition!) is part of the
143 // decl-specifier-seq of some other declaration, it doesn't get comment
144 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000145 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000146 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000147 // TODO: handle comments for function parameters properly.
148 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000149 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000150
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000151 // TODO: we could look up template parameter documentation in the template
152 // documentation.
153 if (isa<TemplateTypeParmDecl>(D) ||
154 isa<NonTypeTemplateParmDecl>(D) ||
155 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000156 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000157
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000158 // Find declaration location.
159 // For Objective-C declarations we generally don't expect to have multiple
160 // declarators, thus use declaration starting location as the "declaration
161 // location".
162 // For all other declarations multiple declarators are used quite frequently,
163 // so we use the location of the identifier as the "declaration location".
164 SourceLocation DeclLoc;
165 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000166 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000167 isa<RedeclarableTemplateDecl>(D) ||
168 isa<ClassTemplateSpecializationDecl>(D))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000169 DeclLoc = D->getBeginLoc();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000170 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000171 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000172 if (DeclLoc.isMacroID()) {
173 if (isa<TypedefDecl>(D)) {
174 // If location of the typedef name is in a macro, it is because being
175 // declared via a macro. Try using declaration's starting location as
176 // the "declaration location".
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000177 DeclLoc = D->getBeginLoc();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000178 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000179 // If location of the tag decl is inside a macro, but the spelling of
180 // the tag name comes from a macro argument, it looks like a special
181 // macro like NS_ENUM is being used to define the tag decl. In that
182 // case, adjust the source location to the expansion loc so that we can
183 // attach the comment to the tag decl.
184 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
185 TD->isCompleteDefinition())
186 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
187 }
188 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000189 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000190
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000191 // If the declaration doesn't map directly to a location in a file, we
192 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000193 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000194 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000195
Jan Korous6644d012019-04-10 20:23:33 +0000196 if (!CommentsLoaded && ExternalSource) {
197 ExternalSource->ReadComments();
198
199#ifndef NDEBUG
200 ArrayRef<RawComment *> RawComments = Comments.getComments();
201 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
202 BeforeThanCompare<RawComment>(SourceMgr)));
203#endif
204
205 CommentsLoaded = true;
206 }
207
208 ArrayRef<RawComment *> RawComments = Comments.getComments();
209 // If there are no comments anywhere, we won't find anything.
210 if (RawComments.empty())
211 return nullptr;
212
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000213 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000214 ArrayRef<RawComment *>::iterator Comment;
215 {
216 // When searching for comments during parsing, the comment we are looking
217 // for is usually among the last two comments we parsed -- check them
218 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000219 RawComment CommentAtDeclLoc(
David L. Jones13d5a872018-03-02 00:07:45 +0000220 SourceMgr, SourceRange(DeclLoc), LangOpts.CommentOpts, false);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000221 BeforeThanCompare<RawComment> Compare(SourceMgr);
222 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
223 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
224 if (!Found && RawComments.size() >= 2) {
225 MaybeBeforeDecl--;
226 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
227 }
228
229 if (Found) {
230 Comment = MaybeBeforeDecl + 1;
231 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
232 &CommentAtDeclLoc, Compare));
233 } else {
234 // Slow path.
235 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
236 &CommentAtDeclLoc, Compare);
237 }
238 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Decompose the location for the declaration and find the beginning of the
241 // file buffer.
242 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
243
244 // First check whether we have a trailing comment.
245 if (Comment != RawComments.end() &&
David L. Jones13d5a872018-03-02 00:07:45 +0000246 ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
247 && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000248 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000249 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000250 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000251 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000252 // Check that Doxygen trailing comment comes after the declaration, starts
253 // on the same line and in the same file as the declaration.
254 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
255 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
256 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
257 CommentBeginDecomp.second)) {
Jan Korous1652d812019-05-13 17:52:09 +0000258 (**Comment).setAttached();
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000259 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000260 }
261 }
262
263 // The comment just after the declaration was not a trailing comment.
264 // Let's look at the previous comment.
265 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000266 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000267 --Comment;
268
269 // Check that we actually have a non-member Doxygen comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000270 if (!((*Comment)->isDocumentation() ||
271 LangOpts.CommentOpts.ParseAllComments) ||
272 (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000273 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000274
275 // Decompose the end of the comment.
276 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000277 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000278
279 // If the comment and the declaration aren't in the same file, then they
280 // aren't related.
281 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000282 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000283
284 // Get the corresponding buffer.
285 bool Invalid = false;
286 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
287 &Invalid).data();
288 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000289 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000290
291 // Extract text between the comment and declaration.
292 StringRef Text(Buffer + CommentEndDecomp.second,
293 DeclLocDecomp.second - CommentEndDecomp.second);
294
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000295 // There should be no other declarations or preprocessor directives between
296 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000297 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000298 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000299
Jan Korous1652d812019-05-13 17:52:09 +0000300 (**Comment).setAttached();
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000301 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000302}
303
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000304/// If we have a 'templated' declaration for a template, adjust 'D' to
305/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000306/// If we have an implicit instantiation, adjust 'D' to refer to template.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000307static const Decl *adjustDeclToTemplate(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000308 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000309 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000310 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000311 return FTD;
312
313 // Nothing to do if function is not an implicit instantiation.
314 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
315 return D;
316
317 // Function is an implicit instantiation of a function template?
318 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
319 return FTD;
320
321 // Function is instantiated from a member definition of a class template?
322 if (const FunctionDecl *MemberDecl =
323 FD->getInstantiatedFromMemberFunction())
324 return MemberDecl;
325
326 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000327 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000328 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000329 // Static data member is instantiated from a member definition of a class
330 // template?
331 if (VD->isStaticDataMember())
332 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
333 return MemberDecl;
334
335 return D;
336 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000337 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000338 // Is this class declaration part of a class template?
339 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
340 return CTD;
341
342 // Class is an implicit instantiation of a class template or partial
343 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000344 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000345 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
346 return D;
347 llvm::PointerUnion<ClassTemplateDecl *,
348 ClassTemplatePartialSpecializationDecl *>
349 PU = CTSD->getSpecializedTemplateOrPartial();
350 return PU.is<ClassTemplateDecl*>() ?
351 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
352 static_cast<const Decl*>(
353 PU.get<ClassTemplatePartialSpecializationDecl *>());
354 }
355
356 // Class is instantiated from a member definition of a class template?
357 if (const MemberSpecializationInfo *Info =
358 CRD->getMemberSpecializationInfo())
359 return Info->getInstantiatedFrom();
360
361 return D;
362 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000363 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000364 // Enum is instantiated from a member definition of a class template?
365 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
366 return MemberDecl;
367
368 return D;
369 }
370 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000371 return D;
372}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000373
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000374const RawComment *ASTContext::getRawCommentForAnyRedecl(
375 const Decl *D,
376 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000377 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000378
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000379 // Check whether we have cached a comment for this declaration already.
380 {
381 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
382 RedeclComments.find(D);
383 if (Pos != RedeclComments.end()) {
384 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000385 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
386 if (OriginalDecl)
387 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000388 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000389 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000390 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000391 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000392
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000393 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000394 const RawComment *RC = nullptr;
395 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000396 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000397 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000398 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000399 if (Pos != RedeclComments.end()) {
400 const RawCommentAndCacheFlags &Raw = Pos->second;
401 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
402 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000403 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000404 break;
405 }
406 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000407 RC = getRawCommentForDeclNoCache(I);
408 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000409 RawCommentAndCacheFlags Raw;
410 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000411 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
412 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000413 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000414 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000415 } else
416 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000417 Raw.setOriginalDecl(I);
418 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000419 if (RC)
420 break;
421 }
422 }
423
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000424 // If we found a comment, it should be a documentation comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000425 assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000426
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000427 if (OriginalDecl)
428 *OriginalDecl = OriginalDeclForRC;
429
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000430 // Update cache for every declaration in the redeclaration chain.
431 RawCommentAndCacheFlags Raw;
432 Raw.setRaw(RC);
433 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000434 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000435
Aaron Ballman86c93902014-03-06 23:45:36 +0000436 for (auto I : D->redecls()) {
437 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000438 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
439 R = Raw;
440 }
441
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000442 return RC;
443}
444
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000445static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
446 SmallVectorImpl<const NamedDecl *> &Redeclared) {
447 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000448 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000449 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
450 if (!ID)
451 return;
452 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000453 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000454 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000455 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000456 ObjCMethod->isInstanceMethod()))
457 Redeclared.push_back(RedeclaredMethod);
458 }
459 }
460}
461
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000462comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
463 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000464 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000465 ThisDeclInfo->CommentDecl = D;
466 ThisDeclInfo->IsFilled = false;
467 ThisDeclInfo->fill();
468 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000469 if (!ThisDeclInfo->TemplateParameters)
470 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000471 comments::FullComment *CFC =
472 new (*this) comments::FullComment(FC->getBlocks(),
473 ThisDeclInfo);
474 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000475}
476
Richard Smithb39b9d52013-05-21 05:24:00 +0000477comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
478 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000479 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000480}
481
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000482comments::FullComment *ASTContext::getCommentForDecl(
483 const Decl *D,
484 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000485 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000486 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000487 D = adjustDeclToTemplate(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000488
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000489 const Decl *Canonical = D->getCanonicalDecl();
490 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
491 ParsedComments.find(Canonical);
Fangrui Song6907ce22018-07-30 19:24:48 +0000492
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000493 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000494 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000495 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000496 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000497 return CFC;
498 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000499 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000500 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000501
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000502 const Decl *OriginalDecl;
Fangrui Song6907ce22018-07-30 19:24:48 +0000503
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000504 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000505 if (!RC) {
506 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000507 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000508 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000509 if (OMD && OMD->isPropertyAccessor())
510 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
511 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
512 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000513 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000514 addRedeclaredMethods(OMD, Overridden);
515 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000516 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
517 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
518 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000519 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000520 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000521 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000522 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000523 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000524 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000525 if (const Decl *TD = TT->getDecl())
526 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000527 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000528 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000529 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000530 while (IC->getSuperClass()) {
531 IC = IC->getSuperClass();
532 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
533 return cloneFullComment(FC, D);
534 }
535 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000536 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000537 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
538 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
539 return cloneFullComment(FC, D);
540 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000541 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000542 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000543 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000544 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000545 for (const auto &I : RD->bases()) {
546 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000547 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000548 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000549 if (Ty.isNull())
550 continue;
551 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
552 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
553 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000554
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000555 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
556 return cloneFullComment(FC, D);
557 }
558 }
559 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000560 for (const auto &I : RD->vbases()) {
561 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000562 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000563 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000564 if (Ty.isNull())
565 continue;
566 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
567 if (!(VirtualBase= VirtualBase->getDefinition()))
568 continue;
569 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
570 return cloneFullComment(FC, D);
571 }
572 }
573 }
Craig Topper36250ad2014-05-12 05:36:57 +0000574 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000575 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000576
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000577 // If the RawComment was attached to other redeclaration of this Decl, we
578 // should parse the comment in context of that other Decl. This is important
579 // because comments can contain references to parameter names which can be
580 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000581 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000582 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000583
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000584 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000585 ParsedComments[Canonical] = FC;
586 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000587}
588
Fangrui Song6907ce22018-07-30 19:24:48 +0000589void
590ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000591 TemplateTemplateParmDecl *Parm) {
592 ID.AddInteger(Parm->getDepth());
593 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000594 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000595
596 TemplateParameterList *Params = Parm->getTemplateParameters();
597 ID.AddInteger(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000598 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000599 PEnd = Params->end();
600 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000601 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000602 ID.AddInteger(0);
603 ID.AddBoolean(TTP->isParameterPack());
604 continue;
605 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000606
Eugene Zelenko7855e772018-04-03 00:11:50 +0000607 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000608 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000609 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000610 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000611 if (NTTP->isExpandedParameterPack()) {
612 ID.AddBoolean(true);
613 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000614 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
615 QualType T = NTTP->getExpansionType(I);
616 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
617 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000618 } else
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000619 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000620 continue;
621 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000622
Eugene Zelenko7855e772018-04-03 00:11:50 +0000623 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000624 ID.AddInteger(2);
625 Profile(ID, TTP);
626 }
627}
628
629TemplateTemplateParmDecl *
630ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000631 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000632 // Check if we already have a canonical template template parameter.
633 llvm::FoldingSetNodeID ID;
634 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000635 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000636 CanonicalTemplateTemplateParm *Canonical
637 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
638 if (Canonical)
639 return Canonical->getParam();
Fangrui Song6907ce22018-07-30 19:24:48 +0000640
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000641 // Build a canonical template parameter list.
642 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000643 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000644 CanonParams.reserve(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000645 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000646 PEnd = Params->end();
647 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000648 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000649 CanonParams.push_back(
Fangrui Song6907ce22018-07-30 19:24:48 +0000650 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000651 SourceLocation(),
652 SourceLocation(),
653 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000654 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000655 TTP->isParameterPack()));
Eugene Zelenko7855e772018-04-03 00:11:50 +0000656 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000657 QualType T = getCanonicalType(NTTP->getType());
658 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
659 NonTypeTemplateParmDecl *Param;
660 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000661 SmallVector<QualType, 2> ExpandedTypes;
662 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000663 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
664 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
665 ExpandedTInfos.push_back(
666 getTrivialTypeSourceInfo(ExpandedTypes.back()));
667 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000668
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000669 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000670 SourceLocation(),
671 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000672 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000673 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000674 T,
675 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000676 ExpandedTypes,
677 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000678 } else {
679 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000680 SourceLocation(),
681 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000682 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000683 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000684 T,
685 NTTP->isParameterPack(),
686 TInfo);
687 }
688 CanonParams.push_back(Param);
689
690 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000691 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
692 cast<TemplateTemplateParmDecl>(*P)));
693 }
694
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000695 assert(!TTP->getRequiresClause() &&
696 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000697 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000698
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000699 TemplateTemplateParmDecl *CanonTTP
Fangrui Song6907ce22018-07-30 19:24:48 +0000700 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000701 SourceLocation(), TTP->getDepth(),
Fangrui Song6907ce22018-07-30 19:24:48 +0000702 TTP->getPosition(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000703 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000704 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000705 TemplateParameterList::Create(*this, SourceLocation(),
706 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000707 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000708 SourceLocation(),
709 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000710
711 // Get the new insert position for the node we care about.
712 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000713 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000714 (void)Canonical;
715
716 // Create the canonical template template parameter entry.
717 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
718 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
719 return CanonTTP;
720}
721
Charles Davis53c59df2010-08-16 03:33:14 +0000722CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000723 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000724
John McCall359b8852013-01-25 22:30:49 +0000725 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000726 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000727 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000728 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000729 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000730 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000731 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000732 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000733 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000734 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000735 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000736 return CreateMicrosoftCXXABI(*this);
737 }
David Blaikie8a40f702012-01-17 06:56:22 +0000738 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000739}
740
Alexander Richardson6d989432017-10-15 18:48:14 +0000741static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
742 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000743 if (LOpts.FakeAddressSpaceMap) {
744 // The fake address space map must have a distinct entry for each
745 // language-specific address space.
746 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000747 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000748 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000749 3, // opencl_local
750 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000751 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000752 4, // opencl_generic
753 5, // cuda_device
754 6, // cuda_constant
755 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000756 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000757 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000758 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000759 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000760 }
761}
762
David Tweed31d09b02013-09-13 12:04:22 +0000763static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
764 const LangOptions &LangOpts) {
765 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000766 case LangOptions::ASMM_Target:
767 return TI.useAddressSpaceMapMangling();
768 case LangOptions::ASMM_On:
769 return true;
770 case LangOptions::ASMM_Off:
771 return false;
772 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000773 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000774}
775
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000776ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000777 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000778 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000779 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
780 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000781 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000782 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000783 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000784 LangOpts.XRayNeverInstrumentFiles,
785 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000786 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000787 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000788 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
789 CompCategories(this_()), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000790 TUDecl = TranslationUnitDecl::Create(*this);
Sam McCall814e7972018-11-14 10:33:30 +0000791 TraversalScope = {TUDecl};
Daniel Dunbar221fa942008-08-11 04:54:23 +0000792}
793
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000794ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000795 // Release the DenseMaps associated with DeclContext objects.
796 // FIXME: Is this the ideal solution?
797 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000798
Manuel Klimeka7328992013-06-03 13:51:33 +0000799 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000800 for (auto &Pair : Deallocations)
801 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000802
Ted Kremenek076baeb2010-06-08 23:00:58 +0000803 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000804 // because they can contain DenseMaps.
805 for (llvm::DenseMap<const ObjCContainerDecl*,
806 const ASTRecordLayout*>::iterator
807 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
808 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000809 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000810 R->Destroy(*this);
811
Ted Kremenek076baeb2010-06-08 23:00:58 +0000812 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
813 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
814 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000815 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000816 R->Destroy(*this);
817 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000818
Douglas Gregor561eceb2010-08-30 16:49:28 +0000819 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
820 AEnd = DeclAttrs.end();
821 A != AEnd; ++A)
822 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000823
David Majnemere694f3e2015-08-14 14:43:50 +0000824 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
825 MaterializedTemporaryValues)
826 MTVPair.second->~APValue();
827
Richard Smith423f46f2016-07-20 21:38:26 +0000828 for (const auto &Value : ModuleInitializers)
829 Value.second->~PerModuleInitializers();
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000830
831 for (APValue *Value : APValueCleanups)
832 Value->~APValue();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000833}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000834
Sam McCall814e7972018-11-14 10:33:30 +0000835class ASTContext::ParentMap {
836 /// Contains parents of a node.
837 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
838
839 /// Maps from a node to its parents. This is used for nodes that have
840 /// pointer identity only, which are more common and we can save space by
841 /// only storing a unique pointer to them.
842 using ParentMapPointers = llvm::DenseMap<
843 const void *,
844 llvm::PointerUnion4<const Decl *, const Stmt *,
845 ast_type_traits::DynTypedNode *, ParentVector *>>;
846
847 /// Parent map for nodes without pointer identity. We store a full
848 /// DynTypedNode for all keys.
849 using ParentMapOtherNodes = llvm::DenseMap<
850 ast_type_traits::DynTypedNode,
851 llvm::PointerUnion4<const Decl *, const Stmt *,
852 ast_type_traits::DynTypedNode *, ParentVector *>>;
853
854 ParentMapPointers PointerParents;
855 ParentMapOtherNodes OtherParents;
856 class ASTVisitor;
857
858 static ast_type_traits::DynTypedNode
859 getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
860 if (const auto *D = U.dyn_cast<const Decl *>())
861 return ast_type_traits::DynTypedNode::create(*D);
862 if (const auto *S = U.dyn_cast<const Stmt *>())
863 return ast_type_traits::DynTypedNode::create(*S);
864 return *U.get<ast_type_traits::DynTypedNode *>();
865 }
866
867 template <typename NodeTy, typename MapTy>
868 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
869 const MapTy &Map) {
870 auto I = Map.find(Node);
871 if (I == Map.end()) {
872 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
873 }
874 if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
875 return llvm::makeArrayRef(*V);
876 }
877 return getSingleDynTypedNodeFromParentMap(I->second);
878 }
879
880public:
881 ParentMap(ASTContext &Ctx);
882 ~ParentMap() {
883 for (const auto &Entry : PointerParents) {
884 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
885 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
886 } else if (Entry.second.is<ParentVector *>()) {
887 delete Entry.second.get<ParentVector *>();
888 }
889 }
890 for (const auto &Entry : OtherParents) {
891 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
892 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
893 } else if (Entry.second.is<ParentVector *>()) {
894 delete Entry.second.get<ParentVector *>();
895 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000896 }
897 }
Sam McCall814e7972018-11-14 10:33:30 +0000898
899 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
900 if (Node.getNodeKind().hasPointerIdentity())
901 return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
902 return getDynNodeFromMap(Node, OtherParents);
Manuel Klimek95403e62014-05-21 13:28:59 +0000903 }
Sam McCall814e7972018-11-14 10:33:30 +0000904};
905
906void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
907 TraversalScope = TopLevelDecls;
908 Parents.reset();
Manuel Klimek95403e62014-05-21 13:28:59 +0000909}
910
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000911void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000912 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000913}
914
Mike Stump11289f42009-09-09 15:08:12 +0000915void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000916ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000917 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000918}
919
Chris Lattner4eb445d2007-01-26 01:27:23 +0000920void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000921 llvm::errs() << "\n*** AST Context Stats:\n";
922 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000923
Douglas Gregora30d0462009-05-26 14:40:08 +0000924 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000925#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000926#define ABSTRACT_TYPE(Name, Parent)
927#include "clang/AST/TypeNodes.def"
928 0 // Extra
929 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000930
Chris Lattner4eb445d2007-01-26 01:27:23 +0000931 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
932 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000933 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000934 }
935
Douglas Gregora30d0462009-05-26 14:40:08 +0000936 unsigned Idx = 0;
937 unsigned TotalBytes = 0;
938#define TYPE(Name, Parent) \
939 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000940 llvm::errs() << " " << counts[Idx] << " " << #Name \
Bruno Ricci58e03222018-08-06 15:17:32 +0000941 << " types, " << sizeof(Name##Type) << " each " \
942 << "(" << counts[Idx] * sizeof(Name##Type) \
943 << " bytes)\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000944 TotalBytes += counts[Idx] * sizeof(Name##Type); \
945 ++Idx;
946#define ABSTRACT_TYPE(Name, Parent)
947#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000948
Chandler Carruth3c147a72011-07-04 05:32:14 +0000949 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
950
Douglas Gregor7454c562010-07-02 20:37:36 +0000951 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000952 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
953 << NumImplicitDefaultConstructors
954 << " implicit default constructors created\n";
955 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
956 << NumImplicitCopyConstructors
957 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000958 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000959 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
960 << NumImplicitMoveConstructors
961 << " implicit move constructors created\n";
962 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
963 << NumImplicitCopyAssignmentOperators
964 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000965 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000966 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
967 << NumImplicitMoveAssignmentOperators
968 << " implicit move assignment operators created\n";
969 llvm::errs() << NumImplicitDestructorsDeclared << "/"
970 << NumImplicitDestructors
971 << " implicit destructors created\n";
972
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000973 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000974 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000975 ExternalSource->PrintStats();
976 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000977
Douglas Gregor5b11d492010-07-25 17:53:33 +0000978 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000979}
980
Richard Smith42413142015-05-15 20:05:43 +0000981void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
982 bool NotifyListeners) {
983 if (NotifyListeners)
984 if (auto *Listener = getASTMutationListener())
985 Listener->RedefinedHiddenDefinition(ND, M);
986
Richard Smith13897eb2018-09-12 23:37:00 +0000987 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
Richard Smith42413142015-05-15 20:05:43 +0000988}
989
990void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
Richard Smith20fbdb32018-09-12 02:13:46 +0000991 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
Richard Smith42413142015-05-15 20:05:43 +0000992 if (It == MergedDefModules.end())
993 return;
994
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000995 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000996 llvm::DenseSet<Module*> Found;
997 for (Module *&M : Merged)
998 if (!Found.insert(M).second)
999 M = nullptr;
1000 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1001}
1002
Richard Smithdc1f0422016-07-20 19:10:16 +00001003void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1004 if (LazyInitializers.empty())
1005 return;
1006
1007 auto *Source = Ctx.getExternalSource();
1008 assert(Source && "lazy initializers but no external source");
1009
1010 auto LazyInits = std::move(LazyInitializers);
1011 LazyInitializers.clear();
1012
1013 for (auto ID : LazyInits)
1014 Initializers.push_back(Source->GetExternalDecl(ID));
1015
1016 assert(LazyInitializers.empty() &&
1017 "GetExternalDecl for lazy module initializer added more inits");
1018}
1019
1020void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1021 // One special case: if we add a module initializer that imports another
1022 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001023 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001024 auto It = ModuleInitializers.find(ID->getImportedModule());
1025
1026 // Maybe the ImportDecl does nothing at all. (Common case.)
1027 if (It == ModuleInitializers.end())
1028 return;
1029
1030 // Maybe the ImportDecl only imports another ImportDecl.
1031 auto &Imported = *It->second;
1032 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1033 Imported.resolve(*this);
1034 auto *OnlyDecl = Imported.Initializers.front();
1035 if (isa<ImportDecl>(OnlyDecl))
1036 D = OnlyDecl;
1037 }
1038 }
1039
1040 auto *&Inits = ModuleInitializers[M];
1041 if (!Inits)
1042 Inits = new (*this) PerModuleInitializers;
1043 Inits->Initializers.push_back(D);
1044}
1045
1046void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1047 auto *&Inits = ModuleInitializers[M];
1048 if (!Inits)
1049 Inits = new (*this) PerModuleInitializers;
1050 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1051 IDs.begin(), IDs.end());
1052}
1053
Eugene Zelenko7855e772018-04-03 00:11:50 +00001054ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001055 auto It = ModuleInitializers.find(M);
Fangrui Song6907ce22018-07-30 19:24:48 +00001056 if (It == ModuleInitializers.end())
Richard Smithdc1f0422016-07-20 19:10:16 +00001057 return None;
1058
1059 auto *Inits = It->second;
1060 Inits->resolve(*this);
1061 return Inits->Initializers;
1062}
1063
Richard Smithf19e1272015-03-07 00:04:49 +00001064ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1065 if (!ExternCContext)
1066 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1067
1068 return ExternCContext;
1069}
1070
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001071BuiltinTemplateDecl *
1072ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1073 const IdentifierInfo *II) const {
1074 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1075 BuiltinTemplate->setImplicit();
1076 TUDecl->addDecl(BuiltinTemplate);
1077
1078 return BuiltinTemplate;
1079}
1080
1081BuiltinTemplateDecl *
1082ASTContext::getMakeIntegerSeqDecl() const {
1083 if (!MakeIntegerSeqDecl)
1084 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1085 getMakeIntegerSeqName());
1086 return MakeIntegerSeqDecl;
1087}
1088
Eric Fiselier6ad68552016-07-01 01:24:09 +00001089BuiltinTemplateDecl *
1090ASTContext::getTypePackElementDecl() const {
1091 if (!TypePackElementDecl)
1092 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1093 getTypePackElementName());
1094 return TypePackElementDecl;
1095}
1096
Alp Toker2dea15b2013-12-17 01:22:38 +00001097RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1098 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001099 SourceLocation Loc;
1100 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001101 if (getLangOpts().CPlusPlus)
1102 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1103 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001104 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001105 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1106 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001107 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001108 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1109 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001110 return NewDecl;
1111}
1112
1113TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1114 StringRef Name) const {
1115 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1116 TypedefDecl *NewDecl = TypedefDecl::Create(
1117 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1118 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1119 NewDecl->setImplicit();
1120 return NewDecl;
1121}
1122
Douglas Gregor801c99d2011-08-12 06:49:56 +00001123TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001124 if (!Int128Decl)
1125 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001126 return Int128Decl;
1127}
1128
1129TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001130 if (!UInt128Decl)
1131 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001132 return UInt128Decl;
1133}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001134
John McCall48f2d582009-10-23 23:03:21 +00001135void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001136 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001137 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001138 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001139}
1140
Artem Belevichb5bc9232015-09-22 17:23:22 +00001141void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1142 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001143 assert((!this->Target || this->Target == &Target) &&
1144 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001145 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001146
Douglas Gregore8bbc122011-09-02 00:18:52 +00001147 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001148 this->AuxTarget = AuxTarget;
1149
Douglas Gregore8bbc122011-09-02 00:18:52 +00001150 ABI.reset(createCXXABI(Target));
1151 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001152 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001153
Chris Lattner970e54e2006-11-12 00:37:36 +00001154 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001155 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001156
Chris Lattner970e54e2006-11-12 00:37:36 +00001157 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001158 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001159 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001160 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001161 InitBuiltinType(CharTy, BuiltinType::Char_S);
1162 else
1163 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001164 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001165 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1166 InitBuiltinType(ShortTy, BuiltinType::Short);
1167 InitBuiltinType(IntTy, BuiltinType::Int);
1168 InitBuiltinType(LongTy, BuiltinType::Long);
1169 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001170
Chris Lattner970e54e2006-11-12 00:37:36 +00001171 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001172 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1173 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1174 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1175 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1176 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001177
Chris Lattner970e54e2006-11-12 00:37:36 +00001178 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001179 InitBuiltinType(FloatTy, BuiltinType::Float);
1180 InitBuiltinType(DoubleTy, BuiltinType::Double);
1181 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001182
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001183 // GNU extension, __float128 for IEEE quadruple precision
1184 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1185
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001186 // C11 extension ISO/IEC TS 18661-3
1187 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1188
Leonard Chanf921d852018-06-04 16:07:52 +00001189 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001190 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1191 InitBuiltinType(AccumTy, BuiltinType::Accum);
1192 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1193 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1194 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1195 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1196 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1197 InitBuiltinType(FractTy, BuiltinType::Fract);
1198 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1199 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1200 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1201 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1202 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1203 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1204 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1205 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1206 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1207 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1208 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1209 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1210 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1211 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1212 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1213 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001214
Chris Lattnerf122cef2009-04-30 02:43:43 +00001215 // GNU extension, 128-bit integers.
1216 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1217 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1218
Hans Wennborg0d81e012013-05-10 10:08:40 +00001219 // C++ 3.9.1p5
1220 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1221 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1222 else // -fshort-wchar makes wchar_t be unsigned.
1223 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1224 if (LangOpts.CPlusPlus && LangOpts.WChar)
1225 WideCharTy = WCharTy;
1226 else {
1227 // C99 (or C++ using -fno-wchar).
1228 WideCharTy = getFromTargetType(Target.getWCharType());
1229 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001230
James Molloy36365542012-05-04 10:55:22 +00001231 WIntTy = getFromTargetType(Target.getWIntType());
1232
Richard Smith3a8244d2018-05-01 05:02:45 +00001233 // C++20 (proposed)
1234 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1235
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001236 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1237 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1238 else // C99
1239 Char16Ty = getFromTargetType(Target.getChar16Type());
1240
1241 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1242 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1243 else // C99
1244 Char32Ty = getFromTargetType(Target.getChar32Type());
1245
Douglas Gregor4619e432008-12-05 23:32:09 +00001246 // Placeholder type for type-dependent expressions whose type is
1247 // completely unknown. No code should ever check a type against
1248 // DependentTy and users should never see it; however, it is here to
1249 // help diagnose failures to properly check for type-dependent
1250 // expressions.
1251 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001252
John McCall36e7fe32010-10-12 00:20:44 +00001253 // Placeholder type for functions.
1254 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1255
John McCall0009fcc2011-04-26 20:42:42 +00001256 // Placeholder type for bound members.
1257 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1258
John McCall526ab472011-10-25 17:37:35 +00001259 // Placeholder type for pseudo-objects.
1260 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1261
John McCall31996342011-04-07 08:22:57 +00001262 // "any" type; useful for debugger-like clients.
1263 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1264
John McCall8a6b59a2011-10-17 18:09:15 +00001265 // Placeholder type for unbridged ARC casts.
1266 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1267
Eli Friedman34866c72012-08-31 00:14:07 +00001268 // Placeholder type for builtin functions.
1269 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1270
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001271 // Placeholder type for OMP array sections.
1272 if (LangOpts.OpenMP)
1273 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1274
Chris Lattner970e54e2006-11-12 00:37:36 +00001275 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001276 FloatComplexTy = getComplexType(FloatTy);
1277 DoubleComplexTy = getComplexType(DoubleTy);
1278 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001279 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001280
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001281 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001282 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1283 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001284 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001285
Alexey Bader954ba212016-04-08 13:40:33 +00001286 if (LangOpts.OpenCL) {
1287#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1288 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001289#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001290
Guy Benyei61054192013-02-07 10:55:47 +00001291 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001292 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001293 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1294 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001295 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001296
1297#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1298 InitBuiltinType(Id##Ty, BuiltinType::Id);
1299#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001300 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001301
Ted Kremeneke65b0862012-03-06 20:05:56 +00001302 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001303 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1304 SignedCharTy : BoolTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001305
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001306 ObjCConstantStringType = QualType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001307
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001308 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001309
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001310 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001311 if (LangOpts.OpenCLVersion >= 200) {
1312 auto Q = VoidTy.getQualifiers();
1313 Q.setAddressSpace(LangAS::opencl_generic);
1314 VoidPtrTy = getPointerType(getCanonicalType(
1315 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1316 } else {
1317 VoidPtrTy = getPointerType(VoidTy);
1318 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001319
1320 // nullptr type (C++0x 2.14.7)
1321 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001322
1323 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1324 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001325
1326 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001327 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001328}
1329
David Blaikie9c902b52011-09-25 23:23:43 +00001330DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001331 return SourceMgr.getDiagnostics();
1332}
1333
Douglas Gregor561eceb2010-08-30 16:49:28 +00001334AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1335 AttrVec *&Result = DeclAttrs[D];
1336 if (!Result) {
1337 void *Mem = Allocate(sizeof(AttrVec));
1338 Result = new (Mem) AttrVec;
1339 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001340
Douglas Gregor561eceb2010-08-30 16:49:28 +00001341 return *Result;
1342}
1343
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001344/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001345void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001346 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1347 if (Pos != DeclAttrs.end()) {
1348 Pos->second->~AttrVec();
1349 DeclAttrs.erase(Pos);
1350 }
1351}
1352
Larisse Voufo39a1e502013-08-06 01:03:05 +00001353// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001354MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001355ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001356 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001357 return getTemplateOrSpecializationInfo(Var)
1358 .dyn_cast<MemberSpecializationInfo *>();
1359}
1360
1361ASTContext::TemplateOrSpecializationInfo
1362ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1363 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1364 TemplateOrInstantiation.find(Var);
1365 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001366 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001367
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001368 return Pos->second;
1369}
1370
Mike Stump11289f42009-09-09 15:08:12 +00001371void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001372ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001373 TemplateSpecializationKind TSK,
1374 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001375 assert(Inst->isStaticDataMember() && "Not a static data member");
1376 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001377 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1378 Tmpl, TSK, PointOfInstantiation));
1379}
1380
1381void
1382ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1383 TemplateOrSpecializationInfo TSI) {
1384 assert(!TemplateOrInstantiation[Inst] &&
1385 "Already noted what the variable was instantiated from");
1386 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001387}
1388
John McCalle61f2ba2009-11-18 02:36:19 +00001389NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001390ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1391 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001392 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001393 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001394
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001395 return Pos->second;
1396}
1397
1398void
Richard Smithd8a9e372016-12-18 21:39:37 +00001399ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001400 assert((isa<UsingDecl>(Pattern) ||
1401 isa<UnresolvedUsingValueDecl>(Pattern) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001402 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
John McCallb96ec562009-12-04 22:46:56 +00001403 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001404 assert((isa<UsingDecl>(Inst) ||
1405 isa<UnresolvedUsingValueDecl>(Inst) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001406 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
Richard Smithd8a9e372016-12-18 21:39:37 +00001407 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001408 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1409 InstantiatedFromUsingDecl[Inst] = Pattern;
1410}
1411
1412UsingShadowDecl *
1413ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1414 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1415 = InstantiatedFromUsingShadowDecl.find(Inst);
1416 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001417 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001418
1419 return Pos->second;
1420}
1421
1422void
1423ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1424 UsingShadowDecl *Pattern) {
1425 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1426 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001427}
1428
Anders Carlsson5da84842009-09-01 04:26:58 +00001429FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1430 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1431 = InstantiatedFromUnnamedFieldDecl.find(Field);
1432 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001433 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001434
Anders Carlsson5da84842009-09-01 04:26:58 +00001435 return Pos->second;
1436}
1437
1438void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1439 FieldDecl *Tmpl) {
1440 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1441 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1442 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1443 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001444
Anders Carlsson5da84842009-09-01 04:26:58 +00001445 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1446}
1447
Douglas Gregor832940b2010-03-02 23:58:15 +00001448ASTContext::overridden_cxx_method_iterator
1449ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001450 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001451}
1452
1453ASTContext::overridden_cxx_method_iterator
1454ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001455 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001456}
1457
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001458unsigned
1459ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001460 auto Range = overridden_methods(Method);
1461 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001462}
1463
Clement Courbet6ecaec82016-07-05 07:49:31 +00001464ASTContext::overridden_method_range
1465ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001466 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1467 OverriddenMethods.find(Method->getCanonicalDecl());
1468 if (Pos == OverriddenMethods.end())
1469 return overridden_method_range(nullptr, nullptr);
1470 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001471}
1472
Fangrui Song6907ce22018-07-30 19:24:48 +00001473void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
Douglas Gregor832940b2010-03-02 23:58:15 +00001474 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001475 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001476 OverriddenMethods[Method].push_back(Overridden);
1477}
1478
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001479void ASTContext::getOverriddenMethods(
1480 const NamedDecl *D,
1481 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001482 assert(D);
1483
Eugene Zelenko7855e772018-04-03 00:11:50 +00001484 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001485 Overridden.append(overridden_methods_begin(CXXMethod),
1486 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001487 return;
1488 }
1489
Eugene Zelenko7855e772018-04-03 00:11:50 +00001490 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001491 if (!Method)
1492 return;
1493
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001494 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1495 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001496 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001497}
1498
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001499void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1500 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1501 assert(!Import->isFromASTFile() && "Non-local import declaration");
1502 if (!FirstLocalImport) {
1503 FirstLocalImport = Import;
1504 LastLocalImport = Import;
1505 return;
1506 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001507
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001508 LastLocalImport->NextLocalImport = Import;
1509 LastLocalImport = Import;
1510}
1511
Chris Lattner53cfe802007-07-18 17:52:12 +00001512//===----------------------------------------------------------------------===//
1513// Type Sizing and Analysis
1514//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001515
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001516/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1517/// scalar floating point type.
1518const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001519 const auto *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001520 assert(BT && "Not a floating point type!");
1521 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001522 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001523 case BuiltinType::Float16:
1524 case BuiltinType::Half:
1525 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001526 case BuiltinType::Float: return Target->getFloatFormat();
1527 case BuiltinType::Double: return Target->getDoubleFormat();
1528 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001529 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001530 }
1531}
1532
Rafael Espindola71eccb32013-08-08 19:53:46 +00001533CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001534 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001535
John McCall94268702010-10-08 18:24:19 +00001536 bool UseAlignAttrOnly = false;
1537 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1538 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001539
John McCall94268702010-10-08 18:24:19 +00001540 // __attribute__((aligned)) can increase or decrease alignment
1541 // *except* on a struct or struct member, where it only increases
1542 // alignment unless 'packed' is also specified.
1543 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001544 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001545 // ignore that possibility; Sema should diagnose it.
1546 if (isa<FieldDecl>(D)) {
1547 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1548 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1549 } else {
1550 UseAlignAttrOnly = true;
1551 }
1552 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001553 else if (isa<FieldDecl>(D))
Fangrui Song6907ce22018-07-30 19:24:48 +00001554 UseAlignAttrOnly =
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001555 D->hasAttr<PackedAttr>() ||
1556 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001557
John McCall4e819612011-01-20 07:57:12 +00001558 // If we're using the align attribute only, just ignore everything
1559 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001560 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001561 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001562 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001563 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001564 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001565 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001566 T = RT->getPointeeType();
1567 else
1568 T = getPointerType(RT->getPointeeType());
1569 }
Richard Smithf6d70302014-06-10 23:34:28 +00001570 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001571 if (T->isFunctionType())
1572 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1573 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001574 // Adjust alignments of declarations with array type by the
1575 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001576 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001577 unsigned MinWidth = Target->getLargeArrayMinWidth();
1578 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001579 if (isa<VariableArrayType>(arrayType))
1580 Align = std::max(Align, Target->getLargeArrayAlign());
1581 else if (isa<ConstantArrayType>(arrayType) &&
1582 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1583 Align = std::max(Align, Target->getLargeArrayAlign());
1584 }
John McCall33ddac02011-01-19 10:06:00 +00001585 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001586 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001587 if (BaseT.getQualifiers().hasUnaligned())
1588 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001589 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Tom Tanb7c6d952019-05-02 00:38:14 +00001590 if (VD->hasGlobalStorage() && !ForAlignof) {
1591 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1592 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1593 }
Ulrich Weigandfa806422013-05-06 16:23:57 +00001594 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001595 }
John McCall4e819612011-01-20 07:57:12 +00001596
1597 // Fields can be subject to extra alignment constraints, like if
1598 // the field is packed, the struct is packed, or the struct has a
1599 // a max-field-alignment constraint (#pragma pack). So calculate
1600 // the actual alignment of the field within the struct, and then
1601 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001602 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001603 const RecordDecl *Parent = Field->getParent();
1604 // We can only produce a sensible answer if the record is valid.
1605 if (!Parent->isInvalidDecl()) {
1606 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001607
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001608 // Start with the record's overall alignment.
1609 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001610
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001611 // Use the GCD of that and the offset within the record.
1612 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1613 if (Offset > 0) {
1614 // Alignment is always a power of 2, so the GCD will be a power of 2,
1615 // which means we get to do this crazy thing instead of Euclid's.
1616 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1617 if (LowBitOfOffset < FieldAlign)
1618 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1619 }
1620
1621 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001622 }
Charles Davis3fc51072010-02-23 04:52:00 +00001623 }
Chris Lattner68061312009-01-24 21:53:27 +00001624 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001625
Ken Dyckcc56c542011-01-15 18:38:59 +00001626 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001627}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001628
John McCallf1249922012-08-21 04:10:00 +00001629// getTypeInfoDataSizeInChars - Return the size of a type, in
1630// chars. If the type is a record, its data size is returned. This is
1631// the size of the memcpy that's performed when assigning this type
1632// using a trivial copy/move assignment operator.
1633std::pair<CharUnits, CharUnits>
1634ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1635 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1636
1637 // In C++, objects can sometimes be allocated into the tail padding
1638 // of a base-class subobject. We decide whether that's possible
1639 // during class layout, so here we can just trust the layout results.
1640 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001641 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001642 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1643 sizeAndAlign.first = layout.getDataSize();
1644 }
1645 }
1646
1647 return sizeAndAlign;
1648}
1649
Richard Trieu04d2d942013-05-14 21:59:17 +00001650/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1651/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1652std::pair<CharUnits, CharUnits>
1653static getConstantArrayInfoInChars(const ASTContext &Context,
1654 const ConstantArrayType *CAT) {
1655 std::pair<CharUnits, CharUnits> EltInfo =
1656 Context.getTypeInfoInChars(CAT->getElementType());
1657 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001658 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1659 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001660 "Overflow in array type char size evaluation");
1661 uint64_t Width = EltInfo.first.getQuantity() * Size;
1662 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001663 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1664 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001665 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001666 return std::make_pair(CharUnits::fromQuantity(Width),
1667 CharUnits::fromQuantity(Align));
1668}
1669
John McCall87fe5d52010-05-20 01:18:31 +00001670std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001671ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001672 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001673 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001674 TypeInfo Info = getTypeInfo(T);
1675 return std::make_pair(toCharUnitsFromBits(Info.Width),
1676 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001677}
1678
1679std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001680ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001681 return getTypeInfoInChars(T.getTypePtr());
1682}
1683
David Majnemer34b57492014-07-30 01:30:47 +00001684bool ASTContext::isAlignmentRequired(const Type *T) const {
1685 return getTypeInfo(T).AlignIsRequired;
1686}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001687
David Majnemer34b57492014-07-30 01:30:47 +00001688bool ASTContext::isAlignmentRequired(QualType T) const {
1689 return isAlignmentRequired(T.getTypePtr());
1690}
1691
Richard Smithb2f0f052016-10-10 18:54:32 +00001692unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1693 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001694 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001695 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1696 return Align;
1697
1698 // If we have an (array of) complete type, we're done.
1699 T = getBaseElementType(T);
1700 if (!T->isIncompleteType())
1701 return getTypeAlign(T);
1702
1703 // If we had an array type, its element type might be a typedef
1704 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001705 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001706 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1707 return Align;
1708
1709 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001710 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001711 return TT->getDecl()->getMaxAlignment();
1712
1713 return 0;
1714}
1715
David Majnemer34b57492014-07-30 01:30:47 +00001716TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001717 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1718 if (I != MemoizedTypeInfo.end())
1719 return I->second;
1720
1721 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1722 TypeInfo TI = getTypeInfoImpl(T);
1723 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001724 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001725}
1726
1727/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1728/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001729///
1730/// FIXME: Pointers into different addr spaces could have different sizes and
1731/// alignment requirements: getPointerInfo should take an AddrSpace, this
1732/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001733TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1734 uint64_t Width = 0;
1735 unsigned Align = 8;
1736 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001737 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001738 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001739#define TYPE(Class, Base)
1740#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001741#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001742#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001743#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1744 case Type::Class: \
1745 assert(!T->isDependentType() && "should not see dependent types here"); \
1746 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001747#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001748 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001749
Chris Lattner355332d2007-07-13 22:27:08 +00001750 case Type::FunctionNoProto:
1751 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001752 // GCC extension: alignof(function) = 32 bits
1753 Width = 0;
1754 Align = 32;
1755 break;
1756
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001757 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001758 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001759 Width = 0;
1760 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1761 break;
1762
Steve Naroff5c131802007-08-30 01:06:46 +00001763 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001764 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001765
David Majnemer34b57492014-07-30 01:30:47 +00001766 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001767 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001768 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001769 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001770 Width = EltInfo.Width * Size;
1771 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001772 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1773 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001774 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001775 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001776 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001777 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001778 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001779 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001780 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1781 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001782 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001783 // If the alignment is not a power of 2, round up to the next power of 2.
1784 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001785 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001786 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001787 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001788 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001789 // Adjust the alignment based on the target max.
1790 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1791 if (TargetVectorAlign && TargetVectorAlign < Align)
1792 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001793 break;
1794 }
Chris Lattner647fb222007-07-18 18:26:58 +00001795
Chris Lattner7570e9c2008-03-08 08:52:55 +00001796 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001797 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001798 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001799 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001800 // GCC extension: alignof(void) = 8 bits.
1801 Width = 0;
1802 Align = 8;
1803 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001804 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001805 Width = Target->getBoolWidth();
1806 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001807 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001808 case BuiltinType::Char_S:
1809 case BuiltinType::Char_U:
1810 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001811 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001812 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001813 Width = Target->getCharWidth();
1814 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001815 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001816 case BuiltinType::WChar_S:
1817 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001818 Width = Target->getWCharWidth();
1819 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001820 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001821 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001822 Width = Target->getChar16Width();
1823 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001824 break;
1825 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001826 Width = Target->getChar32Width();
1827 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001828 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001829 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001830 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001831 Width = Target->getShortWidth();
1832 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001833 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001834 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001835 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001836 Width = Target->getIntWidth();
1837 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001838 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001839 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001840 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001841 Width = Target->getLongWidth();
1842 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001843 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001844 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001845 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001846 Width = Target->getLongLongWidth();
1847 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001848 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001849 case BuiltinType::Int128:
1850 case BuiltinType::UInt128:
1851 Width = 128;
1852 Align = 128; // int128_t is 128-bit aligned on all targets.
1853 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001854 case BuiltinType::ShortAccum:
1855 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001856 case BuiltinType::SatShortAccum:
1857 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001858 Width = Target->getShortAccumWidth();
1859 Align = Target->getShortAccumAlign();
1860 break;
1861 case BuiltinType::Accum:
1862 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001863 case BuiltinType::SatAccum:
1864 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001865 Width = Target->getAccumWidth();
1866 Align = Target->getAccumAlign();
1867 break;
1868 case BuiltinType::LongAccum:
1869 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001870 case BuiltinType::SatLongAccum:
1871 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001872 Width = Target->getLongAccumWidth();
1873 Align = Target->getLongAccumAlign();
1874 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00001875 case BuiltinType::ShortFract:
1876 case BuiltinType::UShortFract:
1877 case BuiltinType::SatShortFract:
1878 case BuiltinType::SatUShortFract:
1879 Width = Target->getShortFractWidth();
1880 Align = Target->getShortFractAlign();
1881 break;
1882 case BuiltinType::Fract:
1883 case BuiltinType::UFract:
1884 case BuiltinType::SatFract:
1885 case BuiltinType::SatUFract:
1886 Width = Target->getFractWidth();
1887 Align = Target->getFractAlign();
1888 break;
1889 case BuiltinType::LongFract:
1890 case BuiltinType::ULongFract:
1891 case BuiltinType::SatLongFract:
1892 case BuiltinType::SatULongFract:
1893 Width = Target->getLongFractWidth();
1894 Align = Target->getLongFractAlign();
1895 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001896 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001897 case BuiltinType::Half:
Alexey Bataev123ad192019-02-27 20:29:45 +00001898 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
1899 !getLangOpts().OpenMPIsDevice) {
1900 Width = Target->getHalfWidth();
1901 Align = Target->getHalfAlign();
1902 } else {
1903 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1904 "Expected OpenMP device compilation.");
1905 Width = AuxTarget->getHalfWidth();
1906 Align = AuxTarget->getHalfAlign();
1907 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001908 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001909 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001910 Width = Target->getFloatWidth();
1911 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001912 break;
1913 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001914 Width = Target->getDoubleWidth();
1915 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001916 break;
1917 case BuiltinType::LongDouble:
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001918 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1919 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
1920 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
1921 Width = AuxTarget->getLongDoubleWidth();
1922 Align = AuxTarget->getLongDoubleAlign();
1923 } else {
1924 Width = Target->getLongDoubleWidth();
1925 Align = Target->getLongDoubleAlign();
1926 }
Chris Lattner6a4f7452007-12-19 19:23:28 +00001927 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001928 case BuiltinType::Float128:
Alexey Bataev123ad192019-02-27 20:29:45 +00001929 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
1930 !getLangOpts().OpenMPIsDevice) {
1931 Width = Target->getFloat128Width();
1932 Align = Target->getFloat128Align();
1933 } else {
1934 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1935 "Expected OpenMP device compilation.");
1936 Width = AuxTarget->getFloat128Width();
1937 Align = AuxTarget->getFloat128Align();
1938 }
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001939 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001940 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001941 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1942 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001943 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001944 case BuiltinType::ObjCId:
1945 case BuiltinType::ObjCClass:
1946 case BuiltinType::ObjCSel:
Fangrui Song6907ce22018-07-30 19:24:48 +00001947 Width = Target->getPointerWidth(0);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001948 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001949 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001950 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001951 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001952 case BuiltinType::OCLClkEvent:
1953 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001954 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001955#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1956 case BuiltinType::Id:
1957#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001958#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1959 case BuiltinType::Id:
1960#include "clang/Basic/OpenCLExtensionTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00001961 AS = getTargetAddressSpace(
1962 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001963 Width = Target->getPointerWidth(AS);
1964 Align = Target->getPointerAlign(AS);
1965 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001966 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001967 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001968 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001969 Width = Target->getPointerWidth(0);
1970 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001971 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001972 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001973 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001974 Width = Target->getPointerWidth(AS);
1975 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001976 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001977 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001978 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001979 // alignof and sizeof should never enter this code path here, so we go
1980 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001981 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001982 Width = Target->getPointerWidth(AS);
1983 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001984 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001985 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001986 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001987 Width = Target->getPointerWidth(AS);
1988 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001989 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001990 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001991 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00001992 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1993 Width = MPI.Width;
1994 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00001995 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001996 }
Chris Lattner647fb222007-07-18 18:26:58 +00001997 case Type::Complex: {
1998 // Complex types have the same alignment as their elements, but twice the
1999 // size.
David Majnemer34b57492014-07-30 01:30:47 +00002000 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2001 Width = EltInfo.Width * 2;
2002 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00002003 break;
2004 }
John McCall8b07ec22010-05-15 11:32:37 +00002005 case Type::ObjCObject:
2006 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00002007 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002008 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002009 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00002010 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002011 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00002012 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00002013 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002014 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00002015 break;
2016 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002017 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002018 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002019 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00002020
2021 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00002022 Width = 8;
2023 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00002024 break;
2025 }
Mike Stump11289f42009-09-09 15:08:12 +00002026
Eugene Zelenko7855e772018-04-03 00:11:50 +00002027 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00002028 const EnumDecl *ED = ET->getDecl();
2029 TypeInfo Info =
2030 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2031 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2032 Info.Align = AttrAlign;
2033 Info.AlignIsRequired = true;
2034 }
2035 return Info;
2036 }
Chris Lattner8b23c252008-04-06 22:05:18 +00002037
Eugene Zelenko7855e772018-04-03 00:11:50 +00002038 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00002039 const RecordDecl *RD = RT->getDecl();
2040 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00002041 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002042 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00002043 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00002044 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00002045 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002046
Chris Lattner63d2b362009-10-22 05:17:15 +00002047 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00002048 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2049 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00002050
Richard Smith600b5262017-01-26 20:40:47 +00002051 case Type::Auto:
2052 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002053 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00002054 assert(!A->getDeducedType().isNull() &&
2055 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00002056 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00002057 }
2058
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002059 case Type::Paren:
2060 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2061
Leonard Chanc72aaf62019-05-07 03:20:17 +00002062 case Type::MacroQualified:
2063 return getTypeInfo(
2064 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2065
Manman Rene6be26c2016-09-13 17:25:08 +00002066 case Type::ObjCTypeParam:
2067 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2068
Douglas Gregoref462e62009-04-30 17:32:17 +00002069 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002070 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002071 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002072 // If the typedef has an aligned attribute on it, it overrides any computed
2073 // alignment we have. This violates the GCC documentation (which says that
2074 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002075 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002076 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002077 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002078 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002079 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002080 AlignIsRequired = Info.AlignIsRequired;
2081 }
David Majnemer34b57492014-07-30 01:30:47 +00002082 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002083 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002084 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002085
Abramo Bagnara6150c882010-05-11 21:36:43 +00002086 case Type::Elaborated:
2087 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002088
John McCall81904512011-01-06 01:58:22 +00002089 case Type::Attributed:
2090 return getTypeInfo(
2091 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2092
Eli Friedman0dfb8892011-10-06 23:00:33 +00002093 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002094 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002095 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2096 Width = Info.Width;
2097 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002098
JF Bastien801fca22018-05-09 03:51:12 +00002099 if (!Width) {
2100 // An otherwise zero-sized type should still generate an
2101 // atomic operation.
2102 Width = Target->getCharWidth();
2103 assert(Align);
2104 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2105 // If the size of the type doesn't exceed the platform's max
2106 // atomic promotion width, make the size and alignment more
2107 // favorable to atomic operations:
2108
John McCalla8ec7eb2013-03-07 21:37:17 +00002109 // Round the size up to a power of 2.
2110 if (!llvm::isPowerOf2_64(Width))
2111 Width = llvm::NextPowerOf2(Width);
2112
2113 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002114 Align = static_cast<unsigned>(Width);
2115 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002116 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002117 break;
2118
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002119 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002120 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2121 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002122 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002123 }
Mike Stump11289f42009-09-09 15:08:12 +00002124
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002125 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002126 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002127}
2128
Momchil Velikov20208cc2018-07-30 17:48:23 +00002129unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2130 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2131 if (I != MemoizedUnadjustedAlign.end())
2132 return I->second;
2133
2134 unsigned UnadjustedAlign;
2135 if (const auto *RT = T->getAs<RecordType>()) {
2136 const RecordDecl *RD = RT->getDecl();
2137 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2138 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2139 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2140 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2141 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2142 } else {
John Brawn6c49f582019-05-22 11:42:54 +00002143 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
Momchil Velikov20208cc2018-07-30 17:48:23 +00002144 }
2145
2146 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2147 return UnadjustedAlign;
2148}
2149
Alexey Bataev00396512015-07-02 03:40:19 +00002150unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2151 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2152 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2153 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2154 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2155 getTargetInfo().getABI() == "elfv1-qpx" &&
2156 T->isSpecificBuiltinType(BuiltinType::Double))
2157 SimdAlign = 256;
2158 return SimdAlign;
2159}
2160
Ken Dyckcc56c542011-01-15 18:38:59 +00002161/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2162CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2163 return CharUnits::fromQuantity(BitSize / getCharWidth());
2164}
2165
Ken Dyckb0fcc592011-02-11 01:54:29 +00002166/// toBits - Convert a size in characters to a size in characters.
2167int64_t ASTContext::toBits(CharUnits CharSize) const {
2168 return CharSize.getQuantity() * getCharWidth();
2169}
2170
Ken Dyck8c89d592009-12-22 14:23:30 +00002171/// getTypeSizeInChars - Return the size of the specified type, in characters.
2172/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002173CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002174 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002175}
Jay Foad39c79802011-01-12 09:06:06 +00002176CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002177 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002178}
2179
Fangrui Song6907ce22018-07-30 19:24:48 +00002180/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002181/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002182CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002183 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002184}
Jay Foad39c79802011-01-12 09:06:06 +00002185CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002186 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002187}
2188
Momchil Velikov20208cc2018-07-30 17:48:23 +00002189/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2190/// type, in characters, before alignment adustments. This method does
2191/// not work on incomplete types.
2192CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2193 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2194}
2195CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2196 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2197}
2198
Chris Lattnera3402cd2009-01-27 18:08:34 +00002199/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2200/// type for the current target in bits. This can be different than the ABI
2201/// alignment in cases where it is beneficial for performance to overalign
2202/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002203unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002204 TypeInfo TI = getTypeInfo(T);
2205 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002206
David Majnemere1544562015-04-24 01:25:05 +00002207 T = T->getBaseElementTypeUnsafe();
2208
2209 // The preferred alignment of member pointers is that of a pointer.
2210 if (T->isMemberPointerType())
2211 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2212
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002213 if (!Target->allowsLargerPreferedTypeAlignment())
2214 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002215
Eli Friedman7ab09572009-05-25 21:27:19 +00002216 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002217 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002218 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002219 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002220 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002221 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002222 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2223 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002224 // Don't increase the alignment if an alignment attribute was specified on a
2225 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002226 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002227 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002228
Chris Lattnera3402cd2009-01-27 18:08:34 +00002229 return ABIAlign;
2230}
2231
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002232/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2233/// for __attribute__((aligned)) on this target, to be used if no alignment
2234/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002235unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002236 return getTargetInfo().getDefaultAlignForAttributeAligned();
2237}
2238
Ulrich Weigandfa806422013-05-06 16:23:57 +00002239/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2240/// to a global variable of the specified type.
2241unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
Tom Tanb7c6d952019-05-02 00:38:14 +00002242 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2243 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
Ulrich Weigandfa806422013-05-06 16:23:57 +00002244}
2245
2246/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2247/// should be given to a global variable of the specified type.
2248CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2249 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2250}
2251
David Majnemer08ef2ba2015-06-23 20:34:18 +00002252CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2253 CharUnits Offset = CharUnits::Zero();
2254 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2255 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2256 Offset += Layout->getBaseClassOffset(Base);
2257 Layout = &getASTRecordLayout(Base);
2258 }
2259 return Offset;
2260}
2261
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002262/// DeepCollectObjCIvars -
2263/// This routine first collects all declared, but not synthesized, ivars in
2264/// super class and then collects all ivars, including those synthesized for
2265/// current class. This routine is used for implementation of current class
2266/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002267void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2268 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002269 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002270 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2271 DeepCollectObjCIvars(SuperClass, false, Ivars);
2272 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002273 for (const auto *I : OI->ivars())
2274 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002275 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002276 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Fangrui Song6907ce22018-07-30 19:24:48 +00002277 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002278 Iv= Iv->getNextIvar())
2279 Ivars.push_back(Iv);
2280 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002281}
2282
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002283/// CollectInheritedProtocols - Collect all protocols in current class and
2284/// those inherited by it.
2285void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002286 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002287 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002288 // We can use protocol_iterator here instead of
Fangrui Song6907ce22018-07-30 19:24:48 +00002289 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002290 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002291 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002292 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002293
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002294 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002295 for (const auto *Cat : OI->visible_categories())
2296 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002297
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002298 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2299 while (SD) {
2300 CollectInheritedProtocols(SD, Protocols);
2301 SD = SD->getSuperClass();
2302 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002303 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002304 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002305 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002306 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002307 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002308 // Insert the protocol.
2309 if (!Protocols.insert(
2310 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2311 return;
2312
2313 for (auto *Proto : OP->protocols())
2314 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002315 }
2316}
2317
Erich Keane8a6b7402017-11-30 16:37:02 +00002318static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2319 const RecordDecl *RD) {
2320 assert(RD->isUnion() && "Must be union type");
2321 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2322
2323 for (const auto *Field : RD->fields()) {
2324 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2325 return false;
2326 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2327 if (FieldSize != UnionSize)
2328 return false;
2329 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002330 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002331}
2332
Benjamin Kramer802e6252017-12-24 12:46:22 +00002333static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002334 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2335
2336 if (!RD->field_empty())
2337 return false;
2338
2339 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2340 return ClassDecl->isEmpty();
2341
2342 return true;
2343}
2344
2345static llvm::Optional<int64_t>
2346structHasUniqueObjectRepresentations(const ASTContext &Context,
2347 const RecordDecl *RD) {
2348 assert(!RD->isUnion() && "Must be struct/class type");
2349 const auto &Layout = Context.getASTRecordLayout(RD);
2350
2351 int64_t CurOffsetInBits = 0;
2352 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2353 if (ClassDecl->isDynamicClass())
2354 return llvm::None;
2355
2356 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2357 for (const auto Base : ClassDecl->bases()) {
2358 // Empty types can be inherited from, and non-empty types can potentially
2359 // have tail padding, so just make sure there isn't an error.
2360 if (!isStructEmpty(Base.getType())) {
2361 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2362 Context, Base.getType()->getAs<RecordType>()->getDecl());
2363 if (!Size)
2364 return llvm::None;
2365 Bases.emplace_back(Base.getType(), Size.getValue());
2366 }
2367 }
2368
Fangrui Song1d38c132018-09-30 21:41:11 +00002369 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2370 const std::pair<QualType, int64_t> &R) {
2371 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2372 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2373 });
Erich Keane8a6b7402017-11-30 16:37:02 +00002374
2375 for (const auto Base : Bases) {
2376 int64_t BaseOffset = Context.toBits(
2377 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2378 int64_t BaseSize = Base.second;
2379 if (BaseOffset != CurOffsetInBits)
2380 return llvm::None;
2381 CurOffsetInBits = BaseOffset + BaseSize;
2382 }
2383 }
2384
2385 for (const auto *Field : RD->fields()) {
2386 if (!Field->getType()->isReferenceType() &&
2387 !Context.hasUniqueObjectRepresentations(Field->getType()))
2388 return llvm::None;
2389
2390 int64_t FieldSizeInBits =
2391 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2392 if (Field->isBitField()) {
2393 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2394
2395 if (BitfieldSize > FieldSizeInBits)
2396 return llvm::None;
2397 FieldSizeInBits = BitfieldSize;
2398 }
2399
2400 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2401
2402 if (FieldOffsetInBits != CurOffsetInBits)
2403 return llvm::None;
2404
2405 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2406 }
2407
2408 return CurOffsetInBits;
2409}
2410
2411bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2412 // C++17 [meta.unary.prop]:
2413 // The predicate condition for a template specialization
2414 // has_unique_object_representations<T> shall be
2415 // satisfied if and only if:
2416 // (9.1) - T is trivially copyable, and
2417 // (9.2) - any two objects of type T with the same value have the same
2418 // object representation, where two objects
2419 // of array or non-union class type are considered to have the same value
2420 // if their respective sequences of
2421 // direct subobjects have the same values, and two objects of union type
2422 // are considered to have the same
2423 // value if they have the same active member and the corresponding members
2424 // have the same value.
2425 // The set of scalar types for which this condition holds is
2426 // implementation-defined. [ Note: If a type has padding
2427 // bits, the condition does not hold; otherwise, the condition holds true
2428 // for unsigned integral types. -- end note ]
2429 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2430
2431 // Arrays are unique only if their element type is unique.
2432 if (Ty->isArrayType())
2433 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2434
2435 // (9.1) - T is trivially copyable...
2436 if (!Ty.isTriviallyCopyableType(*this))
2437 return false;
2438
2439 // All integrals and enums are unique.
2440 if (Ty->isIntegralOrEnumerationType())
2441 return true;
2442
2443 // All other pointers are unique.
2444 if (Ty->isPointerType())
2445 return true;
2446
2447 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002448 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002449 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2450 }
2451
2452 if (Ty->isRecordType()) {
2453 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2454
Erich Keanebd2197c2017-12-12 16:02:06 +00002455 if (Record->isInvalidDecl())
2456 return false;
2457
Erich Keane8a6b7402017-11-30 16:37:02 +00002458 if (Record->isUnion())
2459 return unionHasUniqueObjectRepresentations(*this, Record);
2460
2461 Optional<int64_t> StructSize =
2462 structHasUniqueObjectRepresentations(*this, Record);
2463
2464 return StructSize &&
2465 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2466 }
2467
2468 // FIXME: More cases to handle here (list by rsmith):
2469 // vectors (careful about, eg, vector of 3 foo)
2470 // _Complex int and friends
2471 // _Atomic T
2472 // Obj-C block pointers
2473 // Obj-C object pointers
2474 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2475 // clk_event_t, queue_t, reserve_id_t)
2476 // There're also Obj-C class types and the Obj-C selector type, but I think it
2477 // makes sense for those to return false here.
2478
2479 return false;
2480}
2481
Jay Foad39c79802011-01-12 09:06:06 +00002482unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002483 unsigned count = 0;
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002484 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002485 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002486 count += Ext->ivar_size();
Fangrui Song6907ce22018-07-30 19:24:48 +00002487
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002488 // Count ivar defined in this class's implementation. This
2489 // includes synthesized ivars.
2490 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002491 count += ImplDecl->ivar_size();
2492
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002493 return count;
2494}
2495
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002496bool ASTContext::isSentinelNullExpr(const Expr *E) {
2497 if (!E)
2498 return false;
2499
2500 // nullptr_t is always treated as null.
2501 if (E->getType()->isNullPtrType()) return true;
2502
2503 if (E->getType()->isAnyPointerType() &&
2504 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2505 Expr::NPC_ValueDependentIsNull))
2506 return true;
2507
2508 // Unfortunately, __null has type 'int'.
2509 if (isa<GNUNullExpr>(E)) return true;
2510
2511 return false;
2512}
2513
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002514/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002515/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002516ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2517 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2518 I = ObjCImpls.find(D);
2519 if (I != ObjCImpls.end())
2520 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002521 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002522}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002523
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002524/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002525/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002526ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2527 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2528 I = ObjCImpls.find(D);
2529 if (I != ObjCImpls.end())
2530 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002531 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002532}
2533
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002534/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002535void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2536 ObjCImplementationDecl *ImplD) {
2537 assert(IFaceD && ImplD && "Passed null params");
2538 ObjCImpls[IFaceD] = ImplD;
2539}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002540
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002541/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002542void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2543 ObjCCategoryImplDecl *ImplD) {
2544 assert(CatD && ImplD && "Passed null params");
2545 ObjCImpls[CatD] = ImplD;
2546}
2547
Chandler Carruth21c90602015-12-30 03:24:14 +00002548const ObjCMethodDecl *
2549ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2550 return ObjCMethodRedecls.lookup(MD);
2551}
2552
2553void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2554 const ObjCMethodDecl *Redecl) {
2555 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2556 ObjCMethodRedecls[MD] = Redecl;
2557}
2558
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002559const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2560 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002561 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002562 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002563 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002564 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002565 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002566 return IMD->getClassInterface();
2567
Craig Topper36250ad2014-05-12 05:36:57 +00002568 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002569}
2570
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002571/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002572/// none exists.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002573ASTContext::BlockVarCopyInit
2574ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002575 assert(VD && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002576 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002577 "getBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002578 auto I = BlockVarCopyInits.find(VD);
2579 if (I != BlockVarCopyInits.end())
2580 return I->second;
2581 return {nullptr, false};
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002582}
2583
JF Bastien0d702a72019-04-30 00:11:53 +00002584/// Set the copy initialization expression of a block var decl.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002585void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2586 bool CanThrow) {
2587 assert(VD && CopyExpr && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002588 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002589 "setBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002590 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002591}
2592
John McCallbcd03502009-12-07 02:54:59 +00002593TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002594 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002595 if (!DataSize)
2596 DataSize = TypeLoc::getFullDataSizeForType(T);
2597 else
2598 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002599 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002600
Eugene Zelenko7855e772018-04-03 00:11:50 +00002601 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002602 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2603 new (TInfo) TypeSourceInfo(T);
2604 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002605}
2606
John McCallbcd03502009-12-07 02:54:59 +00002607TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002608 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002609 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002610 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002611 return DI;
2612}
2613
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002614const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002615ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002616 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002617}
2618
2619const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002620ASTContext::getASTObjCImplementationLayout(
2621 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002622 return getObjCLayout(D->getClassInterface(), D);
2623}
2624
Chris Lattner983a8bb2007-07-13 22:13:22 +00002625//===----------------------------------------------------------------------===//
2626// Type creation/memoization methods
2627//===----------------------------------------------------------------------===//
2628
Jay Foad39c79802011-01-12 09:06:06 +00002629QualType
John McCall33ddac02011-01-19 10:06:00 +00002630ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2631 unsigned fastQuals = quals.getFastQualifiers();
2632 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002633
2634 // Check if we've already instantiated this type.
2635 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002636 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002637 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002638 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2639 assert(eq->getQualifiers() == quals);
2640 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002641 }
2642
John McCall33ddac02011-01-19 10:06:00 +00002643 // If the base type is not canonical, make the appropriate canonical type.
2644 QualType canon;
2645 if (!baseType->isCanonicalUnqualified()) {
2646 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002647 canonSplit.Quals.addConsistentQualifiers(quals);
2648 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002649
2650 // Re-find the insert position.
2651 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2652 }
2653
Eugene Zelenko7855e772018-04-03 00:11:50 +00002654 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002655 ExtQualNodes.InsertNode(eq, insertPos);
2656 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002657}
2658
Alexander Richardson6d989432017-10-15 18:48:14 +00002659QualType ASTContext::getAddrSpaceQualType(QualType T,
2660 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002661 QualType CanT = getCanonicalType(T);
2662 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002663 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002664
John McCall8ccfcb52009-09-24 19:53:00 +00002665 // If we are composing extended qualifiers together, merge together
2666 // into one ExtQuals node.
2667 QualifierCollector Quals;
2668 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002669
John McCall8ccfcb52009-09-24 19:53:00 +00002670 // If this type already has an address space specified, it cannot get
2671 // another one.
2672 assert(!Quals.hasAddressSpace() &&
2673 "Type cannot be in multiple addr spaces!");
2674 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002675
John McCall8ccfcb52009-09-24 19:53:00 +00002676 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002677}
2678
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002679QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2680 // If we are composing extended qualifiers together, merge together
2681 // into one ExtQuals node.
2682 QualifierCollector Quals;
2683 const Type *TypeNode = Quals.strip(T);
2684
2685 // If the qualifier doesn't have an address space just return it.
2686 if (!Quals.hasAddressSpace())
2687 return T;
2688
2689 Quals.removeAddressSpace();
2690
2691 // Removal of the address space can mean there are no longer any
2692 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2693 // or required.
2694 if (Quals.hasNonFastQualifiers())
2695 return getExtQualType(TypeNode, Quals);
2696 else
2697 return QualType(TypeNode, Quals.getFastQualifiers());
2698}
2699
Chris Lattnerd60183d2009-02-18 22:53:11 +00002700QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002701 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002702 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002703 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002704 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002705
Eugene Zelenko7855e772018-04-03 00:11:50 +00002706 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002707 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002708 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002709 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2710 return getPointerType(ResultType);
2711 }
2712 }
Mike Stump11289f42009-09-09 15:08:12 +00002713
John McCall8ccfcb52009-09-24 19:53:00 +00002714 // If we are composing extended qualifiers together, merge together
2715 // into one ExtQuals node.
2716 QualifierCollector Quals;
2717 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002718
John McCall8ccfcb52009-09-24 19:53:00 +00002719 // If this type already has an ObjCGC specified, it cannot get
2720 // another one.
2721 assert(!Quals.hasObjCGCAttr() &&
2722 "Type cannot have multiple ObjCGCs!");
2723 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002724
John McCall8ccfcb52009-09-24 19:53:00 +00002725 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002726}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002727
John McCall4f5019e2010-12-19 02:44:49 +00002728const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2729 FunctionType::ExtInfo Info) {
2730 if (T->getExtInfo() == Info)
2731 return T;
2732
2733 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002734 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002735 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002736 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002737 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002738 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2739 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002740 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002741 }
2742
2743 return cast<FunctionType>(Result.getTypePtr());
2744}
2745
Richard Smith2a7d4812013-05-04 07:00:32 +00002746void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2747 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002748 FD = FD->getMostRecentDecl();
2749 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002750 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002751 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002752 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002753 if (FunctionDecl *Next = FD->getPreviousDecl())
2754 FD = Next;
2755 else
2756 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002757 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002758 if (ASTMutationListener *L = getASTMutationListener())
2759 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002760}
2761
Richard Smith0b3a4622014-11-13 20:01:57 +00002762/// Get a function type and produce the equivalent function type with the
2763/// specified exception specification. Type sugar that can be present on a
2764/// declaration of a function with an exception specification is permitted
2765/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002766QualType ASTContext::getFunctionTypeWithExceptionSpec(
2767 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002768 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002769 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002770 return getParenType(
2771 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002772
Leonard Chandc5d9752019-05-10 18:05:15 +00002773 // Might be wrapped in a macro qualified type.
2774 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2775 return getMacroQualifiedType(
2776 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2777 MQT->getMacroIdentifier());
2778
Richard Smith0b3a4622014-11-13 20:01:57 +00002779 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002780 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002781 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002782 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002783 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2784 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002785
2786 // Anything else must be a function type. Rebuild it with the new exception
2787 // specification.
Stephan Bergmann84dcc8f2019-02-13 09:39:17 +00002788 const auto *Proto = Orig->getAs<FunctionProtoType>();
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002789 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002790 Proto->getReturnType(), Proto->getParamTypes(),
2791 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2792}
2793
Richard Smithdfe85e22016-12-15 02:35:39 +00002794bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2795 QualType U) {
2796 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002797 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002798 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2799 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002800}
2801
Richard Smith0b3a4622014-11-13 20:01:57 +00002802void ASTContext::adjustExceptionSpec(
2803 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2804 bool AsWritten) {
2805 // Update the type.
2806 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002807 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002808 FD->setType(Updated);
2809
2810 if (!AsWritten)
2811 return;
2812
2813 // Update the type in the type source information too.
2814 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2815 // If the type and the type-as-written differ, we may need to update
2816 // the type-as-written too.
2817 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002818 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002819
2820 // FIXME: When we get proper type location information for exceptions,
2821 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2822 // up the TypeSourceInfo;
2823 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2824 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2825 "TypeLoc size mismatch from updating exception specification");
2826 TSInfo->overrideType(Updated);
2827 }
2828}
2829
Chris Lattnerc6395932007-06-22 20:56:16 +00002830/// getComplexType - Return the uniqued reference to the type for a complex
2831/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002832QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002833 // Unique pointers, to guarantee there is only one pointer of a particular
2834 // structure.
2835 llvm::FoldingSetNodeID ID;
2836 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002837
Craig Topper36250ad2014-05-12 05:36:57 +00002838 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002839 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2840 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002841
Chris Lattnerc6395932007-06-22 20:56:16 +00002842 // If the pointee type isn't canonical, this won't be a canonical type either,
2843 // so fill in the canonical type field.
2844 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002845 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002846 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002847
Chris Lattnerc6395932007-06-22 20:56:16 +00002848 // Get the new insert position for the node we care about.
2849 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002850 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002851 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002852 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002853 Types.push_back(New);
2854 ComplexTypes.InsertNode(New, InsertPos);
2855 return QualType(New, 0);
2856}
2857
Chris Lattner970e54e2006-11-12 00:37:36 +00002858/// getPointerType - Return the uniqued reference to the type for a pointer to
2859/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002860QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002861 // Unique pointers, to guarantee there is only one pointer of a particular
2862 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002863 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002864 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002865
Craig Topper36250ad2014-05-12 05:36:57 +00002866 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002867 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002868 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002869
Chris Lattner7ccecb92006-11-12 08:50:50 +00002870 // If the pointee type isn't canonical, this won't be a canonical type either,
2871 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002872 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002873 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002874 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002875
Bob Wilsonc8541f22013-03-15 17:12:43 +00002876 // Get the new insert position for the node we care about.
2877 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002878 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002879 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002880 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002881 Types.push_back(New);
2882 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002883 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002884}
2885
Reid Kleckner0503a872013-12-05 01:23:43 +00002886QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2887 llvm::FoldingSetNodeID ID;
2888 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002889 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002890 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2891 if (AT)
2892 return QualType(AT, 0);
2893
2894 QualType Canonical = getCanonicalType(New);
2895
2896 // Get the new insert position for the node we care about.
2897 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002898 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002899
2900 AT = new (*this, TypeAlignment)
2901 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2902 Types.push_back(AT);
2903 AdjustedTypes.InsertNode(AT, InsertPos);
2904 return QualType(AT, 0);
2905}
2906
Reid Kleckner8a365022013-06-24 17:51:48 +00002907QualType ASTContext::getDecayedType(QualType T) const {
2908 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2909
Reid Kleckner8a365022013-06-24 17:51:48 +00002910 QualType Decayed;
2911
2912 // C99 6.7.5.3p7:
2913 // A declaration of a parameter as "array of type" shall be
2914 // adjusted to "qualified pointer to type", where the type
2915 // qualifiers (if any) are those specified within the [ and ] of
2916 // the array type derivation.
2917 if (T->isArrayType())
2918 Decayed = getArrayDecayedType(T);
2919
2920 // C99 6.7.5.3p8:
2921 // A declaration of a parameter as "function returning type"
2922 // shall be adjusted to "pointer to function returning type", as
2923 // in 6.3.2.1.
2924 if (T->isFunctionType())
2925 Decayed = getPointerType(T);
2926
Reid Kleckner0503a872013-12-05 01:23:43 +00002927 llvm::FoldingSetNodeID ID;
2928 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002929 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002930 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2931 if (AT)
2932 return QualType(AT, 0);
2933
Reid Kleckner8a365022013-06-24 17:51:48 +00002934 QualType Canonical = getCanonicalType(Decayed);
2935
2936 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002937 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002938 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002939
Reid Kleckner0503a872013-12-05 01:23:43 +00002940 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2941 Types.push_back(AT);
2942 AdjustedTypes.InsertNode(AT, InsertPos);
2943 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002944}
2945
Mike Stump11289f42009-09-09 15:08:12 +00002946/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002947/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002948QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002949 assert(T->isFunctionType() && "block of function types only");
2950 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002951 // structure.
2952 llvm::FoldingSetNodeID ID;
2953 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002954
Craig Topper36250ad2014-05-12 05:36:57 +00002955 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002956 if (BlockPointerType *PT =
2957 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2958 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002959
2960 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002961 // type either so fill in the canonical type field.
2962 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002963 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002964 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002965
Steve Naroffec33ed92008-08-27 16:04:49 +00002966 // Get the new insert position for the node we care about.
2967 BlockPointerType *NewIP =
2968 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002969 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002970 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002971 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002972 Types.push_back(New);
2973 BlockPointerTypes.InsertNode(New, InsertPos);
2974 return QualType(New, 0);
2975}
2976
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002977/// getLValueReferenceType - Return the uniqued reference to the type for an
2978/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002979QualType
2980ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002981 assert(getCanonicalType(T) != OverloadTy &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002982 "Unresolved overloaded function type");
Fangrui Song6907ce22018-07-30 19:24:48 +00002983
Bill Wendling3708c182007-05-27 10:15:43 +00002984 // Unique pointers, to guarantee there is only one pointer of a particular
2985 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002986 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002987 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002988
Craig Topper36250ad2014-05-12 05:36:57 +00002989 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002990 if (LValueReferenceType *RT =
2991 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002992 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002993
Eugene Zelenko7855e772018-04-03 00:11:50 +00002994 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002995
Bill Wendling3708c182007-05-27 10:15:43 +00002996 // If the referencee type isn't canonical, this won't be a canonical type
2997 // either, so fill in the canonical type field.
2998 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002999 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3000 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3001 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003002
Bill Wendling3708c182007-05-27 10:15:43 +00003003 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003004 LValueReferenceType *NewIP =
3005 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003006 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00003007 }
3008
Eugene Zelenko7855e772018-04-03 00:11:50 +00003009 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3010 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00003011 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003012 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00003013
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003014 return QualType(New, 0);
3015}
3016
3017/// getRValueReferenceType - Return the uniqued reference to the type for an
3018/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003019QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003020 // Unique pointers, to guarantee there is only one pointer of a particular
3021 // structure.
3022 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003023 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003024
Craig Topper36250ad2014-05-12 05:36:57 +00003025 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003026 if (RValueReferenceType *RT =
3027 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3028 return QualType(RT, 0);
3029
Eugene Zelenko7855e772018-04-03 00:11:50 +00003030 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003031
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003032 // If the referencee type isn't canonical, this won't be a canonical type
3033 // either, so fill in the canonical type field.
3034 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003035 if (InnerRef || !T.isCanonical()) {
3036 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3037 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003038
3039 // Get the new insert position for the node we care about.
3040 RValueReferenceType *NewIP =
3041 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003042 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003043 }
3044
Eugene Zelenko7855e772018-04-03 00:11:50 +00003045 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003046 Types.push_back(New);
3047 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00003048 return QualType(New, 0);
3049}
3050
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003051/// getMemberPointerType - Return the uniqued reference to the type for a
3052/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00003053QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003054 // Unique pointers, to guarantee there is only one pointer of a particular
3055 // structure.
3056 llvm::FoldingSetNodeID ID;
3057 MemberPointerType::Profile(ID, T, Cls);
3058
Craig Topper36250ad2014-05-12 05:36:57 +00003059 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003060 if (MemberPointerType *PT =
3061 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3062 return QualType(PT, 0);
3063
3064 // If the pointee or class type isn't canonical, this won't be a canonical
3065 // type either, so fill in the canonical type field.
3066 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00003067 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003068 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3069
3070 // Get the new insert position for the node we care about.
3071 MemberPointerType *NewIP =
3072 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003073 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003074 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003075 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003076 Types.push_back(New);
3077 MemberPointerTypes.InsertNode(New, InsertPos);
3078 return QualType(New, 0);
3079}
3080
Mike Stump11289f42009-09-09 15:08:12 +00003081/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00003082/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00003083QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00003084 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003085 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003086 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00003087 assert((EltTy->isDependentType() ||
3088 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00003089 "Constant array of VLAs is illegal!");
3090
Chris Lattnere2df3f92009-05-13 04:12:56 +00003091 // Convert the array size into a canonical width matching the pointer size for
3092 // the target.
3093 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00003094 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00003095
Chris Lattner23b7eb62007-06-15 23:05:46 +00003096 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00003097 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00003098
Craig Topper36250ad2014-05-12 05:36:57 +00003099 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003100 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003101 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003102 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003103
John McCall33ddac02011-01-19 10:06:00 +00003104 // If the element type isn't canonical or has qualifiers, this won't
3105 // be a canonical type either, so fill in the canonical type field.
3106 QualType Canon;
3107 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3108 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003109 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003110 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003111 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003112
Chris Lattner36f8e652007-01-27 08:31:04 +00003113 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003114 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003115 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003116 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003117 }
Mike Stump11289f42009-09-09 15:08:12 +00003118
Eugene Zelenko7855e772018-04-03 00:11:50 +00003119 auto *New = new (*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003120 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003121 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003122 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003123 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003124}
3125
John McCall06549462011-01-18 08:40:38 +00003126/// getVariableArrayDecayedType - Turns the given type, which may be
3127/// variably-modified, into the corresponding type with all the known
3128/// sizes replaced with [*].
3129QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3130 // Vastly most common case.
3131 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003132
John McCall06549462011-01-18 08:40:38 +00003133 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003134
John McCall06549462011-01-18 08:40:38 +00003135 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003136 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003137 switch (ty->getTypeClass()) {
3138#define TYPE(Class, Base)
3139#define ABSTRACT_TYPE(Class, Base)
3140#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3141#include "clang/AST/TypeNodes.def"
3142 llvm_unreachable("didn't desugar past all non-canonical types?");
3143
3144 // These types should never be variably-modified.
3145 case Type::Builtin:
3146 case Type::Complex:
3147 case Type::Vector:
Erich Keanef702b022018-07-13 19:46:04 +00003148 case Type::DependentVector:
John McCall06549462011-01-18 08:40:38 +00003149 case Type::ExtVector:
3150 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003151 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003152 case Type::ObjCObject:
3153 case Type::ObjCInterface:
3154 case Type::ObjCObjectPointer:
3155 case Type::Record:
3156 case Type::Enum:
3157 case Type::UnresolvedUsing:
3158 case Type::TypeOfExpr:
3159 case Type::TypeOf:
3160 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003161 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003162 case Type::DependentName:
3163 case Type::InjectedClassName:
3164 case Type::TemplateSpecialization:
3165 case Type::DependentTemplateSpecialization:
3166 case Type::TemplateTypeParm:
3167 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003168 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003169 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003170 case Type::PackExpansion:
3171 llvm_unreachable("type should never be variably-modified");
3172
3173 // These types can be variably-modified but should never need to
3174 // further decay.
3175 case Type::FunctionNoProto:
3176 case Type::FunctionProto:
3177 case Type::BlockPointer:
3178 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003179 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003180 return type;
3181
3182 // These types can be variably-modified. All these modifications
3183 // preserve structure except as noted by comments.
3184 // TODO: if we ever care about optimizing VLAs, there are no-op
3185 // optimizations available here.
3186 case Type::Pointer:
3187 result = getPointerType(getVariableArrayDecayedType(
3188 cast<PointerType>(ty)->getPointeeType()));
3189 break;
3190
3191 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003192 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003193 result = getLValueReferenceType(
3194 getVariableArrayDecayedType(lv->getPointeeType()),
3195 lv->isSpelledAsLValue());
3196 break;
3197 }
3198
3199 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003200 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003201 result = getRValueReferenceType(
3202 getVariableArrayDecayedType(lv->getPointeeType()));
3203 break;
3204 }
3205
Eli Friedman0dfb8892011-10-06 23:00:33 +00003206 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003207 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003208 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3209 break;
3210 }
3211
John McCall06549462011-01-18 08:40:38 +00003212 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003213 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003214 result = getConstantArrayType(
3215 getVariableArrayDecayedType(cat->getElementType()),
3216 cat->getSize(),
3217 cat->getSizeModifier(),
3218 cat->getIndexTypeCVRQualifiers());
3219 break;
3220 }
3221
3222 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003223 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003224 result = getDependentSizedArrayType(
3225 getVariableArrayDecayedType(dat->getElementType()),
3226 dat->getSizeExpr(),
3227 dat->getSizeModifier(),
3228 dat->getIndexTypeCVRQualifiers(),
3229 dat->getBracketsRange());
3230 break;
3231 }
3232
3233 // Turn incomplete types into [*] types.
3234 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003235 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003236 result = getVariableArrayType(
3237 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003238 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003239 ArrayType::Normal,
3240 iat->getIndexTypeCVRQualifiers(),
3241 SourceRange());
3242 break;
3243 }
3244
3245 // Turn VLA types into [*] types.
3246 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003247 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003248 result = getVariableArrayType(
3249 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003250 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003251 ArrayType::Star,
3252 vat->getIndexTypeCVRQualifiers(),
3253 vat->getBracketsRange());
3254 break;
3255 }
3256 }
3257
3258 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003259 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003260}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003261
Steve Naroffcadebd02007-08-30 18:14:25 +00003262/// getVariableArrayType - Returns a non-unique reference to the type for a
3263/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003264QualType ASTContext::getVariableArrayType(QualType EltTy,
3265 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003266 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003267 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003268 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003269 // Since we don't unique expressions, it isn't possible to unique VLA's
3270 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003271 QualType Canon;
Fangrui Song6907ce22018-07-30 19:24:48 +00003272
John McCall33ddac02011-01-19 10:06:00 +00003273 // Be sure to pull qualifiers off the element type.
3274 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3275 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003276 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003277 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003278 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003279 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003280
Eugene Zelenko7855e772018-04-03 00:11:50 +00003281 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003282 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003283
3284 VariableArrayTypes.push_back(New);
3285 Types.push_back(New);
3286 return QualType(New, 0);
3287}
3288
Douglas Gregor4619e432008-12-05 23:32:09 +00003289/// getDependentSizedArrayType - Returns a non-unique reference to
3290/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003291/// type.
John McCall33ddac02011-01-19 10:06:00 +00003292QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3293 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003294 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003295 unsigned elementTypeQuals,
3296 SourceRange brackets) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003297 assert((!numElements || numElements->isTypeDependent() ||
John McCall33ddac02011-01-19 10:06:00 +00003298 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003299 "Size must be type- or value-dependent!");
3300
John McCall33ddac02011-01-19 10:06:00 +00003301 // Dependently-sized array types that do not have a specified number
3302 // of elements will have their sizes deduced from a dependent
3303 // initializer. We do no canonicalization here at all, which is okay
3304 // because they can't be used in most locations.
3305 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003306 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003307 = new (*this, TypeAlignment)
3308 DependentSizedArrayType(*this, elementType, QualType(),
3309 numElements, ASM, elementTypeQuals,
3310 brackets);
3311 Types.push_back(newType);
3312 return QualType(newType, 0);
3313 }
3314
3315 // Otherwise, we actually build a new type every time, but we
3316 // also build a canonical type.
3317
3318 SplitQualType canonElementType = getCanonicalType(elementType).split();
3319
Craig Topper36250ad2014-05-12 05:36:57 +00003320 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003321 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003322 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003323 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003324 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003325
John McCall33ddac02011-01-19 10:06:00 +00003326 // Look for an existing type with these properties.
3327 DependentSizedArrayType *canonTy =
3328 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003329
John McCall33ddac02011-01-19 10:06:00 +00003330 // If we don't have one, build one.
3331 if (!canonTy) {
3332 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003333 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003334 QualType(), numElements, ASM, elementTypeQuals,
3335 brackets);
3336 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3337 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003338 }
3339
John McCall33ddac02011-01-19 10:06:00 +00003340 // Apply qualifiers from the element type to the array.
3341 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003342 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003343
David Majnemer16a74702015-07-24 05:54:19 +00003344 // If we didn't need extra canonicalization for the element type or the size
3345 // expression, then just use that as our result.
3346 if (QualType(canonElementType.Ty, 0) == elementType &&
3347 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003348 return canon;
3349
3350 // Otherwise, we need to build a type which follows the spelling
3351 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003352 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003353 = new (*this, TypeAlignment)
3354 DependentSizedArrayType(*this, elementType, canon, numElements,
3355 ASM, elementTypeQuals, brackets);
3356 Types.push_back(sugaredType);
3357 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003358}
3359
John McCall33ddac02011-01-19 10:06:00 +00003360QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003361 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003362 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003363 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003364 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003365
Craig Topper36250ad2014-05-12 05:36:57 +00003366 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003367 if (IncompleteArrayType *iat =
3368 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3369 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003370
3371 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003372 // either, so fill in the canonical type field. We also have to pull
3373 // qualifiers off the element type.
3374 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003375
John McCall33ddac02011-01-19 10:06:00 +00003376 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3377 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003378 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003379 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003380 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003381
3382 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003383 IncompleteArrayType *existing =
3384 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3385 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003386 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003387
Eugene Zelenko7855e772018-04-03 00:11:50 +00003388 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003389 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003390
John McCall33ddac02011-01-19 10:06:00 +00003391 IncompleteArrayTypes.InsertNode(newType, insertPos);
3392 Types.push_back(newType);
3393 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003394}
3395
Steve Naroff91fcddb2007-07-18 18:00:27 +00003396/// getVectorType - Return the unique reference to a vector type of
3397/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003398QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003399 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003400 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003401
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003402 // Check if we've already instantiated a vector of this type.
3403 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003404 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003405
Craig Topper36250ad2014-05-12 05:36:57 +00003406 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003407 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3408 return QualType(VTP, 0);
3409
3410 // If the element type isn't canonical, this won't be a canonical type either,
3411 // so fill in the canonical type field.
3412 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003413 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003414 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003415
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003416 // Get the new insert position for the node we care about.
3417 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003418 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003419 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003420 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003421 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003422 VectorTypes.InsertNode(New, InsertPos);
3423 Types.push_back(New);
3424 return QualType(New, 0);
3425}
3426
Erich Keanef702b022018-07-13 19:46:04 +00003427QualType
3428ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3429 SourceLocation AttrLoc,
3430 VectorType::VectorKind VecKind) const {
3431 llvm::FoldingSetNodeID ID;
3432 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3433 VecKind);
3434 void *InsertPos = nullptr;
3435 DependentVectorType *Canon =
3436 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3437 DependentVectorType *New;
3438
3439 if (Canon) {
3440 New = new (*this, TypeAlignment) DependentVectorType(
3441 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3442 } else {
3443 QualType CanonVecTy = getCanonicalType(VecType);
3444 if (CanonVecTy == VecType) {
3445 New = new (*this, TypeAlignment) DependentVectorType(
3446 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3447
3448 DependentVectorType *CanonCheck =
3449 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3450 assert(!CanonCheck &&
3451 "Dependent-sized vector_size canonical type broken");
3452 (void)CanonCheck;
3453 DependentVectorTypes.InsertNode(New, InsertPos);
3454 } else {
3455 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3456 SourceLocation());
3457 New = new (*this, TypeAlignment) DependentVectorType(
3458 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3459 }
3460 }
3461
3462 Types.push_back(New);
3463 return QualType(New, 0);
3464}
3465
Nate Begemance4d7fc2008-04-18 23:10:10 +00003466/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003467/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003468QualType
3469ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003470 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003471
Steve Naroff91fcddb2007-07-18 18:00:27 +00003472 // Check if we've already instantiated a vector of this type.
3473 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003474 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003475 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003476 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003477 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3478 return QualType(VTP, 0);
3479
3480 // If the element type isn't canonical, this won't be a canonical type either,
3481 // so fill in the canonical type field.
3482 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003483 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003484 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003485
Steve Naroff91fcddb2007-07-18 18:00:27 +00003486 // Get the new insert position for the node we care about.
3487 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003488 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003489 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003490 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003491 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003492 VectorTypes.InsertNode(New, InsertPos);
3493 Types.push_back(New);
3494 return QualType(New, 0);
3495}
3496
Jay Foad39c79802011-01-12 09:06:06 +00003497QualType
3498ASTContext::getDependentSizedExtVectorType(QualType vecType,
3499 Expr *SizeExpr,
3500 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003501 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003502 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003503 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003504
Craig Topper36250ad2014-05-12 05:36:57 +00003505 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003506 DependentSizedExtVectorType *Canon
3507 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3508 DependentSizedExtVectorType *New;
3509 if (Canon) {
3510 // We already have a canonical version of this array type; use it as
3511 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003512 New = new (*this, TypeAlignment)
3513 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3514 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003515 } else {
3516 QualType CanonVecTy = getCanonicalType(vecType);
3517 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003518 New = new (*this, TypeAlignment)
3519 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3520 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003521
3522 DependentSizedExtVectorType *CanonCheck
3523 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3524 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3525 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003526 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3527 } else {
3528 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3529 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003530 New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003531 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003532 }
3533 }
Mike Stump11289f42009-09-09 15:08:12 +00003534
Douglas Gregor758a8692009-06-17 21:51:59 +00003535 Types.push_back(New);
3536 return QualType(New, 0);
3537}
3538
Fangrui Song6907ce22018-07-30 19:24:48 +00003539QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3540 Expr *AddrSpaceExpr,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003541 SourceLocation AttrLoc) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003542 assert(AddrSpaceExpr->isInstantiationDependent());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003543
3544 QualType canonPointeeType = getCanonicalType(PointeeType);
3545
3546 void *insertPos = nullptr;
3547 llvm::FoldingSetNodeID ID;
3548 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3549 AddrSpaceExpr);
3550
3551 DependentAddressSpaceType *canonTy =
3552 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3553
3554 if (!canonTy) {
3555 canonTy = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003556 DependentAddressSpaceType(*this, canonPointeeType,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003557 QualType(), AddrSpaceExpr, AttrLoc);
3558 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3559 Types.push_back(canonTy);
3560 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003561
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003562 if (canonPointeeType == PointeeType &&
3563 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
Fangrui Song6907ce22018-07-30 19:24:48 +00003564 return QualType(canonTy, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003565
Eugene Zelenko7855e772018-04-03 00:11:50 +00003566 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003567 = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003568 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003569 AddrSpaceExpr, AttrLoc);
3570 Types.push_back(sugaredType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003571 return QualType(sugaredType, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003572}
3573
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003574/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003575static bool isCanonicalResultType(QualType T) {
3576 return T.isCanonical() &&
3577 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3578 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3579}
3580
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003581/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003582QualType
3583ASTContext::getFunctionNoProtoType(QualType ResultTy,
3584 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003585 // Unique functions, to guarantee there is only one function of a particular
3586 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003587 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003588 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003589
Craig Topper36250ad2014-05-12 05:36:57 +00003590 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003591 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003592 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003593 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003594
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003595 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003596 if (!isCanonicalResultType(ResultTy)) {
3597 Canonical =
3598 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003599
Chris Lattner47955de2007-01-27 08:37:20 +00003600 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003601 FunctionNoProtoType *NewIP =
3602 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003603 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003604 }
Mike Stump11289f42009-09-09 15:08:12 +00003605
Eugene Zelenko7855e772018-04-03 00:11:50 +00003606 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003607 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003608 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003609 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003610 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003611}
3612
Douglas Gregora602a152015-10-01 20:20:47 +00003613CanQualType
3614ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3615 CanQualType CanResultType = getCanonicalType(ResultType);
3616
3617 // Canonical result types do not have ARC lifetime qualifiers.
3618 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3619 Qualifiers Qs = CanResultType.getQualifiers();
3620 Qs.removeObjCLifetime();
3621 return CanQualType::CreateUnsafe(
3622 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3623 }
3624
3625 return CanResultType;
3626}
3627
Richard Smith3c4f8d22016-10-16 17:54:23 +00003628static bool isCanonicalExceptionSpecification(
3629 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3630 if (ESI.Type == EST_None)
3631 return true;
3632 if (!NoexceptInType)
3633 return false;
3634
3635 // C++17 onwards: exception specification is part of the type, as a simple
3636 // boolean "can this function type throw".
3637 if (ESI.Type == EST_BasicNoexcept)
3638 return true;
3639
Richard Smitheaf11ad2018-05-03 03:58:32 +00003640 // A noexcept(expr) specification is (possibly) canonical if expr is
3641 // value-dependent.
3642 if (ESI.Type == EST_DependentNoexcept)
3643 return true;
3644
Richard Smith3c4f8d22016-10-16 17:54:23 +00003645 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003646 // expansions (so we can't tell whether it's non-throwing) and all its
3647 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003648 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003649 bool AnyPackExpansions = false;
3650 for (QualType ET : ESI.Exceptions) {
3651 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003652 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003653 if (ET->getAs<PackExpansionType>())
3654 AnyPackExpansions = true;
3655 }
3656 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003657 }
3658
Richard Smith3c4f8d22016-10-16 17:54:23 +00003659 return false;
3660}
3661
Richard Smith304b1242016-10-18 20:13:25 +00003662QualType ASTContext::getFunctionTypeInternal(
3663 QualType ResultTy, ArrayRef<QualType> ArgArray,
3664 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003665 size_t NumArgs = ArgArray.size();
3666
Richard Smith2a2cda52016-10-18 19:29:18 +00003667 // Unique functions, to guarantee there is only one function of a particular
3668 // structure.
3669 llvm::FoldingSetNodeID ID;
3670 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3671 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003672
Richard Smith2a2cda52016-10-18 19:29:18 +00003673 QualType Canonical;
3674 bool Unique = false;
3675
3676 void *InsertPos = nullptr;
3677 if (FunctionProtoType *FPT =
3678 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3679 QualType Existing = QualType(FPT, 0);
3680
3681 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3682 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003683 // noexcept expression, or we're just looking for a canonical type.
3684 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003685 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003686 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003687 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3688 return Existing;
3689
3690 // We need a new type sugar node for this one, to hold the new noexcept
3691 // expression. We do no canonicalization here, but that's OK since we don't
3692 // expect to see the same noexcept expression much more than once.
3693 Canonical = getCanonicalType(Existing);
3694 Unique = true;
3695 }
3696
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003697 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003698 bool IsCanonicalExceptionSpec =
3699 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3700
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003701 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003702 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003703 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003704 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003705 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003706 isCanonical = false;
3707
Richard Smith304b1242016-10-18 20:13:25 +00003708 if (OnlyWantCanonical)
3709 assert(isCanonical &&
3710 "given non-canonical parameters constructing canonical type");
3711
Richard Smith2a2cda52016-10-18 19:29:18 +00003712 // If this type isn't canonical, get the canonical version of it if we don't
3713 // already have it. The exception spec is only partially part of the
3714 // canonical type, and only in C++17 onwards.
3715 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003716 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003717 CanonicalArgs.reserve(NumArgs);
3718 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003719 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003720
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003721 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003722 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003723 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003724
3725 if (IsCanonicalExceptionSpec) {
3726 // Exception spec is already OK.
3727 } else if (NoexceptInType) {
3728 switch (EPI.ExceptionSpec.Type) {
3729 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3730 // We don't know yet. It shouldn't matter what we pick here; no-one
3731 // should ever look at this.
3732 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003733 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003734 CanonicalEPI.ExceptionSpec.Type = EST_None;
3735 break;
3736
Richard Smith2a2cda52016-10-18 19:29:18 +00003737 // A dynamic exception specification is almost always "not noexcept",
3738 // with the exception that a pack expansion might expand to no types.
3739 case EST_Dynamic: {
3740 bool AnyPacks = false;
3741 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3742 if (ET->getAs<PackExpansionType>())
3743 AnyPacks = true;
3744 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3745 }
3746 if (!AnyPacks)
3747 CanonicalEPI.ExceptionSpec.Type = EST_None;
3748 else {
3749 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3750 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3751 }
3752 break;
3753 }
3754
Erich Keaned02f4a12019-05-30 17:31:54 +00003755 case EST_DynamicNone:
3756 case EST_BasicNoexcept:
3757 case EST_NoexceptTrue:
3758 case EST_NoThrow:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003759 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3760 break;
3761
Richard Smitheaf11ad2018-05-03 03:58:32 +00003762 case EST_DependentNoexcept:
3763 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003764 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003765 } else {
3766 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3767 }
John McCalldb40c7f2010-12-14 08:05:40 +00003768
Douglas Gregora602a152015-10-01 20:20:47 +00003769 // Adjust the canonical function result type.
3770 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003771 Canonical =
3772 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003773
Chris Lattnerfd4de792007-01-27 01:15:32 +00003774 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003775 FunctionProtoType *NewIP =
3776 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003777 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003778 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003779
Bruno Ricci26a25362018-10-02 11:46:38 +00003780 // Compute the needed size to hold this FunctionProtoType and the
3781 // various trailing objects.
3782 auto ESH = FunctionProtoType::getExceptionSpecSize(
3783 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3784 size_t Size = FunctionProtoType::totalSizeToAlloc<
3785 QualType, FunctionType::FunctionTypeExtraBitfields,
3786 FunctionType::ExceptionType, Expr *, FunctionDecl *,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003787 FunctionProtoType::ExtParameterInfo, Qualifiers>(
Bruno Ricci26a25362018-10-02 11:46:38 +00003788 NumArgs, FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
3789 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003790 EPI.ExtParameterInfos ? NumArgs : 0,
3791 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
John McCall18afab72016-03-01 00:49:02 +00003792
Bruno Ricci26a25362018-10-02 11:46:38 +00003793 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003794 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003795 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003796 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003797 if (!Unique)
3798 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003799 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003800}
Chris Lattneref51c202006-11-10 07:17:23 +00003801
Joey Goulye3c85de2016-12-01 11:30:49 +00003802QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003803 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003804 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003805
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003806 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003807 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003808 return QualType(PT, 0);
3809
3810 // If the pipe element type isn't canonical, this won't be a canonical type
3811 // either, so fill in the canonical type field.
3812 QualType Canonical;
3813 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003814 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003815
3816 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003817 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003818 assert(!NewIP && "Shouldn't be in the map!");
3819 (void)NewIP;
3820 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003821 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003822 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003823 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003824 return QualType(New, 0);
3825}
3826
Anastasia Stulova59055b92018-05-09 13:23:26 +00003827QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3828 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3829 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3830 : Ty;
3831}
3832
Joey Goulye3c85de2016-12-01 11:30:49 +00003833QualType ASTContext::getReadPipeType(QualType T) const {
3834 return getPipeType(T, true);
3835}
3836
Joey Gouly5788b782016-11-18 14:10:54 +00003837QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003838 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003839}
3840
John McCalle78aac42010-03-10 03:28:59 +00003841#ifndef NDEBUG
3842static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3843 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003844 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003845 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3846 return true;
3847 if (RD->getDescribedClassTemplate() &&
3848 !isa<ClassTemplateSpecializationDecl>(RD))
3849 return true;
3850 return false;
3851}
3852#endif
3853
3854/// getInjectedClassNameType - Return the unique reference to the
3855/// injected class name type for the specified templated declaration.
3856QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003857 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003858 assert(NeedsInjectedClassNameType(Decl));
3859 if (Decl->TypeForDecl) {
3860 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003861 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003862 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3863 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3864 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3865 } else {
John McCall424cec92011-01-19 06:33:43 +00003866 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003867 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003868 Decl->TypeForDecl = newType;
3869 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003870 }
3871 return QualType(Decl->TypeForDecl, 0);
3872}
3873
Douglas Gregor83a586e2008-04-13 21:07:44 +00003874/// getTypeDeclType - Return the unique reference to the type for the
3875/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003876QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003877 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003878 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003879
Eugene Zelenko7855e772018-04-03 00:11:50 +00003880 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003881 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003882
John McCall96f0b5f2010-03-10 06:48:02 +00003883 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3884 "Template type parameter types are always available.");
3885
Eugene Zelenko7855e772018-04-03 00:11:50 +00003886 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003887 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003888 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003889 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003890 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003891 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003892 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003893 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003894 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3895 Decl->TypeForDecl = newType;
3896 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003897 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003898 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003899
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003900 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003901}
3902
Chris Lattner32d920b2007-01-26 02:01:53 +00003903/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003904/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003905QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003906ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3907 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003908 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003909
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003910 if (Canonical.isNull())
3911 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00003912 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003913 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003914 Decl->TypeForDecl = newType;
3915 Types.push_back(newType);
3916 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003917}
3918
Jay Foad39c79802011-01-12 09:06:06 +00003919QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003920 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3921
Douglas Gregorec9fd132012-01-14 16:38:05 +00003922 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003923 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003924 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003925
Eugene Zelenko7855e772018-04-03 00:11:50 +00003926 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003927 Decl->TypeForDecl = newType;
3928 Types.push_back(newType);
3929 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003930}
3931
Jay Foad39c79802011-01-12 09:06:06 +00003932QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003933 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3934
Douglas Gregorec9fd132012-01-14 16:38:05 +00003935 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003936 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003937 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003938
Eugene Zelenko7855e772018-04-03 00:11:50 +00003939 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003940 Decl->TypeForDecl = newType;
3941 Types.push_back(newType);
3942 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003943}
3944
Richard Smithe43e2b32018-08-20 21:47:29 +00003945QualType ASTContext::getAttributedType(attr::Kind attrKind,
John McCall81904512011-01-06 01:58:22 +00003946 QualType modifiedType,
3947 QualType equivalentType) {
3948 llvm::FoldingSetNodeID id;
3949 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3950
Craig Topper36250ad2014-05-12 05:36:57 +00003951 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003952 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3953 if (type) return QualType(type, 0);
3954
3955 QualType canon = getCanonicalType(equivalentType);
3956 type = new (*this, TypeAlignment)
Leonard Chanc72aaf62019-05-07 03:20:17 +00003957 AttributedType(canon, attrKind, modifiedType, equivalentType);
John McCall81904512011-01-06 01:58:22 +00003958
3959 Types.push_back(type);
3960 AttributedTypes.InsertNode(type, insertPos);
3961
3962 return QualType(type, 0);
3963}
3964
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003965/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00003966QualType
3967ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003968 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003969 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003970 && "replacement types must always be canonical");
3971
3972 llvm::FoldingSetNodeID ID;
3973 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003974 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003975 SubstTemplateTypeParmType *SubstParm
3976 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3977
3978 if (!SubstParm) {
3979 SubstParm = new (*this, TypeAlignment)
3980 SubstTemplateTypeParmType(Parm, Replacement);
3981 Types.push_back(SubstParm);
3982 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3983 }
3984
3985 return QualType(SubstParm, 0);
3986}
3987
Fangrui Song6907ce22018-07-30 19:24:48 +00003988/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00003989QualType ASTContext::getSubstTemplateTypeParmPackType(
3990 const TemplateTypeParmType *Parm,
3991 const TemplateArgument &ArgPack) {
3992#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003993 for (const auto &P : ArgPack.pack_elements()) {
3994 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3995 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003996 }
3997#endif
Fangrui Song6907ce22018-07-30 19:24:48 +00003998
Douglas Gregorada4b792011-01-14 02:55:32 +00003999 llvm::FoldingSetNodeID ID;
4000 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00004001 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00004002 if (SubstTemplateTypeParmPackType *SubstParm
4003 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4004 return QualType(SubstParm, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00004005
Douglas Gregorada4b792011-01-14 02:55:32 +00004006 QualType Canon;
4007 if (!Parm->isCanonicalUnqualified()) {
4008 Canon = getCanonicalType(QualType(Parm, 0));
4009 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4010 ArgPack);
4011 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4012 }
4013
Eugene Zelenko7855e772018-04-03 00:11:50 +00004014 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00004015 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4016 ArgPack);
4017 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00004018 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00004019 return QualType(SubstParm, 0);
Douglas Gregorada4b792011-01-14 02:55:32 +00004020}
4021
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004022/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00004023/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00004024/// name.
Mike Stump11289f42009-09-09 15:08:12 +00004025QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00004026 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00004027 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00004028 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00004029 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00004030 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004031 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00004032 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4033
4034 if (TypeParm)
4035 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004036
Chandler Carruth08836322011-05-01 00:51:33 +00004037 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00004038 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00004039 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004040
Fangrui Song6907ce22018-07-30 19:24:48 +00004041 TemplateTypeParmType *TypeCheck
Douglas Gregorc42075a2010-02-04 18:10:26 +00004042 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4043 assert(!TypeCheck && "Template type parameter canonical type broken");
4044 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00004045 } else
John McCall90d1c2d2009-09-24 23:30:46 +00004046 TypeParm = new (*this, TypeAlignment)
4047 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00004048
4049 Types.push_back(TypeParm);
4050 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4051
4052 return QualType(TypeParm, 0);
4053}
4054
John McCalle78aac42010-03-10 03:28:59 +00004055TypeSourceInfo *
4056ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4057 SourceLocation NameLoc,
4058 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004059 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004060 assert(!Name.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004061 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004062 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00004063
4064 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00004065 TemplateSpecializationTypeLoc TL =
4066 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00004067 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00004068 TL.setTemplateNameLoc(NameLoc);
4069 TL.setLAngleLoc(Args.getLAngleLoc());
4070 TL.setRAngleLoc(Args.getRAngleLoc());
4071 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4072 TL.setArgLocInfo(i, Args[i].getLocInfo());
4073 return DI;
4074}
4075
Mike Stump11289f42009-09-09 15:08:12 +00004076QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00004077ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00004078 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004079 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004080 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004081 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00004082
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004083 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004084 ArgVec.reserve(Args.size());
4085 for (const TemplateArgumentLoc &Arg : Args.arguments())
4086 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00004087
David Majnemer6fbeee32016-07-07 04:43:07 +00004088 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00004089}
4090
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004091#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00004092static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4093 for (const TemplateArgument &Arg : Args)
4094 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004095 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004096
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004097 return true;
4098}
4099#endif
4100
John McCall0ad16662009-10-29 08:12:44 +00004101QualType
4102ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00004103 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004104 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004105 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004106 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00004107 // Look through qualified template names.
4108 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4109 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004110
4111 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00004112 Template.getAsTemplateDecl() &&
4113 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004114 QualType CanonType;
4115 if (!Underlying.isNull())
4116 CanonType = getCanonicalType(Underlying);
4117 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004118 // We can get here with an alias template when the specialization contains
4119 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00004120 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004121 "Caller must compute aliased type");
4122 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004123 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00004124 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00004125
Douglas Gregora8e02e72009-07-28 23:00:59 +00004126 // Allocate the (non-canonical) template specialization type, but don't
4127 // try to unique it: these types typically have location information that
4128 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004129 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00004130 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004131 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00004132 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004133 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00004134 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004135 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00004136
Douglas Gregor8bf42052009-02-09 18:46:07 +00004137 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00004138 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00004139}
4140
David Majnemer6fbeee32016-07-07 04:43:07 +00004141QualType ASTContext::getCanonicalTemplateSpecializationType(
4142 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004143 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004144 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004145
Douglas Gregore29139c2011-03-03 17:04:51 +00004146 // Look through qualified template names.
4147 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4148 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004149
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004150 // Build the canonical template specialization type.
4151 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004152 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004153 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004154 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004155 for (const TemplateArgument &Arg : Args)
4156 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004157
4158 // Determine whether this canonical template specialization type already
4159 // exists.
4160 llvm::FoldingSetNodeID ID;
4161 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004162 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004163
Craig Topper36250ad2014-05-12 05:36:57 +00004164 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004165 TemplateSpecializationType *Spec
4166 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4167
4168 if (!Spec) {
4169 // Allocate a new canonical template specialization type.
4170 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4171 sizeof(TemplateArgument) * NumArgs),
4172 TypeAlignment);
4173 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004174 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004175 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004176 Types.push_back(Spec);
4177 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4178 }
4179
4180 assert(Spec->isDependentType() &&
4181 "Non-dependent template-id type must have a canonical type");
4182 return QualType(Spec, 0);
4183}
4184
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004185QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4186 NestedNameSpecifier *NNS,
4187 QualType NamedType,
4188 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004189 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004190 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004191
Craig Topper36250ad2014-05-12 05:36:57 +00004192 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004193 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004194 if (T)
4195 return QualType(T, 0);
4196
Douglas Gregorc42075a2010-02-04 18:10:26 +00004197 QualType Canon = NamedType;
4198 if (!Canon.isCanonical()) {
4199 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004200 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4201 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004202 (void)CheckT;
4203 }
4204
Bruno Riccid6bd5982018-08-16 10:48:16 +00004205 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4206 TypeAlignment);
4207 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4208
Douglas Gregor52537682009-03-19 00:18:19 +00004209 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004210 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004211 return QualType(T, 0);
4212}
4213
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004214QualType
Jay Foad39c79802011-01-12 09:06:06 +00004215ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004216 llvm::FoldingSetNodeID ID;
4217 ParenType::Profile(ID, InnerType);
4218
Craig Topper36250ad2014-05-12 05:36:57 +00004219 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004220 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4221 if (T)
4222 return QualType(T, 0);
4223
4224 QualType Canon = InnerType;
4225 if (!Canon.isCanonical()) {
4226 Canon = getCanonicalType(InnerType);
4227 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4228 assert(!CheckT && "Paren canonical type broken");
4229 (void)CheckT;
4230 }
4231
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004232 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004233 Types.push_back(T);
4234 ParenTypes.InsertNode(T, InsertPos);
4235 return QualType(T, 0);
4236}
4237
Leonard Chanc72aaf62019-05-07 03:20:17 +00004238QualType
4239ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4240 const IdentifierInfo *MacroII) const {
4241 QualType Canon = UnderlyingTy;
4242 if (!Canon.isCanonical())
4243 Canon = getCanonicalType(UnderlyingTy);
4244
4245 auto *newType = new (*this, TypeAlignment)
4246 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4247 Types.push_back(newType);
4248 return QualType(newType, 0);
4249}
4250
Douglas Gregor02085352010-03-31 20:19:30 +00004251QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4252 NestedNameSpecifier *NNS,
4253 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004254 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004255 if (Canon.isNull()) {
4256 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004257 if (CanonNNS != NNS)
4258 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004259 }
4260
4261 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004262 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004263
Craig Topper36250ad2014-05-12 05:36:57 +00004264 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004265 DependentNameType *T
4266 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004267 if (T)
4268 return QualType(T, 0);
4269
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004270 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004271 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004272 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004273 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004274}
4275
Mike Stump11289f42009-09-09 15:08:12 +00004276QualType
John McCallc392f372010-06-11 00:33:02 +00004277ASTContext::getDependentTemplateSpecializationType(
4278 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004279 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004280 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004281 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004282 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004283 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004284 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4285 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004286 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004287}
4288
4289QualType
4290ASTContext::getDependentTemplateSpecializationType(
4291 ElaboratedTypeKeyword Keyword,
4292 NestedNameSpecifier *NNS,
4293 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004294 ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004295 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor6e068012011-02-28 00:04:36 +00004296 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004297
Douglas Gregorc42075a2010-02-04 18:10:26 +00004298 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004299 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004300 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004301
Craig Topper36250ad2014-05-12 05:36:57 +00004302 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004303 DependentTemplateSpecializationType *T
4304 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004305 if (T)
4306 return QualType(T, 0);
4307
John McCallc392f372010-06-11 00:33:02 +00004308 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004309
John McCallc392f372010-06-11 00:33:02 +00004310 ElaboratedTypeKeyword CanonKeyword = Keyword;
4311 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4312
4313 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004314 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004315 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004316 for (unsigned I = 0; I != NumArgs; ++I) {
4317 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4318 if (!CanonArgs[I].structurallyEquals(Args[I]))
4319 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004320 }
4321
John McCallc392f372010-06-11 00:33:02 +00004322 QualType Canon;
4323 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4324 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004325 Name,
4326 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004327
4328 // Find the insert position again.
4329 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4330 }
4331
4332 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4333 sizeof(TemplateArgument) * NumArgs),
4334 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004335 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004336 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004337 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004338 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004339 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004340}
4341
Richard Smith32918772017-02-14 00:25:28 +00004342TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4343 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004344 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004345 QualType ArgType = getTypeDeclType(TTP);
4346 if (TTP->isParameterPack())
4347 ArgType = getPackExpansionType(ArgType, None);
4348
4349 Arg = TemplateArgument(ArgType);
4350 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4351 Expr *E = new (*this) DeclRefExpr(
Bruno Ricci5fc4db72018-12-21 14:10:18 +00004352 *this, NTTP, /*enclosing*/ false,
Richard Smith32918772017-02-14 00:25:28 +00004353 NTTP->getType().getNonLValueExprType(*this),
4354 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4355
4356 if (NTTP->isParameterPack())
4357 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4358 None);
4359 Arg = TemplateArgument(E);
4360 } else {
4361 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4362 if (TTP->isParameterPack())
4363 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4364 else
4365 Arg = TemplateArgument(TemplateName(TTP));
4366 }
4367
4368 if (Param->isTemplateParameterPack())
4369 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4370
4371 return Arg;
4372}
4373
Richard Smith43e14d22016-12-23 02:10:11 +00004374void
4375ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4376 SmallVectorImpl<TemplateArgument> &Args) {
4377 Args.reserve(Args.size() + Params->size());
4378
Richard Smith32918772017-02-14 00:25:28 +00004379 for (NamedDecl *Param : *Params)
4380 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004381}
4382
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004383QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004384 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004385 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004386 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004387
Richard Smithb2997f52019-05-21 20:10:50 +00004388 // A deduced type can deduce to a pack, eg
4389 // auto ...x = some_pack;
4390 // That declaration isn't (yet) valid, but is created as part of building an
4391 // init-capture pack:
4392 // [...x = some_pack] {}
4393 assert((Pattern->containsUnexpandedParameterPack() ||
4394 Pattern->getContainedDeducedType()) &&
Douglas Gregord2fa7662010-12-20 02:24:11 +00004395 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004396 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004397 PackExpansionType *T
4398 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4399 if (T)
4400 return QualType(T, 0);
4401
4402 QualType Canon;
4403 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004404 Canon = getCanonicalType(Pattern);
4405 // The canonical type might not contain an unexpanded parameter pack, if it
4406 // contains an alias template specialization which ignores one of its
4407 // parameters.
4408 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004409 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004410
Richard Smith68eea502012-07-16 00:20:35 +00004411 // Find the insert position again, in case we inserted an element into
4412 // PackExpansionTypes and invalidated our insert position.
4413 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4414 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004415 }
4416
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004417 T = new (*this, TypeAlignment)
4418 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004419 Types.push_back(T);
4420 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004421 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004422}
4423
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004424/// CmpProtocolNames - Comparison predicate for sorting protocols
4425/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004426static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4427 ObjCProtocolDecl *const *RHS) {
4428 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004429}
4430
Craig Topper1f26d5b2016-01-03 19:43:23 +00004431static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4432 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004433
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004434 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4435 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004436
Craig Topper1f26d5b2016-01-03 19:43:23 +00004437 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004438 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004439 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004440 return false;
4441 return true;
4442}
4443
Craig Topper6a8c1512015-10-22 01:56:18 +00004444static void
4445SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004446 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004447 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004448
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004449 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004450 for (ObjCProtocolDecl *&P : Protocols)
4451 P = P->getCanonicalDecl();
4452
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004453 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004454 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4455 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004456}
4457
John McCall8b07ec22010-05-15 11:32:37 +00004458QualType ASTContext::getObjCObjectType(QualType BaseType,
4459 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004460 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004461 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004462 llvm::makeArrayRef(Protocols, NumProtocols),
4463 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004464}
4465
4466QualType ASTContext::getObjCObjectType(
4467 QualType baseType,
4468 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004469 ArrayRef<ObjCProtocolDecl *> protocols,
4470 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004471 // If the base type is an interface and there aren't any protocols or
4472 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004473 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4474 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004475 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004476
4477 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004478 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004479 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004480 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004481 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4482 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004483
Douglas Gregore9d95f12015-07-07 03:57:35 +00004484 // Determine the type arguments to be used for canonicalization,
4485 // which may be explicitly specified here or written on the base
4486 // type.
4487 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4488 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004489 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004490 effectiveTypeArgs = baseObject->getTypeArgs();
4491 }
John McCallfc93cf92009-10-22 22:37:11 +00004492
Douglas Gregore9d95f12015-07-07 03:57:35 +00004493 // Build the canonical type, which has the canonical base type and a
4494 // sorted-and-uniqued list of protocols and the type arguments
4495 // canonicalized.
4496 QualType canonical;
4497 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4498 effectiveTypeArgs.end(),
4499 [&](QualType type) {
4500 return type.isCanonical();
4501 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004502 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004503 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4504 // Determine the canonical type arguments.
4505 ArrayRef<QualType> canonTypeArgs;
4506 SmallVector<QualType, 4> canonTypeArgsVec;
4507 if (!typeArgsAreCanonical) {
4508 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4509 for (auto typeArg : effectiveTypeArgs)
4510 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4511 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004512 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004513 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004514 }
4515
Douglas Gregore9d95f12015-07-07 03:57:35 +00004516 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4517 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4518 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004519 canonProtocolsVec.append(protocols.begin(), protocols.end());
4520 SortAndUniqueProtocols(canonProtocolsVec);
4521 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004522 } else {
4523 canonProtocols = protocols;
4524 }
4525
4526 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004527 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004528
John McCallfc93cf92009-10-22 22:37:11 +00004529 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004530 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4531 }
4532
Douglas Gregore9d95f12015-07-07 03:57:35 +00004533 unsigned size = sizeof(ObjCObjectTypeImpl);
4534 size += typeArgs.size() * sizeof(QualType);
4535 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4536 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004537 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004538 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4539 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004540
4541 Types.push_back(T);
4542 ObjCObjectTypes.InsertNode(T, InsertPos);
4543 return QualType(T, 0);
4544}
4545
Manman Ren3569eb52016-09-13 17:03:12 +00004546/// Apply Objective-C protocol qualifiers to the given type.
4547/// If this is for the canonical type of a type parameter, we can apply
4548/// protocol qualifiers on the ObjCObjectPointerType.
4549QualType
4550ASTContext::applyObjCProtocolQualifiers(QualType type,
4551 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4552 bool allowOnPointerType) const {
4553 hasError = false;
4554
Eugene Zelenko7855e772018-04-03 00:11:50 +00004555 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004556 return getObjCTypeParamType(objT->getDecl(), protocols);
4557 }
4558
Manman Ren3569eb52016-09-13 17:03:12 +00004559 // Apply protocol qualifiers to ObjCObjectPointerType.
4560 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004561 if (const auto *objPtr =
4562 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004563 const ObjCObjectType *objT = objPtr->getObjectType();
4564 // Merge protocol lists and construct ObjCObjectType.
4565 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4566 protocolsVec.append(objT->qual_begin(),
4567 objT->qual_end());
4568 protocolsVec.append(protocols.begin(), protocols.end());
4569 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4570 type = getObjCObjectType(
4571 objT->getBaseType(),
4572 objT->getTypeArgsAsWritten(),
4573 protocols,
4574 objT->isKindOfTypeAsWritten());
4575 return getObjCObjectPointerType(type);
4576 }
4577 }
4578
4579 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004580 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004581 // FIXME: Check for protocols to which the class type is already
4582 // known to conform.
4583
4584 return getObjCObjectType(objT->getBaseType(),
4585 objT->getTypeArgsAsWritten(),
4586 protocols,
4587 objT->isKindOfTypeAsWritten());
4588 }
4589
4590 // If the canonical type is ObjCObjectType, ...
4591 if (type->isObjCObjectType()) {
4592 // Silently overwrite any existing protocol qualifiers.
4593 // TODO: determine whether that's the right thing to do.
4594
4595 // FIXME: Check for protocols to which the class type is already
4596 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004597 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004598 }
4599
4600 // id<protocol-list>
4601 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004602 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004603 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004604 objPtr->isKindOfType());
4605 return getObjCObjectPointerType(type);
4606 }
4607
4608 // Class<protocol-list>
4609 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004610 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004611 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004612 objPtr->isKindOfType());
4613 return getObjCObjectPointerType(type);
4614 }
4615
4616 hasError = true;
4617 return type;
4618}
4619
Manman Rene6be26c2016-09-13 17:25:08 +00004620QualType
4621ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4622 ArrayRef<ObjCProtocolDecl *> protocols,
4623 QualType Canonical) const {
4624 // Look in the folding set for an existing type.
4625 llvm::FoldingSetNodeID ID;
4626 ObjCTypeParamType::Profile(ID, Decl, protocols);
4627 void *InsertPos = nullptr;
4628 if (ObjCTypeParamType *TypeParam =
4629 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4630 return QualType(TypeParam, 0);
4631
4632 if (Canonical.isNull()) {
4633 // We canonicalize to the underlying type.
4634 Canonical = getCanonicalType(Decl->getUnderlyingType());
4635 if (!protocols.empty()) {
4636 // Apply the protocol qualifers.
4637 bool hasError;
Richard Trieua986a312018-08-30 01:57:52 +00004638 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4639 Canonical, protocols, hasError, true /*allowOnPointerType*/));
Manman Rene6be26c2016-09-13 17:25:08 +00004640 assert(!hasError && "Error when apply protocol qualifier to bound type");
4641 }
4642 }
4643
4644 unsigned size = sizeof(ObjCTypeParamType);
4645 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4646 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004647 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004648
4649 Types.push_back(newType);
4650 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4651 return QualType(newType, 0);
4652}
4653
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004654/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4655/// protocol list adopt all protocols in QT's qualified-id protocol
4656/// list.
4657bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4658 ObjCInterfaceDecl *IC) {
4659 if (!QT->isObjCQualifiedIdType())
4660 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004661
Eugene Zelenko7855e772018-04-03 00:11:50 +00004662 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004663 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004664 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004665 if (!IC->ClassImplementsProtocol(Proto, false))
4666 return false;
4667 }
4668 return true;
4669 }
4670 return false;
4671}
4672
4673/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4674/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4675/// of protocols.
4676bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4677 ObjCInterfaceDecl *IDecl) {
4678 if (!QT->isObjCQualifiedIdType())
4679 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004680 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004681 if (!OPT)
4682 return false;
4683 if (!IDecl->hasDefinition())
4684 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004685 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4686 CollectInheritedProtocols(IDecl, InheritedProtocols);
4687 if (InheritedProtocols.empty())
4688 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004689 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004690 // of IDecl's, then bridge casting is ok.
4691 bool Conforms = false;
4692 for (auto *Proto : OPT->quals()) {
4693 Conforms = false;
4694 for (auto *PI : InheritedProtocols) {
4695 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4696 Conforms = true;
4697 break;
4698 }
4699 }
4700 if (!Conforms)
4701 break;
4702 }
4703 if (Conforms)
4704 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004705
Aaron Ballman83731462014-03-17 16:14:00 +00004706 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004707 // If both the right and left sides have qualifiers.
4708 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004709 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004710 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004711 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004712 break;
4713 }
4714 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004715 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004716 }
4717 return true;
4718}
4719
John McCall8b07ec22010-05-15 11:32:37 +00004720/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4721/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004722QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004723 llvm::FoldingSetNodeID ID;
4724 ObjCObjectPointerType::Profile(ID, ObjectT);
4725
Craig Topper36250ad2014-05-12 05:36:57 +00004726 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004727 if (ObjCObjectPointerType *QT =
4728 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4729 return QualType(QT, 0);
4730
4731 // Find the canonical object type.
4732 QualType Canonical;
4733 if (!ObjectT.isCanonical()) {
4734 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4735
4736 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004737 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4738 }
4739
Douglas Gregorf85bee62010-02-08 22:59:26 +00004740 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004741 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004742 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004743 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004744
Steve Narofffb4330f2009-06-17 22:40:22 +00004745 Types.push_back(QType);
4746 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004747 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004748}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004749
Douglas Gregor1c283312010-08-11 12:19:30 +00004750/// getObjCInterfaceType - Return the unique reference to the type for the
4751/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004752QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4753 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004754 if (Decl->TypeForDecl)
4755 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004756
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004757 if (PrevDecl) {
4758 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4759 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4760 return QualType(PrevDecl->TypeForDecl, 0);
4761 }
4762
Douglas Gregor7671e532011-12-16 16:34:57 +00004763 // Prefer the definition, if there is one.
4764 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4765 Decl = Def;
Fangrui Song6907ce22018-07-30 19:24:48 +00004766
Douglas Gregor1c283312010-08-11 12:19:30 +00004767 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004768 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004769 Decl->TypeForDecl = T;
4770 Types.push_back(T);
4771 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004772}
4773
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004774/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4775/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004776/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004777/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004778/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004779QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004780 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004781 if (tofExpr->isTypeDependent()) {
4782 llvm::FoldingSetNodeID ID;
4783 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004784
Craig Topper36250ad2014-05-12 05:36:57 +00004785 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004786 DependentTypeOfExprType *Canon
4787 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4788 if (Canon) {
4789 // We already have a "canonical" version of an identical, dependent
4790 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004791 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004792 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004793 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004794 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004795 Canon
4796 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004797 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4798 toe = Canon;
4799 }
4800 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004801 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004802 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004803 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004804 Types.push_back(toe);
4805 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004806}
4807
Steve Naroffa773cd52007-08-01 18:02:17 +00004808/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004809/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004810/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004811/// an issue. This doesn't affect the type checker, since it operates
4812/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004813QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004814 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004815 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004816 Types.push_back(tot);
4817 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004818}
4819
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004820/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004821/// nodes. This would never be helpful, since each such type has its own
4822/// expression, and would not give a significant memory saving, since there
4823/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004824QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004825 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004826
4827 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004828 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004829 // unique dependent type. Two such decltype-specifiers refer to the same
4830 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004831 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004832 llvm::FoldingSetNodeID ID;
4833 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004834
Craig Topper36250ad2014-05-12 05:36:57 +00004835 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004836 DependentDecltypeType *Canon
4837 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004838 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004839 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004840 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004841 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004842 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004843 dt = new (*this, TypeAlignment)
4844 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004845 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004846 dt = new (*this, TypeAlignment)
4847 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004848 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004849 Types.push_back(dt);
4850 return QualType(dt, 0);
4851}
4852
Alexis Hunte852b102011-05-24 22:41:36 +00004853/// getUnaryTransformationType - We don't unique these, since the memory
4854/// savings are minimal and these are rare.
4855QualType ASTContext::getUnaryTransformType(QualType BaseType,
4856 QualType UnderlyingType,
4857 UnaryTransformType::UTTKind Kind)
4858 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004859 UnaryTransformType *ut = nullptr;
4860
4861 if (BaseType->isDependentType()) {
4862 // Look in the folding set for an existing type.
4863 llvm::FoldingSetNodeID ID;
4864 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4865
4866 void *InsertPos = nullptr;
4867 DependentUnaryTransformType *Canon
4868 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4869
4870 if (!Canon) {
4871 // Build a new, canonical __underlying_type(type) type.
4872 Canon = new (*this, TypeAlignment)
4873 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4874 Kind);
4875 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4876 }
4877 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4878 QualType(), Kind,
4879 QualType(Canon, 0));
4880 } else {
4881 QualType CanonType = getCanonicalType(UnderlyingType);
4882 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4883 UnderlyingType, Kind,
4884 CanonType);
4885 }
4886 Types.push_back(ut);
4887 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004888}
4889
Richard Smith2a7d4812013-05-04 07:00:32 +00004890/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4891/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4892/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004893QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Richard Smithb2997f52019-05-21 20:10:50 +00004894 bool IsDependent, bool IsPack) const {
4895 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
Richard Smithe301ba22015-11-11 02:02:15 +00004896 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004897 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004898
Richard Smith2a7d4812013-05-04 07:00:32 +00004899 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004900 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004901 llvm::FoldingSetNodeID ID;
Richard Smithb2997f52019-05-21 20:10:50 +00004902 AutoType::Profile(ID, DeducedType, Keyword, IsDependent, IsPack);
Richard Smith2a7d4812013-05-04 07:00:32 +00004903 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4904 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004905
Eugene Zelenko7855e772018-04-03 00:11:50 +00004906 auto *AT = new (*this, TypeAlignment)
Richard Smithb2997f52019-05-21 20:10:50 +00004907 AutoType(DeducedType, Keyword, IsDependent, IsPack);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004908 Types.push_back(AT);
4909 if (InsertPos)
4910 AutoTypes.InsertNode(AT, InsertPos);
4911 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004912}
4913
Richard Smith600b5262017-01-26 20:40:47 +00004914/// Return the uniqued reference to the deduced template specialization type
4915/// which has been deduced to the given type, or to the canonical undeduced
4916/// such type, or the canonical deduced-but-dependent such type.
4917QualType ASTContext::getDeducedTemplateSpecializationType(
4918 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4919 // Look in the folding set for an existing type.
4920 void *InsertPos = nullptr;
4921 llvm::FoldingSetNodeID ID;
4922 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4923 IsDependent);
4924 if (DeducedTemplateSpecializationType *DTST =
4925 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4926 return QualType(DTST, 0);
4927
Eugene Zelenko7855e772018-04-03 00:11:50 +00004928 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00004929 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4930 Types.push_back(DTST);
4931 if (InsertPos)
4932 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4933 return QualType(DTST, 0);
4934}
4935
Eli Friedman0dfb8892011-10-06 23:00:33 +00004936/// getAtomicType - Return the uniqued reference to the atomic type for
4937/// the given value type.
4938QualType ASTContext::getAtomicType(QualType T) const {
4939 // Unique pointers, to guarantee there is only one pointer of a particular
4940 // structure.
4941 llvm::FoldingSetNodeID ID;
4942 AtomicType::Profile(ID, T);
4943
Craig Topper36250ad2014-05-12 05:36:57 +00004944 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004945 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4946 return QualType(AT, 0);
4947
4948 // If the atomic value type isn't canonical, this won't be a canonical type
4949 // either, so fill in the canonical type field.
4950 QualType Canonical;
4951 if (!T.isCanonical()) {
4952 Canonical = getAtomicType(getCanonicalType(T));
4953
4954 // Get the new insert position for the node we care about.
4955 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004956 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004957 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00004958 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00004959 Types.push_back(New);
4960 AtomicTypes.InsertNode(New, InsertPos);
4961 return QualType(New, 0);
4962}
4963
Richard Smith02e85f32011-04-14 22:09:26 +00004964/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4965QualType ASTContext::getAutoDeductType() const {
4966 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004967 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004968 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Richard Smithb2997f52019-05-21 20:10:50 +00004969 /*dependent*/false, /*pack*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004970 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004971 return AutoDeductTy;
4972}
4973
4974/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4975QualType ASTContext::getAutoRRefDeductType() const {
4976 if (AutoRRefDeductTy.isNull())
4977 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4978 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4979 return AutoRRefDeductTy;
4980}
4981
Chris Lattnerfb072462007-01-23 05:45:31 +00004982/// getTagDeclType - Return the unique reference to the type for the
4983/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004984QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004985 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004986 // FIXME: What is the design on getTagDeclType when it requires casting
4987 // away const? mutable?
4988 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004989}
4990
Mike Stump11289f42009-09-09 15:08:12 +00004991/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4992/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4993/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004994CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004995 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004996}
Chris Lattnerfb072462007-01-23 05:45:31 +00004997
Fangrui Song6907ce22018-07-30 19:24:48 +00004998/// Return the unique signed counterpart of the integer type
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004999/// corresponding to size_t.
5000CanQualType ASTContext::getSignedSizeType() const {
5001 return getFromTargetType(Target->getSignedSizeType());
5002}
5003
Hans Wennborg27541db2011-10-27 08:29:09 +00005004/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5005CanQualType ASTContext::getIntMaxType() const {
5006 return getFromTargetType(Target->getIntMaxType());
5007}
5008
5009/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5010CanQualType ASTContext::getUIntMaxType() const {
5011 return getFromTargetType(Target->getUIntMaxType());
5012}
5013
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00005014/// getSignedWCharType - Return the type of "signed wchar_t".
5015/// Used when in C++, as a GCC extension.
5016QualType ASTContext::getSignedWCharType() const {
5017 // FIXME: derive from "Target" ?
5018 return WCharTy;
5019}
5020
5021/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5022/// Used when in C++, as a GCC extension.
5023QualType ASTContext::getUnsignedWCharType() const {
5024 // FIXME: derive from "Target" ?
5025 return UnsignedIntTy;
5026}
5027
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00005028QualType ASTContext::getIntPtrType() const {
5029 return getFromTargetType(Target->getIntPtrType());
5030}
5031
5032QualType ASTContext::getUIntPtrType() const {
5033 return getCorrespondingUnsignedType(getIntPtrType());
5034}
5035
Hans Wennborg27541db2011-10-27 08:29:09 +00005036/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005037/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5038QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005039 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005040}
5041
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005042/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00005043/// integer type. The standard (C11 7.21.6.1p7) refers to this type
5044/// in the definition of %tu format specifier.
5045QualType ASTContext::getUnsignedPointerDiffType() const {
5046 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5047}
5048
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005049/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00005050/// <sys/types.h>. We need this to compute the correct type for vfork().
5051QualType ASTContext::getProcessIDType() const {
5052 return getFromTargetType(Target->getProcessIDType());
5053}
5054
Chris Lattnera21ad802008-04-02 05:18:44 +00005055//===----------------------------------------------------------------------===//
5056// Type Operators
5057//===----------------------------------------------------------------------===//
5058
Jay Foad39c79802011-01-12 09:06:06 +00005059CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00005060 // Push qualifiers into arrays, and then discard any remaining
5061 // qualifiers.
5062 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00005063 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00005064 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00005065 QualType Result;
5066 if (isa<ArrayType>(Ty)) {
5067 Result = getArrayDecayedType(QualType(Ty,0));
5068 } else if (isa<FunctionType>(Ty)) {
5069 Result = getPointerType(QualType(Ty, 0));
5070 } else {
5071 Result = QualType(Ty, 0);
5072 }
5073
5074 return CanQualType::CreateUnsafe(Result);
5075}
5076
John McCall6c9dd522011-01-18 07:41:22 +00005077QualType ASTContext::getUnqualifiedArrayType(QualType type,
5078 Qualifiers &quals) {
5079 SplitQualType splitType = type.getSplitUnqualifiedType();
5080
5081 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5082 // the unqualified desugared type and then drops it on the floor.
5083 // We then have to strip that sugar back off with
5084 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005085 const auto *AT =
5086 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00005087
5088 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005089 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00005090 quals = splitType.Quals;
5091 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005092 }
5093
John McCall6c9dd522011-01-18 07:41:22 +00005094 // Otherwise, recurse on the array's element type.
5095 QualType elementType = AT->getElementType();
5096 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5097
5098 // If that didn't change the element type, AT has no qualifiers, so we
5099 // can just use the results in splitType.
5100 if (elementType == unqualElementType) {
5101 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00005102 quals = splitType.Quals;
5103 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00005104 }
5105
5106 // Otherwise, add in the qualifiers from the outermost type, then
5107 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00005108 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005109
Eugene Zelenko7855e772018-04-03 00:11:50 +00005110 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005111 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005112 CAT->getSizeModifier(), 0);
5113 }
5114
Eugene Zelenko7855e772018-04-03 00:11:50 +00005115 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005116 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005117 }
5118
Eugene Zelenko7855e772018-04-03 00:11:50 +00005119 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005120 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00005121 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005122 VAT->getSizeModifier(),
5123 VAT->getIndexTypeCVRQualifiers(),
5124 VAT->getBracketsRange());
5125 }
5126
Eugene Zelenko7855e772018-04-03 00:11:50 +00005127 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00005128 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005129 DSAT->getSizeModifier(), 0,
5130 SourceRange());
5131}
5132
Richard Smitha3405ff2018-07-11 00:19:19 +00005133/// Attempt to unwrap two types that may both be array types with the same bound
5134/// (or both be array types of unknown bound) for the purpose of comparing the
5135/// cv-decomposition of two types per C++ [conv.qual].
Richard Smith5407d4f2018-07-18 20:13:36 +00005136bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5137 bool UnwrappedAny = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00005138 while (true) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005139 auto *AT1 = getAsArrayType(T1);
5140 if (!AT1) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005141
Richard Smith5407d4f2018-07-18 20:13:36 +00005142 auto *AT2 = getAsArrayType(T2);
5143 if (!AT2) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005144
5145 // If we don't have two array types with the same constant bound nor two
5146 // incomplete array types, we've unwrapped everything we can.
5147 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5148 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5149 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
Richard Smith5407d4f2018-07-18 20:13:36 +00005150 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005151 } else if (!isa<IncompleteArrayType>(AT1) ||
5152 !isa<IncompleteArrayType>(AT2)) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005153 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005154 }
5155
5156 T1 = AT1->getElementType();
5157 T2 = AT2->getElementType();
Richard Smith5407d4f2018-07-18 20:13:36 +00005158 UnwrappedAny = true;
Richard Smitha3405ff2018-07-11 00:19:19 +00005159 }
5160}
5161
5162/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5163///
5164/// If T1 and T2 are both pointer types of the same kind, or both array types
5165/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5166/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5167///
5168/// This function will typically be called in a loop that successively
5169/// "unwraps" pointer and pointer-to-member types to compare them at each
5170/// level.
5171///
5172/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5173/// pair of types that can't be unwrapped further.
5174bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005175 UnwrapSimilarArrayTypes(T1, T2);
Richard Smitha3405ff2018-07-11 00:19:19 +00005176
Eugene Zelenko7855e772018-04-03 00:11:50 +00005177 const auto *T1PtrType = T1->getAs<PointerType>();
5178 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005179 if (T1PtrType && T2PtrType) {
5180 T1 = T1PtrType->getPointeeType();
5181 T2 = T2PtrType->getPointeeType();
5182 return true;
5183 }
Richard Smith5407d4f2018-07-18 20:13:36 +00005184
Eugene Zelenko7855e772018-04-03 00:11:50 +00005185 const auto *T1MPType = T1->getAs<MemberPointerType>();
5186 const auto *T2MPType = T2->getAs<MemberPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00005187 if (T1MPType && T2MPType &&
5188 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005189 QualType(T2MPType->getClass(), 0))) {
5190 T1 = T1MPType->getPointeeType();
5191 T2 = T2MPType->getPointeeType();
5192 return true;
5193 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005194
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005195 if (getLangOpts().ObjC) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005196 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5197 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005198 if (T1OPType && T2OPType) {
5199 T1 = T1OPType->getPointeeType();
5200 T2 = T2OPType->getPointeeType();
5201 return true;
5202 }
5203 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005204
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005205 // FIXME: Block pointers, too?
Fangrui Song6907ce22018-07-30 19:24:48 +00005206
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005207 return false;
5208}
5209
Richard Smitha3405ff2018-07-11 00:19:19 +00005210bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5211 while (true) {
5212 Qualifiers Quals;
5213 T1 = getUnqualifiedArrayType(T1, Quals);
5214 T2 = getUnqualifiedArrayType(T2, Quals);
5215 if (hasSameType(T1, T2))
5216 return true;
5217 if (!UnwrapSimilarTypes(T1, T2))
5218 return false;
5219 }
5220}
5221
5222bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5223 while (true) {
5224 Qualifiers Quals1, Quals2;
5225 T1 = getUnqualifiedArrayType(T1, Quals1);
5226 T2 = getUnqualifiedArrayType(T2, Quals2);
5227
5228 Quals1.removeCVRQualifiers();
5229 Quals2.removeCVRQualifiers();
5230 if (Quals1 != Quals2)
5231 return false;
5232
5233 if (hasSameType(T1, T2))
5234 return true;
5235
5236 if (!UnwrapSimilarTypes(T1, T2))
5237 return false;
5238 }
5239}
5240
Jay Foad39c79802011-01-12 09:06:06 +00005241DeclarationNameInfo
5242ASTContext::getNameForTemplate(TemplateName Name,
5243 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005244 switch (Name.getKind()) {
5245 case TemplateName::QualifiedTemplate:
5246 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005247 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005248 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5249 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005250
John McCalld9dfe3a2011-06-30 08:33:18 +00005251 case TemplateName::OverloadedTemplate: {
5252 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5253 // DNInfo work in progress: CHECKME: what about DNLoc?
5254 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5255 }
5256
Richard Smithb23c5e82019-05-09 03:31:27 +00005257 case TemplateName::AssumedTemplate: {
5258 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5259 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5260 }
5261
John McCalld9dfe3a2011-06-30 08:33:18 +00005262 case TemplateName::DependentTemplate: {
5263 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005264 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005265 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005266 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5267 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005268 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005269 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5270 // DNInfo work in progress: FIXME: source locations?
5271 DeclarationNameLoc DNLoc;
5272 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5273 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5274 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005275 }
5276 }
5277
John McCalld9dfe3a2011-06-30 08:33:18 +00005278 case TemplateName::SubstTemplateTemplateParm: {
5279 SubstTemplateTemplateParmStorage *subst
5280 = Name.getAsSubstTemplateTemplateParm();
5281 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5282 NameLoc);
5283 }
5284
5285 case TemplateName::SubstTemplateTemplateParmPack: {
5286 SubstTemplateTemplateParmPackStorage *subst
5287 = Name.getAsSubstTemplateTemplateParmPack();
5288 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5289 NameLoc);
5290 }
5291 }
5292
5293 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005294}
5295
Jay Foad39c79802011-01-12 09:06:06 +00005296TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005297 switch (Name.getKind()) {
5298 case TemplateName::QualifiedTemplate:
5299 case TemplateName::Template: {
5300 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005301 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005302 Template = getCanonicalTemplateTemplateParmDecl(TTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00005303
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005304 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005305 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005306 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005307
John McCalld9dfe3a2011-06-30 08:33:18 +00005308 case TemplateName::OverloadedTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00005309 case TemplateName::AssumedTemplate:
5310 llvm_unreachable("cannot canonicalize unresolved template");
Mike Stump11289f42009-09-09 15:08:12 +00005311
John McCalld9dfe3a2011-06-30 08:33:18 +00005312 case TemplateName::DependentTemplate: {
5313 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5314 assert(DTN && "Non-dependent template names must refer to template decls.");
5315 return DTN->CanonicalTemplateName;
5316 }
5317
5318 case TemplateName::SubstTemplateTemplateParm: {
5319 SubstTemplateTemplateParmStorage *subst
5320 = Name.getAsSubstTemplateTemplateParm();
5321 return getCanonicalTemplateName(subst->getReplacement());
5322 }
5323
5324 case TemplateName::SubstTemplateTemplateParmPack: {
5325 SubstTemplateTemplateParmPackStorage *subst
5326 = Name.getAsSubstTemplateTemplateParmPack();
5327 TemplateTemplateParmDecl *canonParameter
5328 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5329 TemplateArgument canonArgPack
5330 = getCanonicalTemplateArgument(subst->getArgumentPack());
5331 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5332 }
5333 }
5334
5335 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005336}
5337
Douglas Gregoradee3e32009-11-11 23:06:43 +00005338bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5339 X = getCanonicalTemplateName(X);
5340 Y = getCanonicalTemplateName(Y);
5341 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5342}
5343
Mike Stump11289f42009-09-09 15:08:12 +00005344TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005345ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005346 switch (Arg.getKind()) {
5347 case TemplateArgument::Null:
5348 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005349
Douglas Gregora8e02e72009-07-28 23:00:59 +00005350 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005351 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005352
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005353 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005354 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005355 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005356 }
Mike Stump11289f42009-09-09 15:08:12 +00005357
Eli Friedmanb826a002012-09-26 02:36:12 +00005358 case TemplateArgument::NullPtr:
5359 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5360 /*isNullPtr*/true);
5361
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005362 case TemplateArgument::Template:
5363 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005364
5365 case TemplateArgument::TemplateExpansion:
5366 return TemplateArgument(getCanonicalTemplateName(
5367 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005368 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005369
Douglas Gregora8e02e72009-07-28 23:00:59 +00005370 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005371 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005372
Douglas Gregora8e02e72009-07-28 23:00:59 +00005373 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005374 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005375
Douglas Gregora8e02e72009-07-28 23:00:59 +00005376 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005377 if (Arg.pack_size() == 0)
5378 return Arg;
Fangrui Song6907ce22018-07-30 19:24:48 +00005379
Eugene Zelenko7855e772018-04-03 00:11:50 +00005380 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005381 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005382 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005383 AEnd = Arg.pack_end();
5384 A != AEnd; (void)++A, ++Idx)
5385 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005386
Benjamin Kramercce63472015-08-05 09:40:22 +00005387 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005388 }
5389 }
5390
5391 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005392 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005393}
5394
Douglas Gregor333489b2009-03-27 23:10:48 +00005395NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005396ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005397 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005398 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005399
5400 switch (NNS->getKind()) {
5401 case NestedNameSpecifier::Identifier:
5402 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005403 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005404 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5405 NNS->getAsIdentifier());
5406
5407 case NestedNameSpecifier::Namespace:
5408 // A namespace is canonical; build a nested-name-specifier with
5409 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005410 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005411 NNS->getAsNamespace()->getOriginalNamespace());
5412
5413 case NestedNameSpecifier::NamespaceAlias:
5414 // A namespace is canonical; build a nested-name-specifier with
5415 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005416 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005417 NNS->getAsNamespaceAlias()->getNamespace()
5418 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005419
5420 case NestedNameSpecifier::TypeSpec:
5421 case NestedNameSpecifier::TypeSpecWithTemplate: {
5422 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Fangrui Song6907ce22018-07-30 19:24:48 +00005423
Douglas Gregor3ade5702010-11-04 00:09:33 +00005424 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5425 // break it apart into its prefix and identifier, then reconsititute those
5426 // as the canonical nested-name-specifier. This is required to canonicalize
5427 // a dependent nested-name-specifier involving typedefs of dependent-name
5428 // types, e.g.,
5429 // typedef typename T::type T1;
5430 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005431 if (const auto *DNT = T->getAs<DependentNameType>())
Fangrui Song6907ce22018-07-30 19:24:48 +00005432 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005433 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005434
Eli Friedman5358a0a2012-03-03 04:09:56 +00005435 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5436 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5437 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005438 return NestedNameSpecifier::Create(*this, nullptr, false,
5439 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005440 }
5441
5442 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005443 case NestedNameSpecifier::Super:
5444 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005445 return NNS;
5446 }
5447
David Blaikie8a40f702012-01-17 06:56:22 +00005448 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005449}
5450
Jay Foad39c79802011-01-12 09:06:06 +00005451const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005452 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005453 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005454 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005455 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005456 return AT;
5457 }
Mike Stump11289f42009-09-09 15:08:12 +00005458
John McCall8ccfcb52009-09-24 19:53:00 +00005459 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005460 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005461 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005462
John McCall8ccfcb52009-09-24 19:53:00 +00005463 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005464 // implements C99 6.7.3p8: "If the specification of an array type includes
5465 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005466
Chris Lattner7adf0762008-08-04 07:31:14 +00005467 // If we get here, we either have type qualifiers on the type, or we have
5468 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005469 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005470
John McCall33ddac02011-01-19 10:06:00 +00005471 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005472 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005473
Chris Lattner7adf0762008-08-04 07:31:14 +00005474 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005475 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005476 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005477 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005478
Chris Lattner7adf0762008-08-04 07:31:14 +00005479 // Otherwise, we have an array and we have qualifiers on it. Push the
5480 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005481 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005482
Eugene Zelenko7855e772018-04-03 00:11:50 +00005483 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005484 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5485 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005486 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005487 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005488 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5489 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005490 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005491
Eugene Zelenko7855e772018-04-03 00:11:50 +00005492 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005493 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005494 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005495 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005496 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005497 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005498 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005499
Eugene Zelenko7855e772018-04-03 00:11:50 +00005500 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005501 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005502 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005503 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005504 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005505 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005506}
5507
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005508QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005509 if (T->isArrayType() || T->isFunctionType())
5510 return getDecayedType(T);
5511 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005512}
5513
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005514QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005515 T = getVariableArrayDecayedType(T);
5516 T = getAdjustedParameterType(T);
5517 return T.getUnqualifiedType();
5518}
5519
David Majnemerd09a51c2015-03-03 01:50:05 +00005520QualType ASTContext::getExceptionObjectType(QualType T) const {
5521 // C++ [except.throw]p3:
5522 // A throw-expression initializes a temporary object, called the exception
5523 // object, the type of which is determined by removing any top-level
5524 // cv-qualifiers from the static type of the operand of throw and adjusting
5525 // the type from "array of T" or "function returning T" to "pointer to T"
5526 // or "pointer to function returning T", [...]
5527 T = getVariableArrayDecayedType(T);
5528 if (T->isArrayType() || T->isFunctionType())
5529 T = getDecayedType(T);
5530 return T.getUnqualifiedType();
5531}
5532
Chris Lattnera21ad802008-04-02 05:18:44 +00005533/// getArrayDecayedType - Return the properly qualified result of decaying the
5534/// specified array type to a pointer. This operation is non-trivial when
5535/// handling typedefs etc. The canonical type of "T" must be an array type,
5536/// this returns a pointer to a properly qualified element of the array.
5537///
5538/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005539QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005540 // Get the element type with 'getAsArrayType' so that we don't lose any
5541 // typedefs in the element type of the array. This also handles propagation
5542 // of type qualifiers from the array type into the element type if present
5543 // (C99 6.7.3p8).
5544 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5545 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005546
Chris Lattner7adf0762008-08-04 07:31:14 +00005547 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005548
5549 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005550 QualType Result = getQualifiedType(PtrTy,
5551 PrettyArrayType->getIndexTypeQualifiers());
5552
5553 // int x[_Nullable] -> int * _Nullable
5554 if (auto Nullability = Ty->getNullability(*this)) {
5555 Result = const_cast<ASTContext *>(this)->getAttributedType(
5556 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5557 }
5558 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005559}
5560
John McCall33ddac02011-01-19 10:06:00 +00005561QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5562 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005563}
5564
John McCall33ddac02011-01-19 10:06:00 +00005565QualType ASTContext::getBaseElementType(QualType type) const {
5566 Qualifiers qs;
5567 while (true) {
5568 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005569 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005570 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005571
John McCall33ddac02011-01-19 10:06:00 +00005572 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005573 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005574 }
Mike Stump11289f42009-09-09 15:08:12 +00005575
John McCall33ddac02011-01-19 10:06:00 +00005576 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005577}
5578
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005579/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005580uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005581ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5582 uint64_t ElementCount = 1;
5583 do {
5584 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005585 CA = dyn_cast_or_null<ConstantArrayType>(
5586 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005587 } while (CA);
5588 return ElementCount;
5589}
5590
Steve Naroff0af91202007-04-27 21:51:21 +00005591/// getFloatingRank - Return a relative rank for floating point types.
5592/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005593static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005594 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005595 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005596
John McCall9dd450b2009-09-21 23:43:11 +00005597 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5598 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005599 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005600 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005601 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005602 case BuiltinType::Float: return FloatRank;
5603 case BuiltinType::Double: return DoubleRank;
5604 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005605 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005606 }
5607}
5608
Mike Stump11289f42009-09-09 15:08:12 +00005609/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5610/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005611/// 'typeDomain' is a real floating point or complex type.
5612/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005613QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5614 QualType Domain) const {
5615 FloatingRank EltRank = getFloatingRank(Size);
5616 if (Domain->isComplexType()) {
5617 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005618 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005619 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005620 case FloatRank: return FloatComplexTy;
5621 case DoubleRank: return DoubleComplexTy;
5622 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005623 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005624 }
Steve Naroff0af91202007-04-27 21:51:21 +00005625 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005626
5627 assert(Domain->isRealFloatingType() && "Unknown domain!");
5628 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005629 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005630 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005631 case FloatRank: return FloatTy;
5632 case DoubleRank: return DoubleTy;
5633 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005634 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005635 }
David Blaikief47fa302012-01-17 02:30:50 +00005636 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005637}
5638
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005639/// getFloatingTypeOrder - Compare the rank of the two specified floating
5640/// point types, ignoring the domain of the type (i.e. 'double' ==
5641/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005642/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005643int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005644 FloatingRank LHSR = getFloatingRank(LHS);
5645 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005646
Chris Lattnerb90739d2008-04-06 23:38:49 +00005647 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005648 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005649 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005650 return 1;
5651 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005652}
5653
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +00005654int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
5655 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
5656 return 0;
5657 return getFloatingTypeOrder(LHS, RHS);
5658}
5659
Chris Lattner76a00cf2008-04-06 22:59:24 +00005660/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5661/// routine will assert if passed a built-in type that isn't an integer or enum,
5662/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005663unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005664 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005665
Chris Lattner76a00cf2008-04-06 22:59:24 +00005666 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005667 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005668 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005669 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005670 case BuiltinType::Char_S:
5671 case BuiltinType::Char_U:
5672 case BuiltinType::SChar:
5673 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005674 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005675 case BuiltinType::Short:
5676 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005677 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005678 case BuiltinType::Int:
5679 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005680 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005681 case BuiltinType::Long:
5682 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005683 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005684 case BuiltinType::LongLong:
5685 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005686 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005687 case BuiltinType::Int128:
5688 case BuiltinType::UInt128:
5689 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005690 }
5691}
5692
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005693/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005694/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5695///
5696/// \returns the type this bit-field will promote to, or NULL if no
5697/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005698QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005699 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005700 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005701
Richard Smithaadb2542018-06-28 21:17:55 +00005702 // C++ [conv.prom]p5:
5703 // If the bit-field has an enumerated type, it is treated as any other
5704 // value of that type for promotion purposes.
5705 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5706 return {};
5707
Richard Smith5b571672014-09-24 23:55:00 +00005708 // FIXME: We should not do this unless E->refersToBitField() is true. This
5709 // matters in C where getSourceBitField() will find bit-fields for various
5710 // cases where the source expression is not a bit-field designator.
5711
John McCalld25db7e2013-05-06 21:39:12 +00005712 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005713 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005714 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005715
5716 QualType FT = Field->getType();
5717
Richard Smithcaf33902011-10-10 18:28:20 +00005718 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005719 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005720 // C++ [conv.prom]p5:
5721 // A prvalue for an integral bit-field can be converted to a prvalue of type
5722 // int if int can represent all the values of the bit-field; otherwise, it
5723 // can be converted to unsigned int if unsigned int can represent all the
5724 // values of the bit-field. If the bit-field is larger yet, no integral
5725 // promotion applies to it.
5726 // C11 6.3.1.1/2:
5727 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5728 // If an int can represent all values of the original type (as restricted by
5729 // the width, for a bit-field), the value is converted to an int; otherwise,
5730 // it is converted to an unsigned int.
5731 //
5732 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5733 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005734 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5735 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005736 if (BitWidth < IntSize)
5737 return IntTy;
5738
5739 if (BitWidth == IntSize)
5740 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5741
Richard Smithaadb2542018-06-28 21:17:55 +00005742 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005743 // like the base type. GCC has some weird bugs in this area that we
5744 // deliberately do not follow (GCC follows a pre-standard resolution to
5745 // C's DR315 which treats bit-width as being part of the type, and this leaks
5746 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005747 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005748}
5749
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005750/// getPromotedIntegerType - Returns the type that Promotable will
5751/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5752/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005753QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005754 assert(!Promotable.isNull());
5755 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005756 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005757 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005758
Eugene Zelenko7855e772018-04-03 00:11:50 +00005759 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005760 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5761 // (3.9.1) can be converted to a prvalue of the first of the following
5762 // types that can represent all the values of its underlying type:
5763 // int, unsigned int, long int, unsigned long int, long long int, or
5764 // unsigned long long int [...]
5765 // FIXME: Is there some better way to compute this?
5766 if (BT->getKind() == BuiltinType::WChar_S ||
5767 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005768 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005769 BT->getKind() == BuiltinType::Char16 ||
5770 BT->getKind() == BuiltinType::Char32) {
5771 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5772 uint64_t FromSize = getTypeSize(BT);
5773 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5774 LongLongTy, UnsignedLongLongTy };
5775 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5776 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5777 if (FromSize < ToSize ||
5778 (FromSize == ToSize &&
5779 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5780 return PromoteTypes[Idx];
5781 }
5782 llvm_unreachable("char type should fit into long long");
5783 }
5784 }
5785
5786 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005787 if (Promotable->isSignedIntegerType())
5788 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005789 uint64_t PromotableSize = getIntWidth(Promotable);
5790 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005791 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5792 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5793}
5794
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005795/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005796/// type and returns its ownership.
5797Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5798 while (!T.isNull()) {
5799 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5800 return T.getObjCLifetime();
5801 if (T->isArrayType())
5802 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005803 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005804 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005805 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005806 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005807 else
5808 break;
5809 }
5810
5811 return Qualifiers::OCL_None;
5812}
5813
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005814static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5815 // Incomplete enum types are not treated as integer types.
5816 // FIXME: In C++, enum types are never integer types.
5817 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5818 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005819 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005820}
5821
Mike Stump11289f42009-09-09 15:08:12 +00005822/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005823/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005824/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005825int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005826 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5827 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005828
5829 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005830 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005831 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005832 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005833 RHSC = getIntegerTypeForEnum(ET);
5834
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005835 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005836
Chris Lattner76a00cf2008-04-06 22:59:24 +00005837 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5838 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005839
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005840 unsigned LHSRank = getIntegerRank(LHSC);
5841 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005842
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005843 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5844 if (LHSRank == RHSRank) return 0;
5845 return LHSRank > RHSRank ? 1 : -1;
5846 }
Mike Stump11289f42009-09-09 15:08:12 +00005847
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005848 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5849 if (LHSUnsigned) {
5850 // If the unsigned [LHS] type is larger, return it.
5851 if (LHSRank >= RHSRank)
5852 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005853
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005854 // If the signed type can represent all values of the unsigned type, it
5855 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005856 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005857 return -1;
5858 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005859
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005860 // If the unsigned [RHS] type is larger, return it.
5861 if (RHSRank >= LHSRank)
5862 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005863
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005864 // If the signed type can represent all values of the unsigned type, it
5865 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005866 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005867 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005868}
Anders Carlsson98f07902007-08-17 05:31:46 +00005869
Ben Langmuirf5416742016-02-04 00:55:24 +00005870TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005871 if (CFConstantStringTypeDecl)
5872 return CFConstantStringTypeDecl;
Anders Carlsson6d417272009-11-14 21:45:58 +00005873
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005874 assert(!CFConstantStringTagDecl &&
5875 "tag and typedef should be initialized together");
5876 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5877 CFConstantStringTagDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00005878
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005879 struct {
5880 QualType Type;
5881 const char *Name;
5882 } Fields[5];
5883 unsigned Count = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005884
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005885 /// Objective-C ABI
5886 ///
5887 /// typedef struct __NSConstantString_tag {
Saleem Abdulrasool1f6c41f2018-10-27 06:12:52 +00005888 /// const int *isa;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005889 /// int flags;
5890 /// const char *str;
5891 /// long length;
5892 /// } __NSConstantString;
5893 ///
5894 /// Swift ABI (4.1, 4.2)
5895 ///
5896 /// typedef struct __NSConstantString_tag {
5897 /// uintptr_t _cfisa;
5898 /// uintptr_t _swift_rc;
5899 /// _Atomic(uint64_t) _cfinfoa;
5900 /// const char *_ptr;
5901 /// uint32_t _length;
5902 /// } __NSConstantString;
5903 ///
5904 /// Swift ABI (5.0)
5905 ///
5906 /// typedef struct __NSConstantString_tag {
5907 /// uintptr_t _cfisa;
5908 /// uintptr_t _swift_rc;
5909 /// _Atomic(uint64_t) _cfinfoa;
5910 /// const char *_ptr;
5911 /// uintptr_t _length;
5912 /// } __NSConstantString;
5913
5914 const auto CFRuntime = getLangOpts().CFRuntime;
5915 if (static_cast<unsigned>(CFRuntime) <
5916 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
5917 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
5918 Fields[Count++] = { IntTy, "flags" };
5919 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
5920 Fields[Count++] = { LongTy, "length" };
5921 } else {
5922 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
5923 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
5924 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
5925 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
5926 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5927 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5928 Fields[Count++] = { IntTy, "_ptr" };
5929 else
5930 Fields[Count++] = { getUIntPtrType(), "_ptr" };
5931 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005932
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005933 // Create fields
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005934 for (unsigned i = 0; i < Count; ++i) {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005935 FieldDecl *Field =
5936 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005937 SourceLocation(), &Idents.get(Fields[i].Name),
5938 Fields[i].Type, /*TInfo=*/nullptr,
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005939 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5940 Field->setAccess(AS_public);
5941 CFConstantStringTagDecl->addDecl(Field);
Anders Carlsson98f07902007-08-17 05:31:46 +00005942 }
Mike Stump11289f42009-09-09 15:08:12 +00005943
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005944 CFConstantStringTagDecl->completeDefinition();
5945 // This type is designed to be compatible with NSConstantString, but cannot
5946 // use the same name, since NSConstantString is an interface.
5947 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5948 CFConstantStringTypeDecl =
5949 buildImplicitTypedef(tagType, "__NSConstantString");
5950
Quentin Colombet043406b2016-02-03 22:41:00 +00005951 return CFConstantStringTypeDecl;
5952}
5953
Ben Langmuirf5416742016-02-04 00:55:24 +00005954RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5955 if (!CFConstantStringTagDecl)
5956 getCFConstantStringDecl(); // Build the tag and the typedef.
5957 return CFConstantStringTagDecl;
5958}
5959
Quentin Colombet043406b2016-02-03 22:41:00 +00005960// getCFConstantStringType - Return the type used for constant CFStrings.
5961QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005962 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005963}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005964
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005965QualType ASTContext::getObjCSuperType() const {
5966 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005967 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005968 TUDecl->addDecl(ObjCSuperTypeDecl);
5969 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5970 }
5971 return ObjCSuperType;
5972}
5973
Douglas Gregor512b0772009-04-23 22:29:11 +00005974void ASTContext::setCFConstantStringType(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005975 const auto *TD = T->getAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00005976 assert(TD && "Invalid CFConstantStringType");
5977 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005978 const auto *TagType =
Ben Langmuirf5416742016-02-04 00:55:24 +00005979 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5980 assert(TagType && "Invalid CFConstantStringType");
5981 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005982}
5983
Jay Foad39c79802011-01-12 09:06:06 +00005984QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005985 if (BlockDescriptorType)
5986 return getTagDeclType(BlockDescriptorType);
5987
Alp Toker2dea15b2013-12-17 01:22:38 +00005988 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005989 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005990 RD = buildImplicitRecord("__block_descriptor");
5991 RD->startDefinition();
5992
Mike Stumpd0153282009-10-20 02:12:22 +00005993 QualType FieldTypes[] = {
5994 UnsignedLongTy,
5995 UnsignedLongTy,
5996 };
5997
Craig Topperd6d31ac2013-07-15 08:24:27 +00005998 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005999 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006000 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00006001 };
6002
6003 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006004 FieldDecl *Field = FieldDecl::Create(
6005 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006006 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6007 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006008 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006009 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00006010 }
6011
Alp Toker2dea15b2013-12-17 01:22:38 +00006012 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00006013
Alp Toker2dea15b2013-12-17 01:22:38 +00006014 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00006015
6016 return getTagDeclType(BlockDescriptorType);
6017}
6018
Jay Foad39c79802011-01-12 09:06:06 +00006019QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006020 if (BlockDescriptorExtendedType)
6021 return getTagDeclType(BlockDescriptorExtendedType);
6022
Alp Toker2dea15b2013-12-17 01:22:38 +00006023 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006024 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00006025 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6026 RD->startDefinition();
6027
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006028 QualType FieldTypes[] = {
6029 UnsignedLongTy,
6030 UnsignedLongTy,
6031 getPointerType(VoidPtrTy),
6032 getPointerType(VoidPtrTy)
6033 };
6034
Craig Topperd6d31ac2013-07-15 08:24:27 +00006035 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006036 "reserved",
6037 "Size",
6038 "CopyFuncPtr",
6039 "DestroyFuncPtr"
6040 };
6041
6042 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006043 FieldDecl *Field = FieldDecl::Create(
6044 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006045 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6046 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00006047 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006048 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006049 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006050 }
6051
Alp Toker2dea15b2013-12-17 01:22:38 +00006052 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006053
Alp Toker2dea15b2013-12-17 01:22:38 +00006054 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006055 return getTagDeclType(BlockDescriptorExtendedType);
6056}
6057
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006058TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006059 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006060
6061 if (!BT) {
6062 if (isa<PipeType>(T))
6063 return TargetInfo::OCLTK_Pipe;
6064
6065 return TargetInfo::OCLTK_Default;
6066 }
6067
6068 switch (BT->getKind()) {
6069#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6070 case BuiltinType::Id: \
6071 return TargetInfo::OCLTK_Image;
6072#include "clang/Basic/OpenCLImageTypes.def"
6073
6074 case BuiltinType::OCLClkEvent:
6075 return TargetInfo::OCLTK_ClkEvent;
6076
6077 case BuiltinType::OCLEvent:
6078 return TargetInfo::OCLTK_Event;
6079
6080 case BuiltinType::OCLQueue:
6081 return TargetInfo::OCLTK_Queue;
6082
6083 case BuiltinType::OCLReserveID:
6084 return TargetInfo::OCLTK_ReserveID;
6085
6086 case BuiltinType::OCLSampler:
6087 return TargetInfo::OCLTK_Sampler;
6088
6089 default:
6090 return TargetInfo::OCLTK_Default;
6091 }
6092}
6093
6094LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6095 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6096}
6097
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006098/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6099/// requires copy/dispose. Note that this must match the logic
6100/// in buildByrefHelpers.
6101bool ASTContext::BlockRequiresCopying(QualType Ty,
6102 const VarDecl *D) {
6103 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00006104 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006105 if (!copyExpr && record->hasTrivialDestructor()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006106
Mike Stump94967902009-10-21 18:16:27 +00006107 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00006108 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006109
Akira Hatanaka7275da02018-02-28 07:15:55 +00006110 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6111 // move or destroy.
6112 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6113 return true;
6114
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006115 if (!Ty->isObjCRetainableType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006116
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006117 Qualifiers qs = Ty.getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00006118
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006119 // If we have lifetime, that dominates.
6120 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006121 switch (lifetime) {
6122 case Qualifiers::OCL_None: llvm_unreachable("impossible");
Fangrui Song6907ce22018-07-30 19:24:48 +00006123
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006124 // These are just bits as far as the runtime is concerned.
6125 case Qualifiers::OCL_ExplicitNone:
6126 case Qualifiers::OCL_Autoreleasing:
6127 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00006128
6129 // These cases should have been taken care of when checking the type's
6130 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006131 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006132 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00006133 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006134 }
6135 llvm_unreachable("fell out of lifetime switch!");
6136 }
6137 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6138 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00006139}
6140
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006141bool ASTContext::getByrefLifetime(QualType Ty,
6142 Qualifiers::ObjCLifetime &LifeTime,
6143 bool &HasByrefExtendedLayout) const {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00006144 if (!getLangOpts().ObjC ||
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006145 getLangOpts().getGC() != LangOptions::NonGC)
6146 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006147
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006148 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00006149 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006150 HasByrefExtendedLayout = true;
6151 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006152 } else if ((LifeTime = Ty.getObjCLifetime())) {
6153 // Honor the ARC qualifiers.
6154 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6155 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006156 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00006157 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006158 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006159 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006160 return true;
6161}
6162
Douglas Gregorbab8a962011-09-08 01:46:34 +00006163TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6164 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00006165 ObjCInstanceTypeDecl =
6166 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00006167 return ObjCInstanceTypeDecl;
6168}
6169
Anders Carlsson18acd442007-10-29 06:33:42 +00006170// This returns true if a type has been typedefed to BOOL:
6171// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00006172static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006173 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00006174 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6175 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00006176
Anders Carlssond8499822007-10-29 05:01:08 +00006177 return false;
6178}
6179
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006180/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006181/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00006182CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00006183 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6184 return CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00006185
Ken Dyck40775002010-01-11 17:06:35 +00006186 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00006187
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006188 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00006189 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00006190 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006191 // Treat arrays as pointers, since that's how they're passed in.
6192 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00006193 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00006194 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00006195}
6196
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006197bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00006198 return getTargetInfo().getCXXABI().isMicrosoft() &&
6199 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00006200 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00006201 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006202}
6203
Richard Smithd9b90092016-07-02 01:32:16 +00006204ASTContext::InlineVariableDefinitionKind
6205ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6206 if (!VD->isInline())
6207 return InlineVariableDefinitionKind::None;
6208
6209 // In almost all cases, it's a weak definition.
6210 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00006211 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00006212 return InlineVariableDefinitionKind::Weak;
6213
6214 // If there's a file-context declaration in this translation unit, it's a
6215 // non-discardable definition.
6216 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00006217 if (D->getLexicalDeclContext()->isFileContext() &&
6218 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00006219 return InlineVariableDefinitionKind::Strong;
6220
6221 // If we've not seen one yet, we don't know.
6222 return InlineVariableDefinitionKind::WeakUnknown;
6223}
6224
Eugene Zelenko7855e772018-04-03 00:11:50 +00006225static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00006226 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006227}
6228
John McCall351762c2011-02-07 10:33:21 +00006229/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00006230/// declaration.
John McCall351762c2011-02-07 10:33:21 +00006231std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6232 std::string S;
6233
David Chisnall950a9512009-11-17 19:33:30 +00006234 const BlockDecl *Decl = Expr->getBlockDecl();
6235 QualType BlockTy =
6236 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
6237 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006238 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00006239 getObjCEncodingForMethodParameter(
6240 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
6241 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006242 else
Alp Toker314cc812014-01-25 16:55:45 +00006243 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00006244 // Compute size of all parameters.
6245 // Start with computing size of a pointer in number of bytes.
6246 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006247 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6248 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006249 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00006250 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006251 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00006252 if (sz.isZero())
6253 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006254 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00006255 ParmOffset += sz;
6256 }
6257 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00006258 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00006259 // Block pointer and offset.
6260 S += "@?0";
Fangrui Song6907ce22018-07-30 19:24:48 +00006261
David Chisnall950a9512009-11-17 19:33:30 +00006262 // Argument types.
6263 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006264 for (auto PVDecl : Decl->parameters()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006265 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006266 if (const auto *AT =
6267 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00006268 // Use array's original type only if it has known number of
6269 // elements.
6270 if (!isa<ConstantArrayType>(AT))
6271 PType = PVDecl->getType();
6272 } else if (PType->isFunctionType())
6273 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006274 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006275 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6276 S, true /*Extended*/);
6277 else
6278 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006279 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006280 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006281 }
John McCall351762c2011-02-07 10:33:21 +00006282
6283 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006284}
6285
John McCall843dfcc2016-11-29 21:57:00 +00006286std::string
6287ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6288 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006289 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006290 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006291 CharUnits ParmOffset;
6292 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006293 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006294 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006295 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006296 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006297 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006298
6299 assert(sz.isPositive() &&
John McCall843dfcc2016-11-29 21:57:00 +00006300 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006301 ParmOffset += sz;
6302 }
6303 S += charUnitsToString(ParmOffset);
6304 ParmOffset = CharUnits::Zero();
6305
6306 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006307 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006308 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006309 if (const auto *AT =
6310 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006311 // Use array's original type only if it has known number of
6312 // elements.
6313 if (!isa<ConstantArrayType>(AT))
6314 PType = PVDecl->getType();
6315 } else if (PType->isFunctionType())
6316 PType = PVDecl->getType();
6317 getObjCEncodingForType(PType, S);
6318 S += charUnitsToString(ParmOffset);
6319 ParmOffset += getObjCEncodingTypeSize(PType);
6320 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006321
John McCall843dfcc2016-11-29 21:57:00 +00006322 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006323}
6324
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006325/// getObjCEncodingForMethodParameter - Return the encoded type for a single
Fangrui Song6907ce22018-07-30 19:24:48 +00006326/// method parameter or return type. If Extended, include class names and
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006327/// block object types.
6328void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6329 QualType T, std::string& S,
6330 bool Extended) const {
6331 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6332 getObjCEncodingForTypeQualifier(QT, S);
6333 // Encode parameter type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006334 ObjCEncOptions Options = ObjCEncOptions()
6335 .setExpandPointedToStructures()
6336 .setExpandStructures()
6337 .setIsOutermostType();
6338 if (Extended)
6339 Options.setEncodeBlockParameters().setEncodeClassNames();
6340 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006341}
6342
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006343/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006344/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006345std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6346 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006347 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006348 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006349 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006350 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6351 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006352 // Compute size of all parameters.
6353 // Start with computing size of a pointer in number of bytes.
6354 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006355 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006356 // The first two arguments (self and _cmd) are pointers; account for
6357 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006358 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006359 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006360 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006361 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006362 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006363 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006364 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006365
6366 assert(sz.isPositive() &&
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006367 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006368 ParmOffset += sz;
6369 }
Ken Dyck40775002010-01-11 17:06:35 +00006370 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006371 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006372 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006373
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006374 // Argument types.
6375 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006376 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006377 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006378 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006379 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006380 if (const auto *AT =
6381 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006382 // Use array's original type only if it has known number of
6383 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006384 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006385 PType = PVDecl->getType();
6386 } else if (PType->isFunctionType())
6387 PType = PVDecl->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00006388 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006389 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006390 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006391 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006392 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006393
John McCall843dfcc2016-11-29 21:57:00 +00006394 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006395}
6396
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006397ObjCPropertyImplDecl *
6398ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6399 const ObjCPropertyDecl *PD,
6400 const Decl *Container) const {
6401 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006402 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006403 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006404 for (auto *PID : CID->property_impls())
6405 if (PID->getPropertyDecl() == PD)
6406 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006407 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006408 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006409 for (auto *PID : OID->property_impls())
6410 if (PID->getPropertyDecl() == PD)
6411 return PID;
6412 }
6413 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006414}
6415
Daniel Dunbar4932b362008-08-28 04:38:10 +00006416/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006417/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006418/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6419/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006420/// Property attributes are stored as a comma-delimited C string. The simple
6421/// attributes readonly and bycopy are encoded as single characters. The
6422/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6423/// encoded as single characters, followed by an identifier. Property types
6424/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006425/// these attributes are defined by the following enumeration:
6426/// @code
6427/// enum PropertyAttributes {
6428/// kPropertyReadOnly = 'R', // property is read-only.
6429/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6430/// kPropertyByref = '&', // property is a reference to the value last assigned
6431/// kPropertyDynamic = 'D', // property is dynamic
6432/// kPropertyGetter = 'G', // followed by getter selector name
6433/// kPropertySetter = 'S', // followed by setter selector name
6434/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006435/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006436/// kPropertyWeak = 'W' // 'weak' property
6437/// kPropertyStrong = 'P' // property GC'able
6438/// kPropertyNonAtomic = 'N' // property non-atomic
6439/// };
6440/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006441std::string
6442ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6443 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006444 // Collect information from the property implementation decl(s).
6445 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006446 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006447
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006448 if (ObjCPropertyImplDecl *PropertyImpDecl =
6449 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6450 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6451 Dynamic = true;
6452 else
6453 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006454 }
6455
6456 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006457 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006458
6459 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006460 // GCC has some special rules regarding encoding of properties which
6461 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006462 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006463
6464 if (PD->isReadOnly()) {
6465 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006466 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6467 S += ",C";
6468 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6469 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006470 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6471 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006472 } else {
6473 switch (PD->getSetterKind()) {
6474 case ObjCPropertyDecl::Assign: break;
6475 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006476 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006477 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006478 }
6479 }
6480
6481 // It really isn't clear at all what this means, since properties
6482 // are "dynamic by default".
6483 if (Dynamic)
6484 S += ",D";
6485
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006486 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6487 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006488
Daniel Dunbar4932b362008-08-28 04:38:10 +00006489 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6490 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006491 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006492 }
6493
6494 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6495 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006496 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006497 }
6498
6499 if (SynthesizePID) {
6500 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6501 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006502 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006503 }
6504
6505 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006506 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006507}
6508
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006509/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006510/// Another legacy compatibility encoding: 32-bit longs are encoded as
6511/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006512/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006513void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006514 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006515 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006516 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006517 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006518 else
Jay Foad39c79802011-01-12 09:06:06 +00006519 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006520 PointeeTy = IntTy;
6521 }
6522 }
6523}
6524
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006525void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006526 const FieldDecl *Field,
6527 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006528 // We follow the behavior of gcc, expanding structures which are
6529 // directly pointed to, and expanding embedded structures. Note that
6530 // these rules are sufficient to prevent recursive encoding of the
6531 // same type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006532 getObjCEncodingForTypeImpl(T, S,
6533 ObjCEncOptions()
6534 .setExpandPointedToStructures()
6535 .setExpandStructures()
6536 .setIsOutermostType(),
6537 Field, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006538}
6539
Joe Groff98ac7d22014-07-07 22:25:15 +00006540void ASTContext::getObjCEncodingForPropertyType(QualType T,
6541 std::string& S) const {
6542 // Encode result type.
6543 // GCC has some special rules regarding encoding of properties which
6544 // closely resembles encoding of ivars.
Nico Weber2e9591c2019-05-14 12:32:37 +00006545 getObjCEncodingForTypeImpl(T, S,
6546 ObjCEncOptions()
6547 .setExpandPointedToStructures()
6548 .setExpandStructures()
6549 .setIsOutermostType()
6550 .setEncodingProperty(),
6551 /*Field=*/nullptr);
Joe Groff98ac7d22014-07-07 22:25:15 +00006552}
6553
John McCall393a78d2012-12-20 02:45:14 +00006554static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6555 BuiltinType::Kind kind) {
6556 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006557 case BuiltinType::Void: return 'v';
6558 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006559 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006560 case BuiltinType::Char_U:
6561 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006562 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006563 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006564 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006565 case BuiltinType::UInt: return 'I';
6566 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006567 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006568 case BuiltinType::UInt128: return 'T';
6569 case BuiltinType::ULongLong: return 'Q';
6570 case BuiltinType::Char_S:
6571 case BuiltinType::SChar: return 'c';
6572 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006573 case BuiltinType::WChar_S:
6574 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006575 case BuiltinType::Int: return 'i';
6576 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006577 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006578 case BuiltinType::LongLong: return 'q';
6579 case BuiltinType::Int128: return 't';
6580 case BuiltinType::Float: return 'f';
6581 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006582 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006583 case BuiltinType::NullPtr: return '*'; // like char*
6584
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006585 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006586 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006587 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006588 case BuiltinType::ShortAccum:
6589 case BuiltinType::Accum:
6590 case BuiltinType::LongAccum:
6591 case BuiltinType::UShortAccum:
6592 case BuiltinType::UAccum:
6593 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006594 case BuiltinType::ShortFract:
6595 case BuiltinType::Fract:
6596 case BuiltinType::LongFract:
6597 case BuiltinType::UShortFract:
6598 case BuiltinType::UFract:
6599 case BuiltinType::ULongFract:
6600 case BuiltinType::SatShortAccum:
6601 case BuiltinType::SatAccum:
6602 case BuiltinType::SatLongAccum:
6603 case BuiltinType::SatUShortAccum:
6604 case BuiltinType::SatUAccum:
6605 case BuiltinType::SatULongAccum:
6606 case BuiltinType::SatShortFract:
6607 case BuiltinType::SatFract:
6608 case BuiltinType::SatLongFract:
6609 case BuiltinType::SatUShortFract:
6610 case BuiltinType::SatUFract:
6611 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006612 // FIXME: potentially need @encodes for these!
6613 return ' ';
6614
6615 case BuiltinType::ObjCId:
6616 case BuiltinType::ObjCClass:
6617 case BuiltinType::ObjCSel:
6618 llvm_unreachable("@encoding ObjC primitive type");
6619
6620 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006621#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6622 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006623#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006624#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6625 case BuiltinType::Id:
6626#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006627 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006628 case BuiltinType::OCLClkEvent:
6629 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006630 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006631 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006632 case BuiltinType::Dependent:
6633#define BUILTIN_TYPE(KIND, ID)
6634#define PLACEHOLDER_TYPE(KIND, ID) \
6635 case BuiltinType::KIND:
6636#include "clang/AST/BuiltinTypes.def"
6637 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006638 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006639 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006640}
6641
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006642static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6643 EnumDecl *Enum = ET->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00006644
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006645 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6646 if (!Enum->isFixed())
6647 return 'i';
Fangrui Song6907ce22018-07-30 19:24:48 +00006648
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006649 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006650 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006651 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006652}
6653
Jay Foad39c79802011-01-12 09:06:06 +00006654static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006655 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006656 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006657 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006658 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6659 // The GNU runtime requires more information; bitfields are encoded as b,
6660 // then the offset (in bits) of the first element, then the type of the
6661 // bitfield, then the size in bits. For example, in this structure:
6662 //
6663 // struct
6664 // {
6665 // int integer;
6666 // int flags:2;
6667 // };
6668 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6669 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6670 // information is not especially sensible, but we're stuck with it for
6671 // compatibility with GCC, although providing it breaks anything that
6672 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006673 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006674 uint64_t Offset;
6675
6676 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6677 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6678 IVD);
6679 } else {
6680 const RecordDecl *RD = FD->getParent();
6681 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6682 Offset = RL.getFieldOffset(FD->getFieldIndex());
6683 }
6684
6685 S += llvm::utostr(Offset);
6686
Eugene Zelenko7855e772018-04-03 00:11:50 +00006687 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006688 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006689 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006690 const auto *BT = T->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006691 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6692 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006693 }
Richard Smithcaf33902011-10-10 18:28:20 +00006694 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006695}
6696
Daniel Dunbar07d07852009-10-18 21:17:35 +00006697// FIXME: Use SmallString for accumulating string.
Nico Weber2e9591c2019-05-14 12:32:37 +00006698void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
6699 const ObjCEncOptions Options,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006700 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006701 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006702 CanQualType CT = getCanonicalType(T);
6703 switch (CT->getTypeClass()) {
6704 case Type::Builtin:
6705 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006706 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006707 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006708 if (const auto *BT = dyn_cast<BuiltinType>(CT))
John McCall393a78d2012-12-20 02:45:14 +00006709 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6710 else
6711 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006712 return;
Mike Stump11289f42009-09-09 15:08:12 +00006713
John McCall393a78d2012-12-20 02:45:14 +00006714 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006715 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006716 S += 'j';
Nico Weber2e9591c2019-05-14 12:32:37 +00006717 getObjCEncodingForTypeImpl(CT->getElementType(), S, ObjCEncOptions(),
6718 /*Field=*/nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006719 return;
6720 }
John McCall393a78d2012-12-20 02:45:14 +00006721
6722 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006723 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006724 S += 'A';
Nico Weber2e9591c2019-05-14 12:32:37 +00006725 getObjCEncodingForTypeImpl(AT->getValueType(), S, ObjCEncOptions(),
6726 /*Field=*/nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006727 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006728 }
John McCall393a78d2012-12-20 02:45:14 +00006729
6730 // encoding for pointer or reference types.
6731 case Type::Pointer:
6732 case Type::LValueReference:
6733 case Type::RValueReference: {
6734 QualType PointeeTy;
6735 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006736 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006737 if (PT->isObjCSelType()) {
6738 S += ':';
6739 return;
6740 }
6741 PointeeTy = PT->getPointeeType();
6742 } else {
6743 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6744 }
6745
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006746 bool isReadOnly = false;
6747 // For historical/compatibility reasons, the read-only qualifier of the
6748 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6749 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006750 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006751 if (isa<TypedefType>(T.getTypePtr())) {
Nico Weber2e9591c2019-05-14 12:32:37 +00006752 if (Options.IsOutermostType() && T.isConstQualified()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006753 isReadOnly = true;
6754 S += 'r';
6755 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006756 } else if (Options.IsOutermostType()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006757 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006758 while (P->getAs<PointerType>())
6759 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006760 if (P.isConstQualified()) {
6761 isReadOnly = true;
6762 S += 'r';
6763 }
6764 }
6765 if (isReadOnly) {
6766 // Another legacy compatibility encoding. Some ObjC qualifier and type
6767 // combinations need to be rearranged.
6768 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006769 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006770 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006771 }
Mike Stump11289f42009-09-09 15:08:12 +00006772
Anders Carlssond8499822007-10-29 05:01:08 +00006773 if (PointeeTy->isCharType()) {
6774 // char pointer types should be encoded as '*' unless it is a
6775 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006776 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006777 S += '*';
6778 return;
6779 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006780 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006781 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6782 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6783 S += '#';
6784 return;
6785 }
6786 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6787 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6788 S += '@';
6789 return;
6790 }
6791 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006792 }
Anders Carlssond8499822007-10-29 05:01:08 +00006793 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006794 getLegacyIntegralTypeEncoding(PointeeTy);
6795
Nico Weber2e9591c2019-05-14 12:32:37 +00006796 ObjCEncOptions NewOptions;
6797 if (Options.ExpandPointedToStructures())
6798 NewOptions.setExpandStructures();
6799 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
6800 /*Field=*/nullptr, NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006801 return;
6802 }
John McCall393a78d2012-12-20 02:45:14 +00006803
6804 case Type::ConstantArray:
6805 case Type::IncompleteArray:
6806 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006807 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006808
Nico Weber2e9591c2019-05-14 12:32:37 +00006809 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006810 // Incomplete arrays are encoded as a pointer to the array element.
6811 S += '^';
6812
Nico Weber2e9591c2019-05-14 12:32:37 +00006813 getObjCEncodingForTypeImpl(
6814 AT->getElementType(), S,
6815 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006816 } else {
6817 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006818
Eugene Zelenko7855e772018-04-03 00:11:50 +00006819 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006820 S += llvm::utostr(CAT->getSize().getZExtValue());
6821 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006822 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006823 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6824 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006825 S += '0';
6826 }
Mike Stump11289f42009-09-09 15:08:12 +00006827
Nico Weberdf129332019-05-10 13:56:56 +00006828 getObjCEncodingForTypeImpl(
6829 AT->getElementType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006830 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
6831 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006832 S += ']';
6833 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006834 return;
6835 }
Mike Stump11289f42009-09-09 15:08:12 +00006836
John McCall393a78d2012-12-20 02:45:14 +00006837 case Type::FunctionNoProto:
6838 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006839 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006840 return;
Mike Stump11289f42009-09-09 15:08:12 +00006841
John McCall393a78d2012-12-20 02:45:14 +00006842 case Type::Record: {
6843 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006844 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006845 // Anonymous structures print as '?'
6846 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6847 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006848 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006849 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006850 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006851 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6852 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006853 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006854 } else {
6855 S += '?';
6856 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006857 if (Options.ExpandStructures()) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006858 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006859 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006860 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006861 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006862 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006863 if (FD) {
6864 S += '"';
6865 S += Field->getNameAsString();
6866 S += '"';
6867 }
Mike Stump11289f42009-09-09 15:08:12 +00006868
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006869 // Special case bit-fields.
6870 if (Field->isBitField()) {
Nico Weberdf129332019-05-10 13:56:56 +00006871 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006872 ObjCEncOptions().setExpandStructures(),
6873 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006874 } else {
6875 QualType qt = Field->getType();
6876 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00006877 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00006878 qt, S,
6879 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
6880 NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006881 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006882 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006883 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006884 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006885 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006886 return;
6887 }
Mike Stump11289f42009-09-09 15:08:12 +00006888
John McCall393a78d2012-12-20 02:45:14 +00006889 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006890 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006891 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Nico Weber2e9591c2019-05-14 12:32:37 +00006892 if (Options.EncodeBlockParameters()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006893 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00006894
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006895 S += '<';
6896 // Block return type
Nico Weber2e9591c2019-05-14 12:32:37 +00006897 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
6898 Options.forComponentType(), FD, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006899 // Block self
6900 S += "@?";
6901 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00006902 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006903 for (const auto &I : FPT->param_types())
Nico Weber2e9591c2019-05-14 12:32:37 +00006904 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
6905 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006906 }
6907 S += '>';
6908 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006909 return;
6910 }
Mike Stump11289f42009-09-09 15:08:12 +00006911
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006912 case Type::ObjCObject: {
6913 // hack to match legacy encoding of *id and *Class
6914 QualType Ty = getObjCObjectPointerType(CT);
6915 if (Ty->isObjCIdType()) {
6916 S += "{objc_object=}";
6917 return;
6918 }
6919 else if (Ty->isObjCClassType()) {
6920 S += "{objc_class=}";
6921 return;
6922 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006923 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006924 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006925 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006926
John McCall393a78d2012-12-20 02:45:14 +00006927 case Type::ObjCInterface: {
6928 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006929 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006930 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006931 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006932 S += OI->getObjCRuntimeNameAsString();
Nico Weber2e9591c2019-05-14 12:32:37 +00006933 if (Options.ExpandStructures()) {
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006934 S += '=';
6935 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6936 DeepCollectObjCIvars(OI, true, Ivars);
6937 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006938 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006939 if (Field->isBitField())
Nico Weberdf129332019-05-10 13:56:56 +00006940 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006941 ObjCEncOptions().setExpandStructures(),
6942 Field);
Akira Hatanakaf3c89b12019-05-29 21:23:30 +00006943 else
6944 getObjCEncodingForTypeImpl(Field->getType(), S,
6945 ObjCEncOptions().setExpandStructures(), FD,
Nico Weber2e9591c2019-05-14 12:32:37 +00006946 NotEncodedT);
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006947 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006948 }
6949 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006950 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006951 }
Mike Stump11289f42009-09-09 15:08:12 +00006952
John McCall393a78d2012-12-20 02:45:14 +00006953 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006954 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006955 if (OPT->isObjCIdType()) {
6956 S += '@';
6957 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006958 }
Mike Stump11289f42009-09-09 15:08:12 +00006959
Steve Narofff0c86112009-10-28 22:03:49 +00006960 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6961 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
Nico Weberdf129332019-05-10 13:56:56 +00006962 // Since this is a binary compatibility issue, need to consult with
6963 // runtime folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006964 S += '#';
6965 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006966 }
Mike Stump11289f42009-09-09 15:08:12 +00006967
Chris Lattnere7cabb92009-07-13 00:10:46 +00006968 if (OPT->isObjCQualifiedIdType()) {
Nico Weber2e9591c2019-05-14 12:32:37 +00006969 getObjCEncodingForTypeImpl(
6970 getObjCIdType(), S,
6971 Options.keepingOnly(ObjCEncOptions()
6972 .setExpandPointedToStructures()
6973 .setExpandStructures()),
6974 FD);
6975 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006976 // Note that we do extended encoding of protocol qualifer list
6977 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006978 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006979 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006980 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006981 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006982 S += '>';
6983 }
6984 S += '"';
6985 }
6986 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006987 }
Mike Stump11289f42009-09-09 15:08:12 +00006988
Chris Lattnere7cabb92009-07-13 00:10:46 +00006989 S += '@';
Fangrui Song6907ce22018-07-30 19:24:48 +00006990 if (OPT->getInterfaceDecl() &&
Nico Weber2e9591c2019-05-14 12:32:37 +00006991 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006992 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006993 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006994 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006995 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006996 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006997 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006998 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006999 S += '"';
7000 }
7001 return;
7002 }
Mike Stump11289f42009-09-09 15:08:12 +00007003
John McCalla9e6e8d2010-05-17 23:56:34 +00007004 // gcc just blithely ignores member pointers.
Nico Weber2e9591c2019-05-14 12:32:37 +00007005 // FIXME: we should do better than that. 'M' is available.
John McCall393a78d2012-12-20 02:45:14 +00007006 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007007 // This matches gcc's encoding, even though technically it is insufficient.
7008 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00007009 case Type::Vector:
7010 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007011 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007012 if (NotEncodedT)
7013 *NotEncodedT = T;
7014 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00007015
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007016 // We could see an undeduced auto type here during error recovery.
7017 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00007018 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007019 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00007020 return;
7021
Xiuli Pan9c14e282016-01-09 12:53:17 +00007022 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00007023#define ABSTRACT_TYPE(KIND, BASE)
7024#define TYPE(KIND, BASE)
7025#define DEPENDENT_TYPE(KIND, BASE) \
7026 case Type::KIND:
7027#define NON_CANONICAL_TYPE(KIND, BASE) \
7028 case Type::KIND:
7029#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7030 case Type::KIND:
7031#include "clang/AST/TypeNodes.def"
7032 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00007033 }
John McCall393a78d2012-12-20 02:45:14 +00007034 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00007035}
7036
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007037void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7038 std::string &S,
7039 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007040 bool includeVBases,
7041 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007042 assert(RDecl && "Expected non-null RecordDecl");
7043 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00007044 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007045 return;
7046
Eugene Zelenko7855e772018-04-03 00:11:50 +00007047 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007048 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7049 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7050
7051 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00007052 for (const auto &BI : CXXRec->bases()) {
7053 if (!BI.isVirtual()) {
7054 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007055 if (base->isEmpty())
7056 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007057 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007058 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7059 std::make_pair(offs, base));
7060 }
7061 }
7062 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007063
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007064 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00007065 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007066 uint64_t offs = layout.getFieldOffset(i);
7067 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00007068 std::make_pair(offs, Field));
7069 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007070 }
7071
7072 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00007073 for (const auto &BI : CXXRec->vbases()) {
7074 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007075 if (base->isEmpty())
7076 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007077 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00007078 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7079 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00007080 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7081 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007082 }
7083 }
7084
7085 CharUnits size;
7086 if (CXXRec) {
7087 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7088 } else {
7089 size = layout.getSize();
7090 }
7091
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007092#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007093 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007094#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007095 std::multimap<uint64_t, NamedDecl *>::iterator
7096 CurLayObj = FieldOrBaseOffsets.begin();
7097
Douglas Gregorf5d6c742012-04-27 22:30:01 +00007098 if (CXXRec && CXXRec->isDynamicClass() &&
7099 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007100 if (FD) {
7101 S += "\"_vptr$";
7102 std::string recname = CXXRec->getNameAsString();
7103 if (recname.empty()) recname = "?";
7104 S += recname;
7105 S += '"';
7106 }
7107 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007108#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007109 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007110#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007111 }
7112
7113 if (!RDecl->hasFlexibleArrayMember()) {
7114 // Mark the end of the structure.
7115 uint64_t offs = toBits(size);
7116 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00007117 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007118 }
7119
7120 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007121#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007122 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007123 if (CurOffs < CurLayObj->first) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007124 uint64_t padding = CurLayObj->first - CurOffs;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007125 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7126 // packing/alignment of members is different that normal, in which case
7127 // the encoding will be out-of-sync with the real layout.
7128 // If the runtime switches to just consider the size of types without
7129 // taking into account alignment, we could make padding explicit in the
7130 // encoding (e.g. using arrays of chars). The encoding strings would be
7131 // longer then though.
7132 CurOffs += padding;
7133 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007134#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007135
7136 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00007137 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007138 break; // reached end of structure.
7139
Eugene Zelenko7855e772018-04-03 00:11:50 +00007140 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007141 // We expand the bases without their virtual bases since those are going
7142 // in the initial structure. Note that this differs from gcc which
7143 // expands virtual bases each time one is encountered in the hierarchy,
7144 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007145 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7146 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007147 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007148#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007149 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007150#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007151 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007152 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007153 if (FD) {
7154 S += '"';
7155 S += field->getNameAsString();
7156 S += '"';
7157 }
7158
7159 if (field->isBitField()) {
7160 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007161#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00007162 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007163#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007164 } else {
7165 QualType qt = field->getType();
7166 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00007167 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00007168 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7169 FD, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007170#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007171 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007172#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007173 }
7174 }
7175 }
7176}
7177
Mike Stump11289f42009-09-09 15:08:12 +00007178void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00007179 std::string& S) const {
7180 if (QT & Decl::OBJC_TQ_In)
7181 S += 'n';
7182 if (QT & Decl::OBJC_TQ_Inout)
7183 S += 'N';
7184 if (QT & Decl::OBJC_TQ_Out)
7185 S += 'o';
7186 if (QT & Decl::OBJC_TQ_Bycopy)
7187 S += 'O';
7188 if (QT & Decl::OBJC_TQ_Byref)
7189 S += 'R';
7190 if (QT & Decl::OBJC_TQ_Oneway)
7191 S += 'V';
7192}
7193
Douglas Gregor3ea72692011-08-12 05:46:01 +00007194TypedefDecl *ASTContext::getObjCIdDecl() const {
7195 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007196 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00007197 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007198 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00007199 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00007200 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00007201}
7202
Douglas Gregor52e02802011-08-12 06:17:30 +00007203TypedefDecl *ASTContext::getObjCSelDecl() const {
7204 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007205 QualType T = getPointerType(ObjCBuiltinSelTy);
7206 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00007207 }
7208 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00007209}
7210
Douglas Gregor0a586182011-08-12 05:59:41 +00007211TypedefDecl *ASTContext::getObjCClassDecl() const {
7212 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007213 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00007214 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007215 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00007216 }
Douglas Gregor0a586182011-08-12 05:59:41 +00007217 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00007218}
7219
Douglas Gregord53ae832012-01-17 18:09:05 +00007220ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7221 if (!ObjCProtocolClassDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007222 ObjCProtocolClassDecl
7223 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregord53ae832012-01-17 18:09:05 +00007224 SourceLocation(),
7225 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00007226 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00007227 /*PrevDecl=*/nullptr,
Fangrui Song6907ce22018-07-30 19:24:48 +00007228 SourceLocation(), true);
Douglas Gregord53ae832012-01-17 18:09:05 +00007229 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007230
Douglas Gregord53ae832012-01-17 18:09:05 +00007231 return ObjCProtocolClassDecl;
7232}
7233
Meador Inge5d3fb222012-06-16 03:34:49 +00007234//===----------------------------------------------------------------------===//
7235// __builtin_va_list Construction Functions
7236//===----------------------------------------------------------------------===//
7237
Charles Davisc7d5c942015-09-17 20:55:33 +00007238static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7239 StringRef Name) {
7240 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007241 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00007242 return Context->buildImplicitTypedef(T, Name);
7243}
7244
7245static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7246 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7247}
7248
7249static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7250 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007251}
7252
7253static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7254 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007255 QualType T = Context->getPointerType(Context->VoidTy);
7256 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007257}
7258
Tim Northover9bb857a2013-01-31 12:13:10 +00007259static TypedefDecl *
7260CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007261 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007262 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007263 if (Context->getLangOpts().CPlusPlus) {
7264 // namespace std { struct __va_list {
7265 NamespaceDecl *NS;
7266 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7267 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007268 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007269 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007270 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007271 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007272 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007273 }
7274
7275 VaListTagDecl->startDefinition();
7276
7277 const size_t NumFields = 5;
7278 QualType FieldTypes[NumFields];
7279 const char *FieldNames[NumFields];
7280
7281 // void *__stack;
7282 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7283 FieldNames[0] = "__stack";
7284
7285 // void *__gr_top;
7286 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7287 FieldNames[1] = "__gr_top";
7288
7289 // void *__vr_top;
7290 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7291 FieldNames[2] = "__vr_top";
7292
7293 // int __gr_offs;
7294 FieldTypes[3] = Context->IntTy;
7295 FieldNames[3] = "__gr_offs";
7296
7297 // int __vr_offs;
7298 FieldTypes[4] = Context->IntTy;
7299 FieldNames[4] = "__vr_offs";
7300
7301 // Create fields
7302 for (unsigned i = 0; i < NumFields; ++i) {
7303 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7304 VaListTagDecl,
7305 SourceLocation(),
7306 SourceLocation(),
7307 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007308 FieldTypes[i], /*TInfo=*/nullptr,
7309 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007310 /*Mutable=*/false,
7311 ICIS_NoInit);
7312 Field->setAccess(AS_public);
7313 VaListTagDecl->addDecl(Field);
7314 }
7315 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007316 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007317 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007318
7319 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007320 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007321}
7322
Meador Inge5d3fb222012-06-16 03:34:49 +00007323static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7324 // typedef struct __va_list_tag {
7325 RecordDecl *VaListTagDecl;
7326
Alp Toker2dea15b2013-12-17 01:22:38 +00007327 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007328 VaListTagDecl->startDefinition();
7329
7330 const size_t NumFields = 5;
7331 QualType FieldTypes[NumFields];
7332 const char *FieldNames[NumFields];
7333
7334 // unsigned char gpr;
7335 FieldTypes[0] = Context->UnsignedCharTy;
7336 FieldNames[0] = "gpr";
7337
7338 // unsigned char fpr;
7339 FieldTypes[1] = Context->UnsignedCharTy;
7340 FieldNames[1] = "fpr";
7341
7342 // unsigned short reserved;
7343 FieldTypes[2] = Context->UnsignedShortTy;
7344 FieldNames[2] = "reserved";
7345
7346 // void* overflow_arg_area;
7347 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7348 FieldNames[3] = "overflow_arg_area";
7349
7350 // void* reg_save_area;
7351 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7352 FieldNames[4] = "reg_save_area";
7353
7354 // Create fields
7355 for (unsigned i = 0; i < NumFields; ++i) {
7356 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7357 SourceLocation(),
7358 SourceLocation(),
7359 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007360 FieldTypes[i], /*TInfo=*/nullptr,
7361 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007362 /*Mutable=*/false,
7363 ICIS_NoInit);
7364 Field->setAccess(AS_public);
7365 VaListTagDecl->addDecl(Field);
7366 }
7367 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007368 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007369 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7370
7371 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007372 TypedefDecl *VaListTagTypedefDecl =
7373 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7374
Meador Inge5d3fb222012-06-16 03:34:49 +00007375 QualType VaListTagTypedefType =
7376 Context->getTypedefType(VaListTagTypedefDecl);
7377
7378 // typedef __va_list_tag __builtin_va_list[1];
7379 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7380 QualType VaListTagArrayType
7381 = Context->getConstantArrayType(VaListTagTypedefType,
7382 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007383 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007384}
7385
7386static TypedefDecl *
7387CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007388 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007389 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007390 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007391 VaListTagDecl->startDefinition();
7392
7393 const size_t NumFields = 4;
7394 QualType FieldTypes[NumFields];
7395 const char *FieldNames[NumFields];
7396
7397 // unsigned gp_offset;
7398 FieldTypes[0] = Context->UnsignedIntTy;
7399 FieldNames[0] = "gp_offset";
7400
7401 // unsigned fp_offset;
7402 FieldTypes[1] = Context->UnsignedIntTy;
7403 FieldNames[1] = "fp_offset";
7404
7405 // void* overflow_arg_area;
7406 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7407 FieldNames[2] = "overflow_arg_area";
7408
7409 // void* reg_save_area;
7410 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7411 FieldNames[3] = "reg_save_area";
7412
7413 // Create fields
7414 for (unsigned i = 0; i < NumFields; ++i) {
7415 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7416 VaListTagDecl,
7417 SourceLocation(),
7418 SourceLocation(),
7419 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007420 FieldTypes[i], /*TInfo=*/nullptr,
7421 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007422 /*Mutable=*/false,
7423 ICIS_NoInit);
7424 Field->setAccess(AS_public);
7425 VaListTagDecl->addDecl(Field);
7426 }
7427 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007428 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007429 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7430
Richard Smith9b88a4c2015-07-27 05:40:23 +00007431 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007432
Richard Smith9b88a4c2015-07-27 05:40:23 +00007433 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007434 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007435 QualType VaListTagArrayType =
7436 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007437 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007438}
7439
7440static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7441 // typedef int __builtin_va_list[4];
7442 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007443 QualType IntArrayType =
7444 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007445 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007446}
7447
Logan Chien57086ce2012-10-10 06:56:20 +00007448static TypedefDecl *
7449CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007450 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007451 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007452 if (Context->getLangOpts().CPlusPlus) {
7453 // namespace std { struct __va_list {
7454 NamespaceDecl *NS;
7455 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7456 Context->getTranslationUnitDecl(),
7457 /*Inline*/false, SourceLocation(),
7458 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007459 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007460 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007461 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007462 }
7463
7464 VaListDecl->startDefinition();
7465
7466 // void * __ap;
7467 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7468 VaListDecl,
7469 SourceLocation(),
7470 SourceLocation(),
7471 &Context->Idents.get("__ap"),
7472 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007473 /*TInfo=*/nullptr,
7474 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007475 /*Mutable=*/false,
7476 ICIS_NoInit);
7477 Field->setAccess(AS_public);
7478 VaListDecl->addDecl(Field);
7479
7480 // };
7481 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007482 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007483
7484 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007485 QualType T = Context->getRecordType(VaListDecl);
7486 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007487}
7488
Ulrich Weigand47445072013-05-06 16:26:41 +00007489static TypedefDecl *
7490CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007491 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007492 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007493 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007494 VaListTagDecl->startDefinition();
7495
7496 const size_t NumFields = 4;
7497 QualType FieldTypes[NumFields];
7498 const char *FieldNames[NumFields];
7499
7500 // long __gpr;
7501 FieldTypes[0] = Context->LongTy;
7502 FieldNames[0] = "__gpr";
7503
7504 // long __fpr;
7505 FieldTypes[1] = Context->LongTy;
7506 FieldNames[1] = "__fpr";
7507
7508 // void *__overflow_arg_area;
7509 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7510 FieldNames[2] = "__overflow_arg_area";
7511
7512 // void *__reg_save_area;
7513 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7514 FieldNames[3] = "__reg_save_area";
7515
7516 // Create fields
7517 for (unsigned i = 0; i < NumFields; ++i) {
7518 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7519 VaListTagDecl,
7520 SourceLocation(),
7521 SourceLocation(),
7522 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007523 FieldTypes[i], /*TInfo=*/nullptr,
7524 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007525 /*Mutable=*/false,
7526 ICIS_NoInit);
7527 Field->setAccess(AS_public);
7528 VaListTagDecl->addDecl(Field);
7529 }
7530 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007531 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007532 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007533
Richard Smith9b88a4c2015-07-27 05:40:23 +00007534 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007535
7536 // typedef __va_list_tag __builtin_va_list[1];
7537 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007538 QualType VaListTagArrayType =
7539 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007540
Alp Toker56b5cc92013-12-15 10:36:26 +00007541 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007542}
7543
Meador Inge5d3fb222012-06-16 03:34:49 +00007544static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7545 TargetInfo::BuiltinVaListKind Kind) {
7546 switch (Kind) {
7547 case TargetInfo::CharPtrBuiltinVaList:
7548 return CreateCharPtrBuiltinVaListDecl(Context);
7549 case TargetInfo::VoidPtrBuiltinVaList:
7550 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007551 case TargetInfo::AArch64ABIBuiltinVaList:
7552 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007553 case TargetInfo::PowerABIBuiltinVaList:
7554 return CreatePowerABIBuiltinVaListDecl(Context);
7555 case TargetInfo::X86_64ABIBuiltinVaList:
7556 return CreateX86_64ABIBuiltinVaListDecl(Context);
7557 case TargetInfo::PNaClABIBuiltinVaList:
7558 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007559 case TargetInfo::AAPCSABIBuiltinVaList:
7560 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007561 case TargetInfo::SystemZBuiltinVaList:
7562 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007563 }
7564
7565 llvm_unreachable("Unhandled __builtin_va_list type kind");
7566}
7567
7568TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007569 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007570 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007571 assert(BuiltinVaListDecl->isImplicit());
7572 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007573
7574 return BuiltinVaListDecl;
7575}
7576
Richard Smith9b88a4c2015-07-27 05:40:23 +00007577Decl *ASTContext::getVaListTagDecl() const {
7578 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007579 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007580 if (!VaListTagDecl)
7581 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007582
Richard Smith9b88a4c2015-07-27 05:40:23 +00007583 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007584}
7585
Charles Davisc7d5c942015-09-17 20:55:33 +00007586TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7587 if (!BuiltinMSVaListDecl)
7588 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7589
7590 return BuiltinMSVaListDecl;
7591}
7592
Erich Keane41af9712018-04-16 21:30:08 +00007593bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7594 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7595}
7596
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007597void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007598 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007599 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007600
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007601 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007602}
7603
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007604/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007605/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007606TemplateName
7607ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7608 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007609 unsigned size = End - Begin;
7610 assert(size > 1 && "set is not overloaded!");
7611
7612 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7613 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007614 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007615
7616 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007617 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007618 NamedDecl *D = *I;
7619 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007620 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007621 (isa<UsingShadowDecl>(D) &&
7622 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7623 *Storage++ = D;
7624 }
7625
7626 return TemplateName(OT);
7627}
7628
Richard Smithb23c5e82019-05-09 03:31:27 +00007629/// Retrieve a template name representing an unqualified-id that has been
7630/// assumed to name a template for ADL purposes.
7631TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
7632 auto *OT = new (*this) AssumedTemplateStorage(Name);
7633 return TemplateName(OT);
7634}
7635
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007636/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007637/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007638TemplateName
7639ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7640 bool TemplateKeyword,
7641 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007642 assert(NNS && "Missing nested-name-specifier in qualified template name");
Fangrui Song6907ce22018-07-30 19:24:48 +00007643
Douglas Gregorc42075a2010-02-04 18:10:26 +00007644 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007645 llvm::FoldingSetNodeID ID;
7646 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7647
Craig Topper36250ad2014-05-12 05:36:57 +00007648 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007649 QualifiedTemplateName *QTN =
7650 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7651 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007652 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007653 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007654 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7655 }
7656
7657 return TemplateName(QTN);
7658}
7659
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007660/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007661/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007662TemplateName
7663ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7664 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007665 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007666 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007667
7668 llvm::FoldingSetNodeID ID;
7669 DependentTemplateName::Profile(ID, NNS, Name);
7670
Craig Topper36250ad2014-05-12 05:36:57 +00007671 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007672 DependentTemplateName *QTN =
7673 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7674
7675 if (QTN)
7676 return TemplateName(QTN);
7677
7678 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7679 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007680 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007681 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007682 } else {
7683 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007684 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007685 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007686 DependentTemplateName *CheckQTN =
7687 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7688 assert(!CheckQTN && "Dependent type name canonicalization broken");
7689 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007690 }
7691
7692 DependentTemplateNames.InsertNode(QTN, InsertPos);
7693 return TemplateName(QTN);
7694}
7695
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007696/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007697/// template name such as \c MetaFun::template operator+.
Fangrui Song6907ce22018-07-30 19:24:48 +00007698TemplateName
Douglas Gregor71395fa2009-11-04 00:56:37 +00007699ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007700 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007701 assert((!NNS || NNS->isDependent()) &&
7702 "Nested name specifier must be dependent");
Fangrui Song6907ce22018-07-30 19:24:48 +00007703
Douglas Gregor71395fa2009-11-04 00:56:37 +00007704 llvm::FoldingSetNodeID ID;
7705 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007706
7707 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007708 DependentTemplateName *QTN
7709 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007710
Douglas Gregor71395fa2009-11-04 00:56:37 +00007711 if (QTN)
7712 return TemplateName(QTN);
Fangrui Song6907ce22018-07-30 19:24:48 +00007713
Douglas Gregor71395fa2009-11-04 00:56:37 +00007714 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7715 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007716 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007717 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007718 } else {
7719 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007720 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007721 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007722
Douglas Gregorc42075a2010-02-04 18:10:26 +00007723 DependentTemplateName *CheckQTN
7724 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7725 assert(!CheckQTN && "Dependent template name canonicalization broken");
7726 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007727 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007728
Douglas Gregor71395fa2009-11-04 00:56:37 +00007729 DependentTemplateNames.InsertNode(QTN, InsertPos);
7730 return TemplateName(QTN);
7731}
7732
Fangrui Song6907ce22018-07-30 19:24:48 +00007733TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007734ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7735 TemplateName replacement) const {
7736 llvm::FoldingSetNodeID ID;
7737 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007738
7739 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007740 SubstTemplateTemplateParmStorage *subst
7741 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007742
John McCalld9dfe3a2011-06-30 08:33:18 +00007743 if (!subst) {
7744 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7745 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7746 }
7747
7748 return TemplateName(subst);
7749}
7750
Fangrui Song6907ce22018-07-30 19:24:48 +00007751TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007752ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7753 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007754 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007755 llvm::FoldingSetNodeID ID;
7756 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007757
7758 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007759 SubstTemplateTemplateParmPackStorage *Subst
7760 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007761
Douglas Gregor5590be02011-01-15 06:45:20 +00007762 if (!Subst) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007763 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007764 ArgPack.pack_size(),
7765 ArgPack.pack_begin());
7766 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7767 }
7768
7769 return TemplateName(Subst);
7770}
7771
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007772/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007773/// TargetInfo, produce the corresponding type. The unsigned @p Type
7774/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007775CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007776 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007777 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007778 case TargetInfo::SignedChar: return SignedCharTy;
7779 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007780 case TargetInfo::SignedShort: return ShortTy;
7781 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7782 case TargetInfo::SignedInt: return IntTy;
7783 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7784 case TargetInfo::SignedLong: return LongTy;
7785 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7786 case TargetInfo::SignedLongLong: return LongLongTy;
7787 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7788 }
7789
David Blaikie83d382b2011-09-23 05:06:16 +00007790 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007791}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007792
7793//===----------------------------------------------------------------------===//
7794// Type Predicates.
7795//===----------------------------------------------------------------------===//
7796
Fariborz Jahanian96207692009-02-18 21:49:28 +00007797/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7798/// garbage collection attribute.
7799///
John McCall553d45a2011-01-12 00:34:59 +00007800Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007801 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007802 return Qualifiers::GCNone;
7803
Erik Pilkingtonfa983902018-10-30 20:31:30 +00007804 assert(getLangOpts().ObjC);
John McCall553d45a2011-01-12 00:34:59 +00007805 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7806
7807 // Default behaviour under objective-C's gc is for ObjC pointers
7808 // (or pointers to them) be treated as though they were declared
7809 // as __strong.
7810 if (GCAttrs == Qualifiers::GCNone) {
7811 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7812 return Qualifiers::Strong;
7813 else if (Ty->isPointerType())
7814 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7815 } else {
7816 // It's not valid to set GC attributes on anything that isn't a
7817 // pointer.
7818#ifndef NDEBUG
7819 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007820 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007821 CT = AT->getElementType();
7822 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7823#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007824 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007825 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007826}
7827
Chris Lattner49af6a42008-04-07 06:51:04 +00007828//===----------------------------------------------------------------------===//
7829// Type Compatibility Testing
7830//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007831
Mike Stump11289f42009-09-09 15:08:12 +00007832/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007833/// compatible.
7834static bool areCompatVectorTypes(const VectorType *LHS,
7835 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007836 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007837 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007838 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007839}
7840
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007841bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7842 QualType SecondVec) {
7843 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7844 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7845
7846 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7847 return true;
7848
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007849 // Treat Neon vector types and most AltiVec vector types as if they are the
7850 // equivalent GCC vector types.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007851 const auto *First = FirstVec->getAs<VectorType>();
7852 const auto *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007853 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007854 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007855 First->getVectorKind() != VectorType::AltiVecPixel &&
7856 First->getVectorKind() != VectorType::AltiVecBool &&
7857 Second->getVectorKind() != VectorType::AltiVecPixel &&
7858 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007859 return true;
7860
7861 return false;
7862}
7863
Steve Naroff8e6aee52009-07-23 01:01:38 +00007864//===----------------------------------------------------------------------===//
7865// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7866//===----------------------------------------------------------------------===//
7867
7868/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7869/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007870bool
7871ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7872 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007873 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007874 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007875 for (auto *PI : rProto->protocols())
7876 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007877 return true;
7878 return false;
7879}
7880
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007881/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7882/// Class<pr1, ...>.
Fangrui Song6907ce22018-07-30 19:24:48 +00007883bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007884 QualType rhs) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007885 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7886 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007887 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fangrui Song6907ce22018-07-30 19:24:48 +00007888
Aaron Ballman83731462014-03-17 16:14:00 +00007889 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007890 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007891 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007892 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7893 match = true;
7894 break;
7895 }
7896 }
7897 if (!match)
7898 return false;
7899 }
7900 return true;
7901}
7902
Steve Naroff8e6aee52009-07-23 01:01:38 +00007903/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7904/// ObjCQualifiedIDType.
7905bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7906 bool compare) {
7907 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007908 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007909 lhs->isObjCIdType() || lhs->isObjCClassType())
7910 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007911 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007912 rhs->isObjCIdType() || rhs->isObjCClassType())
7913 return true;
7914
7915 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007916 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007917
Steve Naroff8e6aee52009-07-23 01:01:38 +00007918 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007919
Steve Naroff8e6aee52009-07-23 01:01:38 +00007920 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007921 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007922 // make sure we check the class hierarchy.
7923 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007924 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007925 // when comparing an id<P> on lhs with a static type on rhs,
7926 // see if static class implements all of id's protocols, directly or
7927 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007928 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007929 return false;
7930 }
7931 }
7932 // If there are no qualifiers and no interface, we have an 'id'.
7933 return true;
7934 }
Mike Stump11289f42009-09-09 15:08:12 +00007935 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007936 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007937 bool match = false;
7938
7939 // when comparing an id<P> on lhs with a static type on rhs,
7940 // see if static class implements all of id's protocols, directly or
7941 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007942 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007943 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7944 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7945 match = true;
7946 break;
7947 }
7948 }
Mike Stump11289f42009-09-09 15:08:12 +00007949 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007950 // make sure we check the class hierarchy.
7951 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007952 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007953 // when comparing an id<P> on lhs with a static type on rhs,
7954 // see if static class implements all of id's protocols, directly or
7955 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007956 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007957 match = true;
7958 break;
7959 }
7960 }
7961 }
7962 if (!match)
7963 return false;
7964 }
Mike Stump11289f42009-09-09 15:08:12 +00007965
Steve Naroff8e6aee52009-07-23 01:01:38 +00007966 return true;
7967 }
Mike Stump11289f42009-09-09 15:08:12 +00007968
Steve Naroff8e6aee52009-07-23 01:01:38 +00007969 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7970 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7971
Mike Stump11289f42009-09-09 15:08:12 +00007972 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007973 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007974 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007975 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007976 bool match = false;
7977
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007978 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007979 // see if static class implements all of id's protocols, directly or
7980 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007981 // First, lhs protocols in the qualifier list must be found, direct
7982 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007983 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007984 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7985 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7986 match = true;
7987 break;
7988 }
7989 }
7990 if (!match)
7991 return false;
7992 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007993
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007994 // Static class's protocols, or its super class or category protocols
7995 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7996 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7997 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7998 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7999 // This is rather dubious but matches gcc's behavior. If lhs has
8000 // no type qualifier and its class has no static protocol(s)
8001 // assume that it is mismatch.
8002 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
8003 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00008004 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008005 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00008006 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008007 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8008 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8009 match = true;
8010 break;
8011 }
8012 }
8013 if (!match)
8014 return false;
8015 }
8016 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00008017 return true;
8018 }
8019 return false;
8020}
8021
Eli Friedman47f77112008-08-22 00:56:42 +00008022/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00008023/// compatible for assignment from RHS to LHS. This handles validation of any
8024/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00008025bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8026 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00008027 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8028 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8029
Steve Naroff1329fa02009-07-15 18:40:39 +00008030 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00008031 if (LHS->isObjCUnqualifiedIdOrClass() ||
8032 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00008033 return true;
8034
Douglas Gregorab209d82015-07-07 03:58:42 +00008035 // Function object that propagates a successful result or handles
8036 // __kindof types.
8037 auto finish = [&](bool succeeded) -> bool {
8038 if (succeeded)
8039 return true;
8040
8041 if (!RHS->isKindOfType())
8042 return false;
8043
8044 // Strip off __kindof and protocol qualifiers, then check whether
8045 // we can assign the other way.
8046 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8047 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8048 };
8049
8050 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8051 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8052 QualType(RHSOPT,0),
8053 false));
8054 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008055
Douglas Gregorab209d82015-07-07 03:58:42 +00008056 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8057 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
8058 QualType(RHSOPT,0)));
8059 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008060
John McCall8b07ec22010-05-15 11:32:37 +00008061 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00008062 if (LHS->getInterface() && RHS->getInterface()) {
8063 return finish(canAssignObjCInterfaces(LHS, RHS));
8064 }
Mike Stump11289f42009-09-09 15:08:12 +00008065
Steve Naroff8e6aee52009-07-23 01:01:38 +00008066 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008067}
8068
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008069/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Fangrui Song6907ce22018-07-30 19:24:48 +00008070/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008071/// arguments in block literals. When passed as arguments, passing 'A*' where
8072/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8073/// not OK. For the return type, the opposite is not OK.
8074bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8075 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008076 const ObjCObjectPointerType *RHSOPT,
8077 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008078
8079 // Function object that propagates a successful result or handles
8080 // __kindof types.
8081 auto finish = [&](bool succeeded) -> bool {
8082 if (succeeded)
8083 return true;
8084
8085 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8086 if (!Expected->isKindOfType())
8087 return false;
8088
8089 // Strip off __kindof and protocol qualifiers, then check whether
8090 // we can assign the other way.
8091 return canAssignObjCInterfacesInBlockPointer(
8092 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8093 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8094 BlockReturnType);
8095 };
8096
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008097 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008098 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008099
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008100 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008101 return finish(RHSOPT->isObjCBuiltinType() ||
8102 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008103 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008104
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008105 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00008106 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8107 QualType(RHSOPT,0),
8108 false));
Fangrui Song6907ce22018-07-30 19:24:48 +00008109
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008110 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8111 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8112 if (LHS && RHS) { // We have 2 user-defined types.
8113 if (LHS != RHS) {
8114 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008115 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008116 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008117 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008118 }
8119 else
8120 return true;
8121 }
8122 return false;
8123}
8124
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008125/// Comparison routine for Objective-C protocols to be used with
8126/// llvm::array_pod_sort.
8127static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8128 ObjCProtocolDecl * const *rhs) {
8129 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008130}
8131
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008132/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008133/// of protocols inherited from two distinct objective-c pointer objects with
8134/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008135/// It is used to build composite qualifier list of the composite type of
8136/// the conditional expression involving two objective-c pointer objects.
Fangrui Song6907ce22018-07-30 19:24:48 +00008137static
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008138void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008139 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008140 const ObjCObjectPointerType *LHSOPT,
8141 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008142 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008143
John McCall8b07ec22010-05-15 11:32:37 +00008144 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8145 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8146 assert(LHS->getInterface() && "LHS must have an interface base");
8147 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008148
8149 // Add all of the protocols for the LHS.
8150 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8151
8152 // Start with the protocol qualifiers.
8153 for (auto proto : LHS->quals()) {
8154 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008155 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008156
8157 // Also add the protocols associated with the LHS interface.
8158 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8159
Raphael Isemannb23ccec2018-12-10 12:37:46 +00008160 // Add all of the protocols for the RHS.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008161 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8162
8163 // Start with the protocol qualifiers.
8164 for (auto proto : RHS->quals()) {
8165 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008166 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008167
8168 // Also add the protocols associated with the RHS interface.
8169 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8170
8171 // Compute the intersection of the collected protocol sets.
8172 for (auto proto : LHSProtocolSet) {
8173 if (RHSProtocolSet.count(proto))
8174 IntersectionSet.push_back(proto);
8175 }
8176
8177 // Compute the set of protocols that is implied by either the common type or
8178 // the protocols within the intersection.
8179 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8180 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8181
8182 // Remove any implied protocols from the list of inherited protocols.
8183 if (!ImpliedProtocols.empty()) {
8184 IntersectionSet.erase(
8185 std::remove_if(IntersectionSet.begin(),
8186 IntersectionSet.end(),
8187 [&](ObjCProtocolDecl *proto) -> bool {
8188 return ImpliedProtocols.count(proto) > 0;
8189 }),
8190 IntersectionSet.end());
8191 }
8192
8193 // Sort the remaining protocols by name.
8194 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8195 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008196}
8197
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008198/// Determine whether the first type is a subtype of the second.
8199static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8200 QualType rhs) {
8201 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008202 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8203 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008204 if (lhsOPT && rhsOPT)
8205 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8206
8207 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008208 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8209 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008210 if (lhsBlock && rhsBlock)
8211 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8212
8213 // If either is an unqualified 'id' and the other is a block, it's
8214 // acceptable.
8215 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8216 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8217 return true;
8218
8219 return false;
8220}
8221
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008222// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008223static bool sameObjCTypeArgs(ASTContext &ctx,
8224 const ObjCInterfaceDecl *iface,
8225 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00008226 ArrayRef<QualType> rhsArgs,
8227 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008228 if (lhsArgs.size() != rhsArgs.size())
8229 return false;
8230
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008231 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008232 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008233 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8234 continue;
8235
8236 switch (typeParams->begin()[i]->getVariance()) {
8237 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00008238 if (!stripKindOf ||
8239 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8240 rhsArgs[i].stripObjCKindOfType(ctx))) {
8241 return false;
8242 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008243 break;
8244
8245 case ObjCTypeParamVariance::Covariant:
8246 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8247 return false;
8248 break;
8249
8250 case ObjCTypeParamVariance::Contravariant:
8251 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8252 return false;
8253 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00008254 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008255 }
8256
8257 return true;
8258}
8259
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008260QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008261 const ObjCObjectPointerType *Lptr,
8262 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008263 const ObjCObjectType *LHS = Lptr->getObjectType();
8264 const ObjCObjectType *RHS = Rptr->getObjectType();
8265 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8266 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008267
8268 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008269 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008270
Manman Renc46f7d12016-05-06 19:35:02 +00008271 // When either LHS or RHS is a kindof type, we should return a kindof type.
8272 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8273 // kindof(A).
8274 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8275
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008276 // Follow the left-hand side up the class hierarchy until we either hit a
8277 // root or find the RHS. Record the ancestors in case we don't find it.
8278 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8279 LHSAncestors;
8280 while (true) {
8281 // Record this ancestor. We'll need this if the common type isn't in the
8282 // path from the LHS to the root.
8283 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008284
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008285 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8286 // Get the type arguments.
8287 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8288 bool anyChanges = false;
8289 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8290 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008291 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8292 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008293 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008294 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008295 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8296 // If only one has type arguments, the result will not have type
8297 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008298 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008299 anyChanges = true;
8300 }
8301
8302 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008303 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008304 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8305 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008306 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008307 anyChanges = true;
8308
8309 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008310 // If we need to return a kindof type but LHS is not a kindof type, we
8311 // build a new result type.
8312 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008313 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008314 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008315 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008316 return getObjCObjectPointerType(Result);
8317 }
8318
8319 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008320 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008321
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008322 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008323 QualType LHSSuperType = LHS->getSuperClassType();
8324 if (LHSSuperType.isNull())
8325 break;
8326
8327 LHS = LHSSuperType->castAs<ObjCObjectType>();
8328 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008329
8330 // We didn't find anything by following the LHS to its root; now check
8331 // the RHS against the cached set of ancestors.
8332 while (true) {
8333 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8334 if (KnownLHS != LHSAncestors.end()) {
8335 LHS = KnownLHS->second;
8336
8337 // Get the type arguments.
8338 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8339 bool anyChanges = false;
8340 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8341 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008342 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8343 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008344 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008345 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008346 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8347 // If only one has type arguments, the result will not have type
8348 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008349 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008350 anyChanges = true;
8351 }
8352
8353 // Compute the intersection of protocols.
8354 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8355 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8356 Protocols);
8357 if (!Protocols.empty())
8358 anyChanges = true;
8359
Manman Renc46f7d12016-05-06 19:35:02 +00008360 // If we need to return a kindof type but RHS is not a kindof type, we
8361 // build a new result type.
8362 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008363 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008364 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008365 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008366 return getObjCObjectPointerType(Result);
8367 }
8368
8369 return getObjCObjectPointerType(QualType(RHS, 0));
8370 }
8371
8372 // Find the superclass of the RHS.
8373 QualType RHSSuperType = RHS->getSuperClassType();
8374 if (RHSSuperType.isNull())
8375 break;
8376
8377 RHS = RHSSuperType->castAs<ObjCObjectType>();
8378 }
8379
Eugene Zelenko7855e772018-04-03 00:11:50 +00008380 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008381}
8382
John McCall8b07ec22010-05-15 11:32:37 +00008383bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8384 const ObjCObjectType *RHS) {
8385 assert(LHS->getInterface() && "LHS is not an interface type");
8386 assert(RHS->getInterface() && "RHS is not an interface type");
8387
Chris Lattner49af6a42008-04-07 06:51:04 +00008388 // Verify that the base decls are compatible: the RHS must be a subclass of
8389 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008390 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8391 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8392 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008393 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008394
Douglas Gregore83b9562015-07-07 03:57:53 +00008395 // If the LHS has protocol qualifiers, determine whether all of them are
8396 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8397 // LHS).
8398 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008399 // OK if conversion of LHS to SuperClass results in narrowing of types
8400 // ; i.e., SuperClass may implement at least one of the protocols
8401 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8402 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8403 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8404 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8405 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8406 // qualifiers.
8407 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008408 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008409 // If there is no protocols associated with RHS, it is not a match.
8410 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008411 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008412
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008413 for (const auto *LHSProto : LHS->quals()) {
8414 bool SuperImplementsProtocol = false;
8415 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8416 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8417 SuperImplementsProtocol = true;
8418 break;
8419 }
8420 if (!SuperImplementsProtocol)
8421 return false;
8422 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008423 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008424
8425 // If the LHS is specialized, we may need to check type arguments.
8426 if (LHS->isSpecialized()) {
8427 // Follow the superclass chain until we've matched the LHS class in the
8428 // hierarchy. This substitutes type arguments through.
8429 const ObjCObjectType *RHSSuper = RHS;
8430 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8431 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8432
8433 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008434 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008435 !sameObjCTypeArgs(*this, LHS->getInterface(),
8436 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008437 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008438 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008439 }
8440 }
8441
8442 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008443}
8444
Steve Naroffb7605152009-02-12 17:52:19 +00008445bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8446 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008447 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8448 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008449
Steve Naroff7cae42b2009-07-10 23:34:53 +00008450 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008451 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008452
8453 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8454 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008455}
8456
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008457bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8458 return canAssignObjCInterfaces(
8459 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8460 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8461}
8462
Mike Stump11289f42009-09-09 15:08:12 +00008463/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008464/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008465/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008466/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008467bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8468 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008469 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008470 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008471
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008472 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008473}
8474
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008475bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008476 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008477}
8478
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008479bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8480 return !mergeTypes(LHS, RHS, true).isNull();
8481}
8482
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008483/// mergeTransparentUnionType - if T is a transparent union type and a member
8484/// of T is compatible with SubType, return the merged type, else return
8485/// QualType()
8486QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8487 bool OfBlockPointer,
8488 bool Unqualified) {
8489 if (const RecordType *UT = T->getAsUnionType()) {
8490 RecordDecl *UD = UT->getDecl();
8491 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008492 for (const auto *I : UD->fields()) {
8493 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008494 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8495 if (!MT.isNull())
8496 return MT;
8497 }
8498 }
8499 }
8500
Eugene Zelenko7855e772018-04-03 00:11:50 +00008501 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008502}
8503
Alp Toker9cacbab2014-01-20 20:26:09 +00008504/// mergeFunctionParameterTypes - merge two types which appear as function
8505/// parameter types
8506QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8507 bool OfBlockPointer,
8508 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008509 // GNU extension: two types are compatible if they appear as a function
8510 // argument, one of the types is a transparent union type and the other
8511 // type is compatible with a union member
8512 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8513 Unqualified);
8514 if (!lmerge.isNull())
8515 return lmerge;
8516
8517 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8518 Unqualified);
8519 if (!rmerge.isNull())
8520 return rmerge;
8521
8522 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8523}
8524
Fangrui Song6907ce22018-07-30 19:24:48 +00008525QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008526 bool OfBlockPointer,
8527 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008528 const auto *lbase = lhs->getAs<FunctionType>();
8529 const auto *rbase = rhs->getAs<FunctionType>();
8530 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8531 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008532 bool allLTypes = true;
8533 bool allRTypes = true;
8534
8535 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008536 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008537 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008538 QualType RHS = rbase->getReturnType();
8539 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008540 bool UnqualifiedResult = Unqualified;
8541 if (!UnqualifiedResult)
8542 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008543 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008544 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008545 else
Alp Toker314cc812014-01-25 16:55:45 +00008546 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008547 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008548 if (retType.isNull())
8549 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00008550
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008551 if (Unqualified)
8552 retType = retType.getUnqualifiedType();
8553
Alp Toker314cc812014-01-25 16:55:45 +00008554 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8555 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008556 if (Unqualified) {
8557 LRetType = LRetType.getUnqualifiedType();
8558 RRetType = RRetType.getUnqualifiedType();
8559 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008560
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008561 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008562 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008563 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008564 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008565
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008566 // FIXME: double check this
8567 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8568 // rbase->getRegParmAttr() != 0 &&
8569 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008570 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8571 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008572
Douglas Gregor8c940862010-01-18 17:14:39 +00008573 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008574 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008575 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008576
John McCall8c6b56f2010-12-15 01:06:38 +00008577 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008578 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008579 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008580 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008581 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008582
John McCall31168b02011-06-15 23:02:42 +00008583 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008584 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008585 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008586 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008587 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008588 return {};
John McCall31168b02011-06-15 23:02:42 +00008589
John McCall8c6b56f2010-12-15 01:06:38 +00008590 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8591 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008592
Rafael Espindola8778c282012-11-29 16:09:03 +00008593 if (lbaseInfo.getNoReturn() != NoReturn)
8594 allLTypes = false;
8595 if (rbaseInfo.getNoReturn() != NoReturn)
8596 allRTypes = false;
8597
John McCall31168b02011-06-15 23:02:42 +00008598 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008599
Eli Friedman47f77112008-08-22 00:56:42 +00008600 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008601 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8602 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008603 // Compatible functions must have the same number of parameters
8604 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008605 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008606
8607 // Variadic and non-variadic functions aren't compatible
8608 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008609 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008610
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008611 if (lproto->getMethodQuals() != rproto->getMethodQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008612 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008613
Akira Hatanaka98a49332017-09-22 00:41:05 +00008614 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8615 bool canUseLeft, canUseRight;
8616 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8617 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008618 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008619
Akira Hatanaka98a49332017-09-22 00:41:05 +00008620 if (!canUseLeft)
8621 allLTypes = false;
8622 if (!canUseRight)
8623 allRTypes = false;
8624
Alp Toker601b22c2014-01-21 23:35:24 +00008625 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008626 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008627 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8628 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8629 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8630 QualType paramType = mergeFunctionParameterTypes(
8631 lParamType, rParamType, OfBlockPointer, Unqualified);
8632 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008633 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008634
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008635 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008636 paramType = paramType.getUnqualifiedType();
8637
8638 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008639 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008640 lParamType = lParamType.getUnqualifiedType();
8641 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008642 }
Alp Toker601b22c2014-01-21 23:35:24 +00008643
8644 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008645 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008646 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008647 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008648 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008649
Eli Friedman47f77112008-08-22 00:56:42 +00008650 if (allLTypes) return lhs;
8651 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008652
8653 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8654 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008655 EPI.ExtParameterInfos =
8656 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008657 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008658 }
8659
8660 if (lproto) allRTypes = false;
8661 if (rproto) allLTypes = false;
8662
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008663 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008664 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008665 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008666 if (proto->isVariadic())
8667 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008668 // Check that the types are compatible with the types that
8669 // would result from default argument promotions (C99 6.7.5.3p15).
8670 // The only types actually affected are promotable integer
8671 // types and floats, which would be passed as a different
8672 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008673 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8674 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008675
Eli Friedman448ce402012-08-30 00:44:15 +00008676 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008677 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008678 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008679 paramTy = Enum->getDecl()->getIntegerType();
8680 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008681 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008682 }
Alp Toker601b22c2014-01-21 23:35:24 +00008683
8684 if (paramTy->isPromotableIntegerType() ||
8685 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008686 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008687 }
8688
8689 if (allLTypes) return lhs;
8690 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008691
8692 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8693 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008694 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008695 }
8696
8697 if (allLTypes) return lhs;
8698 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008699 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008700}
8701
John McCall433c2e62013-03-21 00:10:07 +00008702/// Given that we have an enum type and a non-enum type, try to merge them.
8703static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8704 QualType other, bool isBlockReturnType) {
8705 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8706 // a signed integer type, or an unsigned integer type.
8707 // Compatibility is based on the underlying type, not the promotion
8708 // type.
8709 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008710 if (underlyingType.isNull())
8711 return {};
John McCall433c2e62013-03-21 00:10:07 +00008712 if (Context.hasSameType(underlyingType, other))
8713 return other;
8714
8715 // In block return types, we're more permissive and accept any
8716 // integral type of the same size.
8717 if (isBlockReturnType && other->isIntegerType() &&
8718 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8719 return other;
8720
Eugene Zelenko7855e772018-04-03 00:11:50 +00008721 return {};
John McCall433c2e62013-03-21 00:10:07 +00008722}
8723
Fangrui Song6907ce22018-07-30 19:24:48 +00008724QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008725 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008726 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008727 // C++ [expr]: If an expression initially has the type "reference to T", the
8728 // type is adjusted to "T" prior to any further analysis, the expression
8729 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008730 // expression is an lvalue unless the reference is an rvalue reference and
8731 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008732 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8733 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008734
8735 if (Unqualified) {
8736 LHS = LHS.getUnqualifiedType();
8737 RHS = RHS.getUnqualifiedType();
8738 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008739
Eli Friedman47f77112008-08-22 00:56:42 +00008740 QualType LHSCan = getCanonicalType(LHS),
8741 RHSCan = getCanonicalType(RHS);
8742
8743 // If two types are identical, they are compatible.
8744 if (LHSCan == RHSCan)
8745 return LHS;
8746
John McCall8ccfcb52009-09-24 19:53:00 +00008747 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008748 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8749 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008750 if (LQuals != RQuals) {
8751 // If any of these qualifiers are different, we have a type
8752 // mismatch.
8753 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008754 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008755 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8756 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008757 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008758
8759 // Exactly one GC qualifier difference is allowed: __strong is
8760 // okay if the other type has no GC qualifier but is an Objective
8761 // C object pointer (i.e. implicitly strong by default). We fix
8762 // this by pretending that the unqualified type was actually
8763 // qualified __strong.
8764 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8765 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8766 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8767
8768 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008769 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008770
8771 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8772 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8773 }
8774 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8775 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8776 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008777 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008778 }
8779
8780 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008781
Eli Friedmandcca6332009-06-01 01:22:52 +00008782 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8783 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008784
Chris Lattnerfd652912008-01-14 05:45:46 +00008785 // We want to consider the two function types to be the same for these
8786 // comparisons, just force one to the other.
8787 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8788 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008789
8790 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008791 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8792 LHSClass = Type::ConstantArray;
8793 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8794 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008795
John McCall8b07ec22010-05-15 11:32:37 +00008796 // ObjCInterfaces are just specialized ObjCObjects.
8797 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8798 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8799
Nate Begemance4d7fc2008-04-18 23:10:10 +00008800 // Canonicalize ExtVector -> Vector.
8801 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8802 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008803
Chris Lattner95554662008-04-07 05:43:21 +00008804 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008805 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008806 // Note that we only have special rules for turning block enum
8807 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008808 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008809 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008810 }
John McCall9dd450b2009-09-21 23:43:11 +00008811 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008812 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008813 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008814 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008815 if (OfBlockPointer && !BlockReturnType) {
8816 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8817 return LHS;
8818 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8819 return RHS;
8820 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008821
Eugene Zelenko7855e772018-04-03 00:11:50 +00008822 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008823 }
Eli Friedman47f77112008-08-22 00:56:42 +00008824
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008825 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008826 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008827#define TYPE(Class, Base)
8828#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008829#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008830#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8831#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8832#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008833 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008834
Richard Smith27d807c2013-04-30 13:56:41 +00008835 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008836 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008837 case Type::LValueReference:
8838 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008839 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008840 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008841
John McCall8b07ec22010-05-15 11:32:37 +00008842 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008843 case Type::IncompleteArray:
8844 case Type::VariableArray:
8845 case Type::FunctionProto:
8846 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008847 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008848
Chris Lattnerfd652912008-01-14 05:45:46 +00008849 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008850 {
8851 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008852 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8853 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008854 if (Unqualified) {
8855 LHSPointee = LHSPointee.getUnqualifiedType();
8856 RHSPointee = RHSPointee.getUnqualifiedType();
8857 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008858 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008859 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008860 if (ResultType.isNull())
8861 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008862 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008863 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008864 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008865 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008866 return getPointerType(ResultType);
8867 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008868 case Type::BlockPointer:
8869 {
8870 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008871 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8872 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008873 if (Unqualified) {
8874 LHSPointee = LHSPointee.getUnqualifiedType();
8875 RHSPointee = RHSPointee.getUnqualifiedType();
8876 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008877 if (getLangOpts().OpenCL) {
8878 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8879 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8880 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8881 // 6.12.5) thus the following check is asymmetric.
8882 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008883 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008884 LHSPteeQual.removeAddressSpace();
8885 RHSPteeQual.removeAddressSpace();
8886 LHSPointee =
8887 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8888 RHSPointee =
8889 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8890 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008891 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8892 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008893 if (ResultType.isNull())
8894 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00008895 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8896 return LHS;
8897 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8898 return RHS;
8899 return getBlockPointerType(ResultType);
8900 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008901 case Type::Atomic:
8902 {
8903 // Merge two pointer types, while trying to preserve typedef info
8904 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8905 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8906 if (Unqualified) {
8907 LHSValue = LHSValue.getUnqualifiedType();
8908 RHSValue = RHSValue.getUnqualifiedType();
8909 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008910 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
Eli Friedman0dfb8892011-10-06 23:00:33 +00008911 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008912 if (ResultType.isNull())
8913 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00008914 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8915 return LHS;
8916 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8917 return RHS;
8918 return getAtomicType(ResultType);
8919 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008920 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008921 {
8922 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8923 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8924 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008925 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008926
8927 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8928 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008929 if (Unqualified) {
8930 LHSElem = LHSElem.getUnqualifiedType();
8931 RHSElem = RHSElem.getUnqualifiedType();
8932 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008933
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008934 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008935 if (ResultType.isNull())
8936 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00008937
8938 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8939 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8940
8941 // If either side is a variable array, and both are complete, check whether
8942 // the current dimension is definite.
8943 if (LVAT || RVAT) {
8944 auto SizeFetch = [this](const VariableArrayType* VAT,
8945 const ConstantArrayType* CAT)
8946 -> std::pair<bool,llvm::APInt> {
8947 if (VAT) {
8948 llvm::APSInt TheInt;
8949 Expr *E = VAT->getSizeExpr();
8950 if (E && E->isIntegerConstantExpr(TheInt, *this))
8951 return std::make_pair(true, TheInt);
8952 else
8953 return std::make_pair(false, TheInt);
8954 } else if (CAT) {
8955 return std::make_pair(true, CAT->getSize());
8956 } else {
8957 return std::make_pair(false, llvm::APInt());
8958 }
8959 };
8960
8961 bool HaveLSize, HaveRSize;
8962 llvm::APInt LSize, RSize;
8963 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
8964 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
8965 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
8966 return {}; // Definite, but unequal, array dimension
8967 }
8968
Chris Lattner465fa322008-10-05 17:34:18 +00008969 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8970 return LHS;
8971 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8972 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008973 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8974 ArrayType::ArraySizeModifier(), 0);
8975 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8976 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00008977 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8978 return LHS;
8979 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8980 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008981 if (LVAT) {
8982 // FIXME: This isn't correct! But tricky to implement because
8983 // the array's size has to be the size of LHS, but the type
8984 // has to be different.
8985 return LHS;
8986 }
8987 if (RVAT) {
8988 // FIXME: This isn't correct! But tricky to implement because
8989 // the array's size has to be the size of RHS, but the type
8990 // has to be different.
8991 return RHS;
8992 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008993 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8994 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008995 return getIncompleteArrayType(ResultType,
8996 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008997 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008998 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008999 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009000 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009001 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00009002 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00009003 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009004 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009005 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00009006 case Type::Complex:
9007 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009008 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009009 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00009010 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00009011 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
9012 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00009013 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009014 return {};
John McCall8b07ec22010-05-15 11:32:37 +00009015 case Type::ObjCObject: {
9016 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00009017 // FIXME: This should be type compatibility, e.g. whether
9018 // "LHS x; RHS x;" at global scope is legal.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009019 const auto *LHSIface = LHS->getAs<ObjCObjectType>();
9020 const auto *RHSIface = RHS->getAs<ObjCObjectType>();
John McCall8b07ec22010-05-15 11:32:37 +00009021 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00009022 return LHS;
9023
Eugene Zelenko7855e772018-04-03 00:11:50 +00009024 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00009025 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009026 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009027 if (OfBlockPointer) {
9028 if (canAssignObjCInterfacesInBlockPointer(
9029 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00009030 RHS->getAs<ObjCObjectPointerType>(),
9031 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00009032 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009033 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009034 }
John McCall9dd450b2009-09-21 23:43:11 +00009035 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
9036 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00009037 return LHS;
9038
Eugene Zelenko7855e772018-04-03 00:11:50 +00009039 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009040 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00009041 assert(LHS != RHS &&
9042 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00009043 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009044 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009045
David Blaikie8a40f702012-01-17 06:56:22 +00009046 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00009047}
Ted Kremenekfc581a92007-10-31 17:10:13 +00009048
Akira Hatanaka98a49332017-09-22 00:41:05 +00009049bool ASTContext::mergeExtParameterInfo(
9050 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9051 bool &CanUseFirst, bool &CanUseSecond,
9052 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9053 assert(NewParamInfos.empty() && "param info list not empty");
9054 CanUseFirst = CanUseSecond = true;
9055 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9056 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9057
John McCall18afab72016-03-01 00:49:02 +00009058 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00009059 // we match if and only if the second type also doesn't have them.
9060 if (!FirstHasInfo && !SecondHasInfo)
9061 return true;
John McCall18afab72016-03-01 00:49:02 +00009062
Akira Hatanaka98a49332017-09-22 00:41:05 +00009063 bool NeedParamInfo = false;
9064 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9065 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00009066
Akira Hatanaka98a49332017-09-22 00:41:05 +00009067 for (size_t I = 0; I < E; ++I) {
9068 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9069 if (FirstHasInfo)
9070 FirstParam = FirstFnType->getExtParameterInfo(I);
9071 if (SecondHasInfo)
9072 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00009073
Akira Hatanaka98a49332017-09-22 00:41:05 +00009074 // Cannot merge unless everything except the noescape flag matches.
9075 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00009076 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00009077
9078 bool FirstNoEscape = FirstParam.isNoEscape();
9079 bool SecondNoEscape = SecondParam.isNoEscape();
9080 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9081 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9082 if (NewParamInfos.back().getOpaqueValue())
9083 NeedParamInfo = true;
9084 if (FirstNoEscape != IsNoEscape)
9085 CanUseFirst = false;
9086 if (SecondNoEscape != IsNoEscape)
9087 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00009088 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00009089
9090 if (!NeedParamInfo)
9091 NewParamInfos.clear();
9092
Fariborz Jahanian97676972011-09-28 21:52:05 +00009093 return true;
9094}
9095
Chandler Carruth21c90602015-12-30 03:24:14 +00009096void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9097 ObjCLayouts[CD] = nullptr;
9098}
9099
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009100/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9101/// 'RHS' attributes and returns the merged version; including for function
9102/// return types.
9103QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9104 QualType LHSCan = getCanonicalType(LHS),
9105 RHSCan = getCanonicalType(RHS);
9106 // If two types are identical, they are compatible.
9107 if (LHSCan == RHSCan)
9108 return LHS;
9109 if (RHSCan->isFunctionType()) {
9110 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009111 return {};
Alp Toker314cc812014-01-25 16:55:45 +00009112 QualType OldReturnType =
9113 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009114 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00009115 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009116 QualType ResReturnType =
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009117 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9118 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009119 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009120 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9121 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9122 // In either case, use OldReturnType to build the new function type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009123 const auto *F = LHS->getAs<FunctionType>();
9124 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009125 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9126 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00009127 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00009128 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009129 return ResultType;
9130 }
9131 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009132 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009133 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009134
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009135 // If the qualifiers are different, the types can still be merged.
9136 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9137 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9138 if (LQuals != RQuals) {
9139 // If any of these qualifiers are different, we have a type mismatch.
9140 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9141 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009142 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009143
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009144 // Exactly one GC qualifier difference is allowed: __strong is
9145 // okay if the other type has no GC qualifier but is an Objective
9146 // C object pointer (i.e. implicitly strong by default). We fix
9147 // this by pretending that the unqualified type was actually
9148 // qualified __strong.
9149 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9150 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9151 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
Fangrui Song6907ce22018-07-30 19:24:48 +00009152
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009153 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009154 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009155
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009156 if (GC_L == Qualifiers::Strong)
9157 return LHS;
9158 if (GC_R == Qualifiers::Strong)
9159 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009160 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009161 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009162
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009163 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9164 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9165 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9166 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9167 if (ResQT == LHSBaseQT)
9168 return LHS;
9169 if (ResQT == RHSBaseQT)
9170 return RHS;
9171 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009172 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009173}
9174
Chris Lattner4ba0cef2008-04-07 07:01:58 +00009175//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009176// Integer Predicates
9177//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00009178
Jay Foad39c79802011-01-12 09:06:06 +00009179unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009180 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00009181 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009182 if (T->isBooleanType())
9183 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00009184 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009185 return (unsigned)getTypeSize(T);
9186}
9187
Abramo Bagnara13640492012-09-09 10:21:24 +00009188QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00009189 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9190 "Unexpected type");
Fangrui Song6907ce22018-07-30 19:24:48 +00009191
Chris Lattnerec3a1562009-10-17 20:33:28 +00009192 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00009193 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00009194 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00009195 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00009196
9197 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009198 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009199 T = ETy->getDecl()->getIntegerType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009200
Eugene Zelenko7855e772018-04-03 00:11:50 +00009201 const auto *BTy = T->getAs<BuiltinType>();
Leonard Chanab80f3c2018-06-14 14:53:51 +00009202 assert(BTy && "Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009203 switch (BTy->getKind()) {
9204 case BuiltinType::Char_S:
9205 case BuiltinType::SChar:
9206 return UnsignedCharTy;
9207 case BuiltinType::Short:
9208 return UnsignedShortTy;
9209 case BuiltinType::Int:
9210 return UnsignedIntTy;
9211 case BuiltinType::Long:
9212 return UnsignedLongTy;
9213 case BuiltinType::LongLong:
9214 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00009215 case BuiltinType::Int128:
9216 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00009217
9218 case BuiltinType::ShortAccum:
9219 return UnsignedShortAccumTy;
9220 case BuiltinType::Accum:
9221 return UnsignedAccumTy;
9222 case BuiltinType::LongAccum:
9223 return UnsignedLongAccumTy;
9224 case BuiltinType::SatShortAccum:
9225 return SatUnsignedShortAccumTy;
9226 case BuiltinType::SatAccum:
9227 return SatUnsignedAccumTy;
9228 case BuiltinType::SatLongAccum:
9229 return SatUnsignedLongAccumTy;
9230 case BuiltinType::ShortFract:
9231 return UnsignedShortFractTy;
9232 case BuiltinType::Fract:
9233 return UnsignedFractTy;
9234 case BuiltinType::LongFract:
9235 return UnsignedLongFractTy;
9236 case BuiltinType::SatShortFract:
9237 return SatUnsignedShortFractTy;
9238 case BuiltinType::SatFract:
9239 return SatUnsignedFractTy;
9240 case BuiltinType::SatLongFract:
9241 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009242 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009243 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009244 }
9245}
9246
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009247ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00009248
Richard Smith1fa5d642013-05-11 05:45:24 +00009249void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9250 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00009251
9252//===----------------------------------------------------------------------===//
9253// Builtin Type Computation
9254//===----------------------------------------------------------------------===//
9255
9256/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00009257/// pointer over the consumed characters. This returns the resultant type. If
9258/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9259/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9260/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009261///
9262/// RequiresICE is filled in on return to indicate whether the value is required
9263/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009264static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009265 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009266 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009267 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009268 // Modifiers.
9269 int HowLong = 0;
9270 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009271 RequiresICE = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009272
Chris Lattnerdc226c22010-10-01 22:42:38 +00009273 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009274 bool Done = false;
9275 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009276 bool IsSpecial = false;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009277 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009278 while (!Done) {
9279 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009280 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009281 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009282 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009283 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009284 case 'S':
9285 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9286 assert(!Signed && "Can't use 'S' modifier multiple times!");
9287 Signed = true;
9288 break;
9289 case 'U':
9290 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009291 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009292 Unsigned = true;
9293 break;
9294 case 'L':
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009295 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009296 assert(HowLong <= 2 && "Can't have LLLL modifier");
9297 ++HowLong;
9298 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009299 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009300 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009301 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009302 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009303 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009304 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009305 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009306 if (Context.getTargetInfo().getLongWidth() == 32)
9307 ++HowLong;
9308 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009309 case 'W':
9310 // This modifier represents int64 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009311 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009312 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009313 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009314 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009315 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009316 switch (Context.getTargetInfo().getInt64Type()) {
9317 default:
9318 llvm_unreachable("Unexpected integer type");
9319 case TargetInfo::SignedLong:
9320 HowLong = 1;
9321 break;
9322 case TargetInfo::SignedLongLong:
9323 HowLong = 2;
9324 break;
9325 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009326 break;
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009327 case 'Z':
9328 // This modifier represents int32 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009329 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009330 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
9331 #ifndef NDEBUG
9332 IsSpecial = true;
9333 #endif
9334 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
9335 default:
9336 llvm_unreachable("Unexpected integer type");
9337 case TargetInfo::SignedInt:
9338 HowLong = 0;
9339 break;
9340 case TargetInfo::SignedLong:
9341 HowLong = 1;
9342 break;
9343 case TargetInfo::SignedLongLong:
9344 HowLong = 2;
9345 break;
9346 }
9347 break;
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009348 case 'O':
9349 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9350 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
9351 #ifndef NDEBUG
9352 IsSpecial = true;
9353 #endif
9354 if (Context.getLangOpts().OpenCL)
9355 HowLong = 1;
9356 else
9357 HowLong = 2;
9358 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009359 }
9360 }
9361
9362 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009363
Chris Lattnerecd79c62009-06-14 00:45:47 +00009364 // Read the base type.
9365 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009366 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009367 case 'v':
9368 assert(HowLong == 0 && !Signed && !Unsigned &&
9369 "Bad modifiers used with 'v'!");
9370 Type = Context.VoidTy;
9371 break;
Jack Carter24bef982013-08-15 15:16:57 +00009372 case 'h':
9373 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009374 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009375 Type = Context.HalfTy;
9376 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009377 case 'f':
9378 assert(HowLong == 0 && !Signed && !Unsigned &&
9379 "Bad modifiers used with 'f'!");
9380 Type = Context.FloatTy;
9381 break;
9382 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009383 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009384 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009385 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009386 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009387 else if (HowLong == 2)
9388 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009389 else
9390 Type = Context.DoubleTy;
9391 break;
9392 case 's':
9393 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9394 if (Unsigned)
9395 Type = Context.UnsignedShortTy;
9396 else
9397 Type = Context.ShortTy;
9398 break;
9399 case 'i':
9400 if (HowLong == 3)
9401 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9402 else if (HowLong == 2)
9403 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9404 else if (HowLong == 1)
9405 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9406 else
9407 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9408 break;
9409 case 'c':
9410 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9411 if (Signed)
9412 Type = Context.SignedCharTy;
9413 else if (Unsigned)
9414 Type = Context.UnsignedCharTy;
9415 else
9416 Type = Context.CharTy;
9417 break;
9418 case 'b': // boolean
9419 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9420 Type = Context.BoolTy;
9421 break;
9422 case 'z': // size_t.
9423 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9424 Type = Context.getSizeType();
9425 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009426 case 'w': // wchar_t.
9427 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9428 Type = Context.getWideCharType();
9429 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009430 case 'F':
9431 Type = Context.getCFConstantStringType();
9432 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009433 case 'G':
9434 Type = Context.getObjCIdType();
9435 break;
9436 case 'H':
9437 Type = Context.getObjCSelType();
9438 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009439 case 'M':
9440 Type = Context.getObjCSuperType();
9441 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009442 case 'a':
9443 Type = Context.getBuiltinVaListType();
9444 assert(!Type.isNull() && "builtin va list type not initialized!");
9445 break;
9446 case 'A':
9447 // This is a "reference" to a va_list; however, what exactly
9448 // this means depends on how va_list is defined. There are two
9449 // different kinds of va_list: ones passed by value, and ones
9450 // passed by reference. An example of a by-value va_list is
9451 // x86, where va_list is a char*. An example of by-ref va_list
9452 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9453 // we want this argument to be a char*&; for x86-64, we want
9454 // it to be a __va_list_tag*.
9455 Type = Context.getBuiltinVaListType();
9456 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009457 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009458 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009459 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009460 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009461 break;
9462 case 'V': {
9463 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009464 unsigned NumElements = strtoul(Str, &End, 10);
9465 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009466 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009467
Fangrui Song6907ce22018-07-30 19:24:48 +00009468 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009469 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009470 assert(!RequiresICE && "Can't require vector ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009471
Chris Lattnerdc226c22010-10-01 22:42:38 +00009472 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009473 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009474 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009475 break;
9476 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009477 case 'E': {
9478 char *End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009479
Douglas Gregorfed66992012-06-07 18:08:25 +00009480 unsigned NumElements = strtoul(Str, &End, 10);
9481 assert(End != Str && "Missing vector size");
Fangrui Song6907ce22018-07-30 19:24:48 +00009482
Douglas Gregorfed66992012-06-07 18:08:25 +00009483 Str = End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009484
Douglas Gregorfed66992012-06-07 18:08:25 +00009485 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009486 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009487 Type = Context.getExtVectorType(ElementType, NumElements);
Fangrui Song6907ce22018-07-30 19:24:48 +00009488 break;
Douglas Gregorfed66992012-06-07 18:08:25 +00009489 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009490 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009491 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009492 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009493 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009494 Type = Context.getComplexType(ElementType);
9495 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00009496 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009497 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009498 Type = Context.getPointerDiffType();
9499 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009500 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009501 Type = Context.getFILEType();
9502 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009503 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009504 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009505 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009506 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009507 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009508 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009509 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009510 else
9511 Type = Context.getjmp_bufType();
9512
Mike Stump2adb4da2009-07-28 23:47:15 +00009513 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009514 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009515 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009516 }
9517 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009518 case 'K':
9519 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9520 Type = Context.getucontext_tType();
9521
9522 if (Type.isNull()) {
9523 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009524 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009525 }
9526 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009527 case 'p':
9528 Type = Context.getProcessIDType();
9529 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009530 }
Mike Stump11289f42009-09-09 15:08:12 +00009531
Chris Lattnerdc226c22010-10-01 22:42:38 +00009532 // If there are modifiers and if we're allowed to parse them, go for it.
9533 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009534 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009535 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009536 default: Done = true; --Str; break;
9537 case '*':
9538 case '&': {
9539 // Both pointers and references can have their pointee types
9540 // qualified with an address space.
9541 char *End;
9542 unsigned AddrSpace = strtoul(Str, &End, 10);
Matt Arsenaultc65f9662018-08-02 12:14:28 +00009543 if (End != Str) {
9544 // Note AddrSpace == 0 is not the same as an unspecified address space.
9545 Type = Context.getAddrSpaceQualType(
9546 Type,
9547 Context.getLangASForBuiltinAddressSpace(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009548 Str = End;
9549 }
9550 if (c == '*')
9551 Type = Context.getPointerType(Type);
9552 else
9553 Type = Context.getLValueReferenceType(Type);
9554 break;
9555 }
9556 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9557 case 'C':
9558 Type = Type.withConst();
9559 break;
9560 case 'D':
9561 Type = Context.getVolatileType(Type);
9562 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009563 case 'R':
9564 Type = Type.withRestrict();
9565 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009566 }
9567 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009568
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009569 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Fangrui Song6907ce22018-07-30 19:24:48 +00009570 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009571
Chris Lattnerecd79c62009-06-14 00:45:47 +00009572 return Type;
9573}
9574
9575/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009576QualType ASTContext::GetBuiltinType(unsigned Id,
9577 GetBuiltinTypeError &Error,
9578 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009579 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00009580 if (TypeStr[0] == '\0') {
9581 Error = GE_Missing_type;
9582 return {};
9583 }
Mike Stump11289f42009-09-09 15:08:12 +00009584
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009585 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009586
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009587 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009588 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009589 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9590 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009591 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009592 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009593
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009594 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009595
Chris Lattnerecd79c62009-06-14 00:45:47 +00009596 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009597 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009598 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009599 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009600
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009601 // If this argument is required to be an IntegerConstantExpression and the
9602 // caller cares, fill in the bitmask we return.
9603 if (RequiresICE && IntegerConstantArgs)
9604 *IntegerConstantArgs |= 1 << ArgTypes.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00009605
Chris Lattnerecd79c62009-06-14 00:45:47 +00009606 // Do array -> pointer decay. The builtin should use the decayed type.
9607 if (Ty->isArrayType())
9608 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009609
Chris Lattnerecd79c62009-06-14 00:45:47 +00009610 ArgTypes.push_back(Ty);
9611 }
9612
David Majnemerba3e5ec2015-03-13 18:26:17 +00009613 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009614 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009615
Chris Lattnerecd79c62009-06-14 00:45:47 +00009616 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9617 "'.' should only occur at end of builtin type list!");
9618
Erich Keane881e83d2019-03-04 14:54:52 +00009619 bool Variadic = (TypeStr[0] == '.');
9620
Erich Keane00022812019-05-23 16:05:21 +00009621 FunctionType::ExtInfo EI(getDefaultCallingConvention(
9622 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
John McCall991eb4b2010-12-21 00:44:39 +00009623 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9624
John McCall991eb4b2010-12-21 00:44:39 +00009625
Richard Smith836de6b2016-12-19 23:59:34 +00009626 // We really shouldn't be making a no-proto type here.
9627 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009628 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009629
John McCalldb40c7f2010-12-14 08:05:40 +00009630 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009631 EPI.ExtInfo = EI;
9632 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009633 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9634 EPI.ExceptionSpec.Type =
9635 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009636
Jordan Rose5c382722013-03-08 21:51:21 +00009637 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009638}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009639
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009640static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9641 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009642 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009643 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009644
Richard Smithe2467b72017-11-16 23:54:56 +00009645 // Non-user-provided functions get emitted as weak definitions with every
9646 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009647 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009648 if (!MD->isUserProvided())
9649 return GVA_DiscardableODR;
9650
Yaron Keren4cd211b2017-02-22 14:32:39 +00009651 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009652 switch (FD->getTemplateSpecializationKind()) {
9653 case TSK_Undeclared:
9654 case TSK_ExplicitSpecialization:
9655 External = GVA_StrongExternal;
9656 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009657
Rafael Espindola3ae00052013-05-13 00:12:11 +00009658 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009659 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009660
David Majnemerc3d07332014-05-15 06:25:57 +00009661 // C++11 [temp.explicit]p10:
9662 // [ Note: The intent is that an inline function that is the subject of
9663 // an explicit instantiation declaration will still be implicitly
9664 // instantiated when used so that the body can be considered for
9665 // inlining, but that no out-of-line copy of the inline function would be
9666 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009667 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009668 return GVA_AvailableExternally;
9669
Rafael Espindola3ae00052013-05-13 00:12:11 +00009670 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009671 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009672 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009673 }
9674
9675 if (!FD->isInlined())
9676 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009677
David Majnemer3f021502015-10-08 04:53:31 +00009678 if ((!Context.getLangOpts().CPlusPlus &&
9679 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009680 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009681 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009682 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9683
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009684 // GNU or C99 inline semantics. Determine whether this symbol should be
9685 // externally visible.
9686 if (FD->isInlineDefinitionExternallyVisible())
9687 return External;
9688
9689 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009690 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009691 }
9692
David Majnemer54e3ba52014-04-02 23:17:29 +00009693 // Functions specified with extern and inline in -fms-compatibility mode
9694 // forcibly get emitted. While the body of the function cannot be later
9695 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009696 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009697 return GVA_StrongODR;
9698
David Majnemer27d69db2014-04-28 22:17:59 +00009699 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009700}
9701
Artem Belevichca2b9512016-05-02 20:30:03 +00009702static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009703 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009704 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9705 // dllexport/dllimport on inline functions.
9706 if (D->hasAttr<DLLImportAttr>()) {
9707 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9708 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009709 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009710 if (L == GVA_DiscardableODR)
9711 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009712 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9713 D->hasAttr<CUDAGlobalAttr>()) {
9714 // Device-side functions with __global__ attribute must always be
9715 // visible externally so they can be launched from host.
9716 if (L == GVA_DiscardableODR || L == GVA_Internal)
9717 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009718 }
9719 return L;
9720}
9721
Richard Smitha4653622017-09-06 20:01:14 +00009722/// Adjust the GVALinkage for a declaration based on what an external AST source
9723/// knows about whether there can be other definitions of this declaration.
9724static GVALinkage
9725adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9726 GVALinkage L) {
9727 ExternalASTSource *Source = Ctx.getExternalSource();
9728 if (!Source)
9729 return L;
9730
9731 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009732 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009733 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009734 if (L == GVA_DiscardableODR)
9735 return GVA_StrongODR;
9736 break;
Richard Smitha4653622017-09-06 20:01:14 +00009737
David Blaikie9ffe5a32017-01-30 05:00:26 +00009738 case ExternalASTSource::EK_Always:
9739 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009740
David Blaikie9ffe5a32017-01-30 05:00:26 +00009741 case ExternalASTSource::EK_ReplyHazy:
9742 break;
9743 }
9744 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009745}
9746
Richard Smitha4653622017-09-06 20:01:14 +00009747GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9748 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9749 adjustGVALinkageForAttributes(*this, FD,
9750 basicGVALinkageForFunction(*this, FD)));
9751}
9752
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009753static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9754 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009755 if (!VD->isExternallyVisible())
9756 return GVA_Internal;
9757
David Majnemer27d69db2014-04-28 22:17:59 +00009758 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009759 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9760 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9761 LexicalContext = LexicalContext->getLexicalParent();
9762
David Blaikieeb210012017-01-27 23:11:10 +00009763 // ObjC Blocks can create local variables that don't have a FunctionDecl
9764 // LexicalContext.
9765 if (!LexicalContext)
9766 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009767
David Blaikieeb210012017-01-27 23:11:10 +00009768 // Otherwise, let the static local variable inherit its linkage from the
9769 // nearest enclosing function.
9770 auto StaticLocalLinkage =
9771 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9772
9773 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9774 // be emitted in any object with references to the symbol for the object it
9775 // contains, whether inline or out-of-line."
9776 // Similar behavior is observed with MSVC. An alternative ABI could use
9777 // StrongODR/AvailableExternally to match the function, but none are
9778 // known/supported currently.
9779 if (StaticLocalLinkage == GVA_StrongODR ||
9780 StaticLocalLinkage == GVA_AvailableExternally)
9781 return GVA_DiscardableODR;
9782 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009783 }
9784
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009785 // MSVC treats in-class initialized static data members as definitions.
9786 // By giving them non-strong linkage, out-of-line definitions won't
9787 // cause link errors.
9788 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9789 return GVA_DiscardableODR;
9790
Richard Smithd9b90092016-07-02 01:32:16 +00009791 // Most non-template variables have strong linkage; inline variables are
9792 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9793 GVALinkage StrongLinkage;
9794 switch (Context.getInlineVariableDefinitionKind(VD)) {
9795 case ASTContext::InlineVariableDefinitionKind::None:
9796 StrongLinkage = GVA_StrongExternal;
9797 break;
9798 case ASTContext::InlineVariableDefinitionKind::Weak:
9799 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009800 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009801 break;
9802 case ASTContext::InlineVariableDefinitionKind::Strong:
9803 StrongLinkage = GVA_StrongODR;
9804 break;
9805 }
Richard Smith62f19e72016-06-25 00:15:56 +00009806
Richard Smith8809a0c2013-09-27 20:14:12 +00009807 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009808 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009809 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009810
David Majnemer6d1780c2015-07-17 23:36:49 +00009811 case TSK_ExplicitSpecialization:
Reid Klecknere6f2ff22019-06-26 21:16:51 +00009812 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9813 VD->isStaticDataMember()
9814 ? GVA_StrongODR
9815 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009816
Rafael Espindola3ae00052013-05-13 00:12:11 +00009817 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009818 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009819
David Majnemer27d69db2014-04-28 22:17:59 +00009820 case TSK_ExplicitInstantiationDeclaration:
9821 return GVA_AvailableExternally;
9822
Rafael Espindola3ae00052013-05-13 00:12:11 +00009823 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009824 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009825 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009826
9827 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009828}
9829
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009830GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009831 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9832 adjustGVALinkageForAttributes(*this, VD,
9833 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009834}
9835
David Blaikiee6b7c282017-04-11 20:46:34 +00009836bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009837 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009838 if (!VD->isFileVarDecl())
9839 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009840 // Global named register variables (GNU extension) are never emitted.
9841 if (VD->getStorageClass() == SC_Register)
9842 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009843 if (VD->getDescribedVarTemplate() ||
9844 isa<VarTemplatePartialSpecializationDecl>(VD))
9845 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009846 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +00009847 // We never need to emit an uninstantiated function template.
9848 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9849 return false;
Nico Weber66220292016-03-02 17:28:48 +00009850 } else if (isa<PragmaCommentDecl>(D))
9851 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009852 else if (isa<PragmaDetectMismatchDecl>(D))
9853 return true;
Nico Weber66220292016-03-02 17:28:48 +00009854 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009855 return !D->getDeclContext()->isDependentContext();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009856 else if (isa<OMPAllocateDecl>(D))
9857 return !D->getDeclContext()->isDependentContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009858 else if (isa<OMPDeclareReductionDecl>(D))
9859 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009860 else if (isa<ImportDecl>(D))
9861 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009862 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009863 return false;
9864
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009865 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9866 assert(getExternalSource() && "It's from an AST file; must have a source.");
9867 // On Windows, PCH files are built together with an object file. If this
9868 // declaration comes from such a PCH and DeclMustBeEmitted would return
9869 // true, it would have returned true and the decl would have been emitted
9870 // into that object file, so it doesn't need to be emitted here.
9871 // Note that decls are still emitted if they're referenced, as usual;
9872 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9873 // if it's not referenced.
9874 //
9875 // Explicit template instantiation definitions are tricky. If there was an
9876 // explicit template instantiation decl in the PCH before, it will look like
9877 // the definition comes from there, even if that was just the declaration.
9878 // (Explicit instantiation defs of variable templates always get emitted.)
9879 bool IsExpInstDef =
9880 isa<FunctionDecl>(D) &&
9881 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
9882 TSK_ExplicitInstantiationDefinition;
9883
Hans Wennborgb51a7032018-09-14 15:18:30 +00009884 // Implicit member function definitions, such as operator= might not be
9885 // marked as template specializations, since they're not coming from a
9886 // template but synthesized directly on the class.
9887 IsExpInstDef |=
9888 isa<CXXMethodDecl>(D) &&
9889 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
9890 TSK_ExplicitInstantiationDefinition;
9891
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009892 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
9893 return false;
9894 }
9895
Richard Smith5205a8c2013-04-01 20:22:16 +00009896 // If this is a member of a class template, we do not need to emit it.
9897 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009898 return false;
9899
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009900 // Weak references don't produce any output by themselves.
9901 if (D->hasAttr<WeakRefAttr>())
9902 return false;
9903
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009904 // Aliases and used decls are required.
9905 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9906 return true;
9907
Eugene Zelenko7855e772018-04-03 00:11:50 +00009908 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009909 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009910 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009911 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009912
9913 // Constructors and destructors are required.
9914 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9915 return true;
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009916
John McCall6bd2a892013-01-25 22:31:03 +00009917 // The key function for a class is required. This rule only comes
9918 // into play when inline functions can be key functions, though.
9919 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009920 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +00009921 const CXXRecordDecl *RD = MD->getParent();
9922 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9923 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9924 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9925 return true;
9926 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009927 }
9928 }
9929
David Blaikie9ffe5a32017-01-30 05:00:26 +00009930 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9931
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009932 // static, static inline, always_inline, and extern inline functions can
9933 // always be deferred. Normal inline functions can be deferred in C99/C++.
9934 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009935 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009936 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009937
Eugene Zelenko7855e772018-04-03 00:11:50 +00009938 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009939 assert(VD->isFileVarDecl() && "Expected file scoped var");
9940
Alexey Bataevd01b7492018-08-15 19:45:12 +00009941 // If the decl is marked as `declare target to`, it should be emitted for the
9942 // host and for the device.
9943 if (LangOpts.OpenMP &&
9944 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
9945 return true;
9946
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009947 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9948 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009949 return false;
9950
Richard Smitha0e5e542012-11-12 21:38:00 +00009951 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009952 auto Linkage = GetGVALinkageForVariable(VD);
9953 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009954 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009955
Richard Smitha4653622017-09-06 20:01:14 +00009956 // We never need to emit a variable that is available in another TU.
9957 if (Linkage == GVA_AvailableExternally)
9958 return false;
9959
Richard Smitha0e5e542012-11-12 21:38:00 +00009960 // Variables that have destruction with side-effects are required.
9961 if (VD->getType().isDestructedType())
9962 return true;
9963
9964 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009965 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009966 // We can get a value-dependent initializer during error recovery.
9967 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009968 return true;
9969
Richard Smithda383632016-08-15 01:33:41 +00009970 // Likewise, variables with tuple-like bindings are required if their
9971 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009972 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
9973 for (const auto *BD : DD->bindings())
9974 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +00009975 if (DeclMustBeEmitted(BindingVD))
9976 return true;
9977
Richard Smitha0e5e542012-11-12 21:38:00 +00009978 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009979}
Charles Davis53c59df2010-08-16 03:33:14 +00009980
Erich Keane281d20b2018-01-08 21:34:17 +00009981void ASTContext::forEachMultiversionedFunctionVersion(
9982 const FunctionDecl *FD,
Erich Keane0fb16482018-08-13 18:33:20 +00009983 llvm::function_ref<void(FunctionDecl *)> Pred) const {
Erich Keane281d20b2018-01-08 21:34:17 +00009984 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
9985 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
Erich Keane7304f0a2018-11-28 20:58:43 +00009986 FD = FD->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00009987 for (auto *CurDecl :
9988 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
Erich Keane7304f0a2018-11-28 20:58:43 +00009989 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00009990 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
9991 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
9992 SeenDecls.insert(CurFD);
9993 Pred(CurFD);
9994 }
9995 }
9996}
9997
Reid Kleckner78af0702013-08-27 23:08:25 +00009998CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
Erich Keane00022812019-05-23 16:05:21 +00009999 bool IsCXXMethod,
10000 bool IsBuiltin) const {
Charles Davis99202b32010-11-09 18:04:24 +000010001 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +000010002 if (IsCXXMethod)
10003 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +000010004
Erich Keane00022812019-05-23 16:05:21 +000010005 // Builtins ignore user-specified default calling convention and remain the
10006 // Target's default calling convention.
10007 if (!IsBuiltin) {
10008 switch (LangOpts.getDefaultCallingConv()) {
10009 case LangOptions::DCC_None:
10010 break;
10011 case LangOptions::DCC_CDecl:
10012 return CC_C;
10013 case LangOptions::DCC_FastCall:
10014 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10015 return CC_X86FastCall;
10016 break;
10017 case LangOptions::DCC_StdCall:
10018 if (!IsVariadic)
10019 return CC_X86StdCall;
10020 break;
10021 case LangOptions::DCC_VectorCall:
10022 // __vectorcall cannot be applied to variadic functions.
10023 if (!IsVariadic)
10024 return CC_X86VectorCall;
10025 break;
10026 case LangOptions::DCC_RegCall:
10027 // __regcall cannot be applied to variadic functions.
10028 if (!IsVariadic)
10029 return CC_X86RegCall;
10030 break;
10031 }
Alexey Bataeva7547182016-05-18 09:06:38 +000010032 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000010033 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +000010034}
10035
Jay Foad39c79802011-01-12 09:06:06 +000010036bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +000010037 // Pass through to the C++ ABI object
10038 return ABI->isNearlyEmpty(RD);
10039}
10040
Reid Kleckner96f8f932014-02-05 17:27:08 +000010041VTableContextBase *ASTContext::getVTableContext() {
10042 if (!VTContext.get()) {
10043 if (Target->getCXXABI().isMicrosoft())
10044 VTContext.reset(new MicrosoftVTableContext(*this));
10045 else
10046 VTContext.reset(new ItaniumVTableContext(*this));
10047 }
10048 return VTContext.get();
10049}
10050
Yaxun Liuc18e9ec2019-02-14 02:00:09 +000010051MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10052 if (!T)
10053 T = Target;
10054 switch (T->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000010055 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +000010056 case TargetCXXABI::GenericItanium:
10057 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000010058 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +000010059 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000010060 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +000010061 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +000010062 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010063 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +000010064 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010065 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010066 }
David Blaikie83d382b2011-09-23 05:06:16 +000010067 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010068}
10069
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010070CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010071
10072size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +000010073 return ASTRecordLayouts.getMemorySize() +
10074 llvm::capacity_in_bytes(ObjCLayouts) +
10075 llvm::capacity_in_bytes(KeyFunctions) +
10076 llvm::capacity_in_bytes(ObjCImpls) +
10077 llvm::capacity_in_bytes(BlockVarCopyInits) +
10078 llvm::capacity_in_bytes(DeclAttrs) +
10079 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10080 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10081 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10082 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10083 llvm::capacity_in_bytes(OverriddenMethods) +
10084 llvm::capacity_in_bytes(Types) +
Richard Smithf19a8b02019-05-02 00:49:14 +000010085 llvm::capacity_in_bytes(VariableArrayTypes);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010086}
Ted Kremenek540017e2011-10-06 05:00:56 +000010087
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010088/// getIntTypeForBitwidth -
10089/// sets integer QualTy according to specified details:
10090/// bitwidth, signed/unsigned.
10091/// Returns empty type if there is no appropriate target types.
10092QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10093 unsigned Signed) const {
10094 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10095 CanQualType QualTy = getFromTargetType(Ty);
10096 if (!QualTy && DestWidth == 128)
10097 return Signed ? Int128Ty : UnsignedInt128Ty;
10098 return QualTy;
10099}
10100
10101/// getRealTypeForBitwidth -
10102/// sets floating point QualTy according to specified bitwidth.
10103/// Returns empty type if there is no appropriate target types.
10104QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
10105 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
10106 switch (Ty) {
10107 case TargetInfo::Float:
10108 return FloatTy;
10109 case TargetInfo::Double:
10110 return DoubleTy;
10111 case TargetInfo::LongDouble:
10112 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000010113 case TargetInfo::Float128:
10114 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010115 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +000010116 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010117 }
10118
10119 llvm_unreachable("Unhandled TargetInfo::RealType value");
10120}
10121
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010122void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10123 if (Number > 1)
10124 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +000010125}
10126
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010127unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010128 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010129 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +000010130}
10131
David Majnemer2206bf52014-03-05 08:57:59 +000010132void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10133 if (Number > 1)
10134 StaticLocalNumbers[VD] = Number;
10135}
10136
10137unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010138 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +000010139 return I != StaticLocalNumbers.end() ? I->second : 1;
10140}
10141
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010142MangleNumberingContext &
10143ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010144 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +000010145 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +000010146 if (!MCtx)
10147 MCtx = createMangleNumberingContext();
10148 return *MCtx;
10149}
10150
Justin Lebar20ebffc2016-10-10 16:26:19 +000010151std::unique_ptr<MangleNumberingContext>
10152ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010153 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +000010154}
10155
David Majnemere7a818f2015-03-06 18:53:55 +000010156const CXXConstructorDecl *
10157ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10158 return ABI->getCopyConstructorForExceptionObject(
10159 cast<CXXRecordDecl>(RD->getFirstDecl()));
10160}
10161
10162void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10163 CXXConstructorDecl *CD) {
10164 return ABI->addCopyConstructorForExceptionObject(
10165 cast<CXXRecordDecl>(RD->getFirstDecl()),
10166 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10167}
10168
David Majnemer00350522015-08-31 18:48:39 +000010169void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10170 TypedefNameDecl *DD) {
10171 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10172}
10173
10174TypedefNameDecl *
10175ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10176 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10177}
10178
10179void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10180 DeclaratorDecl *DD) {
10181 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10182}
10183
10184DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10185 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10186}
10187
Ted Kremenek540017e2011-10-06 05:00:56 +000010188void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10189 ParamIndices[D] = index;
10190}
10191
10192unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10193 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
Fangrui Song6907ce22018-07-30 19:24:48 +000010194 assert(I != ParamIndices.end() &&
Ted Kremenek540017e2011-10-06 05:00:56 +000010195 "ParmIndices lacks entry set by ParmVarDecl");
10196 return I->second;
10197}
Fariborz Jahanian615de762013-05-28 17:37:39 +000010198
Richard Smithe6c01442013-06-05 00:46:14 +000010199APValue *
10200ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
10201 bool MayCreate) {
10202 assert(E && E->getStorageDuration() == SD_Static &&
10203 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +000010204 if (MayCreate) {
10205 APValue *&MTVI = MaterializedTemporaryValues[E];
10206 if (!MTVI)
10207 MTVI = new (*this) APValue;
10208 return MTVI;
10209 }
Richard Smithe6c01442013-06-05 00:46:14 +000010210
David Majnemer2dcef9e2015-08-13 23:50:15 +000010211 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +000010212}
10213
Eric Fiselier708afb52019-05-16 21:04:15 +000010214QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
10215 unsigned Length) const {
10216 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
10217 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
10218 EltTy = EltTy.withConst();
10219
10220 EltTy = adjustStringLiteralBaseType(EltTy);
10221
10222 // Get an array type for the string, according to C99 6.4.5. This includes
10223 // the null terminator character.
10224 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1),
10225 ArrayType::Normal, /*IndexTypeQuals*/ 0);
10226}
10227
10228StringLiteral *
10229ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
10230 StringLiteral *&Result = StringLiteralCache[Key];
10231 if (!Result)
10232 Result = StringLiteral::Create(
10233 *this, Key, StringLiteral::Ascii,
10234 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
10235 SourceLocation());
10236 return Result;
10237}
10238
Fariborz Jahanian615de762013-05-28 17:37:39 +000010239bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10240 const llvm::Triple &T = getTargetInfo().getTriple();
10241 if (!T.isOSDarwin())
10242 return false;
10243
Bob Wilson2c82c3d2013-11-02 23:27:49 +000010244 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10245 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10246 return false;
10247
Fariborz Jahanian615de762013-05-28 17:37:39 +000010248 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10249 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10250 uint64_t Size = sizeChars.getQuantity();
10251 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10252 unsigned Align = alignChars.getQuantity();
10253 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10254 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10255}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010256
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010257/// Template specializations to abstract away from pointers and TypeLocs.
10258/// @{
10259template <typename T>
Sam McCall814e7972018-11-14 10:33:30 +000010260static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010261 return ast_type_traits::DynTypedNode::create(*Node);
10262}
10263template <>
10264ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10265 return ast_type_traits::DynTypedNode::create(Node);
10266}
10267template <>
10268ast_type_traits::DynTypedNode
10269createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10270 return ast_type_traits::DynTypedNode::create(Node);
10271}
10272/// @}
10273
Sam McCall814e7972018-11-14 10:33:30 +000010274/// A \c RecursiveASTVisitor that builds a map from nodes to their
10275/// parents as defined by the \c RecursiveASTVisitor.
10276///
10277/// Note that the relationship described here is purely in terms of AST
10278/// traversal - there are other relationships (for example declaration context)
10279/// in the AST that are better modeled by special matchers.
10280///
10281/// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10282class ASTContext::ParentMap::ASTVisitor
10283 : public RecursiveASTVisitor<ASTVisitor> {
10284public:
10285 ASTVisitor(ParentMap &Map) : Map(Map) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010286
Sam McCall814e7972018-11-14 10:33:30 +000010287private:
10288 friend class RecursiveASTVisitor<ASTVisitor>;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010289
Sam McCall814e7972018-11-14 10:33:30 +000010290 using VisitorBase = RecursiveASTVisitor<ASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010291
Sam McCall814e7972018-11-14 10:33:30 +000010292 bool shouldVisitTemplateInstantiations() const { return true; }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010293
Sam McCall814e7972018-11-14 10:33:30 +000010294 bool shouldVisitImplicitCode() const { return true; }
10295
10296 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10297 typename MapTy>
10298 bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
10299 MapTy *Parents) {
10300 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010301 return true;
Sam McCall814e7972018-11-14 10:33:30 +000010302 if (ParentStack.size() > 0) {
10303 // FIXME: Currently we add the same parent multiple times, but only
10304 // when no memoization data is available for the type.
10305 // For example when we visit all subexpressions of template
10306 // instantiations; this is suboptimal, but benign: the only way to
10307 // visit those is with hasAncestor / hasParent, and those do not create
10308 // new matches.
10309 // The plan is to enable DynTypedNode to be storable in a map or hash
10310 // map. The main problem there is to implement hash functions /
10311 // comparison operators for all types that DynTypedNode supports that
10312 // do not have pointer identity.
10313 auto &NodeOrVector = (*Parents)[MapNode];
10314 if (NodeOrVector.isNull()) {
10315 if (const auto *D = ParentStack.back().get<Decl>())
10316 NodeOrVector = D;
10317 else if (const auto *S = ParentStack.back().get<Stmt>())
10318 NodeOrVector = S;
10319 else
10320 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
10321 } else {
10322 if (!NodeOrVector.template is<ParentVector *>()) {
10323 auto *Vector = new ParentVector(
10324 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10325 delete NodeOrVector
10326 .template dyn_cast<ast_type_traits::DynTypedNode *>();
10327 NodeOrVector = Vector;
Manuel Klimek95403e62014-05-21 13:28:59 +000010328 }
Sam McCall814e7972018-11-14 10:33:30 +000010329
10330 auto *Vector = NodeOrVector.template get<ParentVector *>();
10331 // Skip duplicates for types that have memoization data.
10332 // We must check that the type has memoization data before calling
10333 // std::find() because DynTypedNode::operator== can't compare all
10334 // types.
10335 bool Found = ParentStack.back().getMemoizationData() &&
10336 std::find(Vector->begin(), Vector->end(),
10337 ParentStack.back()) != Vector->end();
10338 if (!Found)
10339 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010340 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010341 }
Sam McCall814e7972018-11-14 10:33:30 +000010342 ParentStack.push_back(createDynTypedNode(Node));
10343 bool Result = BaseTraverse();
10344 ParentStack.pop_back();
10345 return Result;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010346 }
Sam McCall814e7972018-11-14 10:33:30 +000010347
10348 bool TraverseDecl(Decl *DeclNode) {
10349 return TraverseNode(
10350 DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
10351 &Map.PointerParents);
Manuel Klimek95403e62014-05-21 13:28:59 +000010352 }
Sam McCall814e7972018-11-14 10:33:30 +000010353
10354 bool TraverseStmt(Stmt *StmtNode) {
10355 return TraverseNode(
10356 StmtNode, StmtNode, [&] { return VisitorBase::TraverseStmt(StmtNode); },
10357 &Map.PointerParents);
10358 }
10359
10360 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10361 return TraverseNode(
10362 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10363 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10364 &Map.OtherParents);
10365 }
10366
10367 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10368 return TraverseNode(
10369 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10370 [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
10371 &Map.OtherParents);
10372 }
10373
10374 ParentMap &Map;
10375 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
10376};
10377
10378ASTContext::ParentMap::ParentMap(ASTContext &Ctx) {
10379 ASTVisitor(*this).TraverseAST(Ctx);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010380}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010381
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010382ASTContext::DynTypedNodeList
10383ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
Sam McCall814e7972018-11-14 10:33:30 +000010384 if (!Parents)
10385 // We build the parent map for the traversal scope (usually whole TU), as
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010386 // hasAncestor can escape any subtree.
Sam McCall814e7972018-11-14 10:33:30 +000010387 Parents = llvm::make_unique<ParentMap>(*this);
10388 return Parents->getParents(Node);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010389}
10390
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010391bool
10392ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10393 const ObjCMethodDecl *MethodImpl) {
10394 // No point trying to match an unavailable/deprecated mothod.
10395 if (MethodDecl->hasAttr<UnavailableAttr>()
10396 || MethodDecl->hasAttr<DeprecatedAttr>())
10397 return false;
10398 if (MethodDecl->getObjCDeclQualifier() !=
10399 MethodImpl->getObjCDeclQualifier())
10400 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010401 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010402 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010403
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010404 if (MethodDecl->param_size() != MethodImpl->param_size())
10405 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010406
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010407 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10408 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10409 EF = MethodDecl->param_end();
10410 IM != EM && IF != EF; ++IM, ++IF) {
10411 const ParmVarDecl *DeclVar = (*IF);
10412 const ParmVarDecl *ImplVar = (*IM);
10413 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10414 return false;
10415 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10416 return false;
10417 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010418
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010419 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010420}
Richard Smith053f6c62014-05-16 23:01:30 +000010421
Yaxun Liu402804b2016-12-15 08:09:08 +000010422uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010423 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010424 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010425 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010426 else
10427 AS = QT->getPointeeType().getAddressSpace();
10428
10429 return getTargetInfo().getNullPointerValue(AS);
10430}
10431
Alexander Richardson6d989432017-10-15 18:48:14 +000010432unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10433 if (isTargetAddressSpace(AS))
10434 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010435 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010436 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010437}
10438
Leonard Chanab80f3c2018-06-14 14:53:51 +000010439QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10440 assert(Ty->isFixedPointType());
10441
10442 if (Ty->isSaturatedFixedPointType()) return Ty;
10443
10444 const auto &BT = Ty->getAs<BuiltinType>();
10445 switch (BT->getKind()) {
10446 default:
10447 llvm_unreachable("Not a fixed point type!");
10448 case BuiltinType::ShortAccum:
10449 return SatShortAccumTy;
10450 case BuiltinType::Accum:
10451 return SatAccumTy;
10452 case BuiltinType::LongAccum:
10453 return SatLongAccumTy;
10454 case BuiltinType::UShortAccum:
10455 return SatUnsignedShortAccumTy;
10456 case BuiltinType::UAccum:
10457 return SatUnsignedAccumTy;
10458 case BuiltinType::ULongAccum:
10459 return SatUnsignedLongAccumTy;
10460 case BuiltinType::ShortFract:
10461 return SatShortFractTy;
10462 case BuiltinType::Fract:
10463 return SatFractTy;
10464 case BuiltinType::LongFract:
10465 return SatLongFractTy;
10466 case BuiltinType::UShortFract:
10467 return SatUnsignedShortFractTy;
10468 case BuiltinType::UFract:
10469 return SatUnsignedFractTy;
10470 case BuiltinType::ULongFract:
10471 return SatUnsignedLongFractTy;
10472 }
10473}
10474
Matt Arsenaultc65f9662018-08-02 12:14:28 +000010475LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10476 if (LangOpts.OpenCL)
10477 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10478
10479 if (LangOpts.CUDA)
10480 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10481
10482 return getLangASFromTargetAS(AS);
10483}
10484
Richard Smith053f6c62014-05-16 23:01:30 +000010485// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10486// doesn't include ASTContext.h
10487template
10488clang::LazyGenerationalUpdatePtr<
10489 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10490clang::LazyGenerationalUpdatePtr<
10491 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10492 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010493
10494unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10495 assert(Ty->isFixedPointType());
10496
10497 const auto *BT = Ty->getAs<BuiltinType>();
10498 const TargetInfo &Target = getTargetInfo();
10499 switch (BT->getKind()) {
10500 default:
10501 llvm_unreachable("Not a fixed point type!");
10502 case BuiltinType::ShortAccum:
10503 case BuiltinType::SatShortAccum:
10504 return Target.getShortAccumScale();
10505 case BuiltinType::Accum:
10506 case BuiltinType::SatAccum:
10507 return Target.getAccumScale();
10508 case BuiltinType::LongAccum:
10509 case BuiltinType::SatLongAccum:
10510 return Target.getLongAccumScale();
10511 case BuiltinType::UShortAccum:
10512 case BuiltinType::SatUShortAccum:
10513 return Target.getUnsignedShortAccumScale();
10514 case BuiltinType::UAccum:
10515 case BuiltinType::SatUAccum:
10516 return Target.getUnsignedAccumScale();
10517 case BuiltinType::ULongAccum:
10518 case BuiltinType::SatULongAccum:
10519 return Target.getUnsignedLongAccumScale();
10520 case BuiltinType::ShortFract:
10521 case BuiltinType::SatShortFract:
10522 return Target.getShortFractScale();
10523 case BuiltinType::Fract:
10524 case BuiltinType::SatFract:
10525 return Target.getFractScale();
10526 case BuiltinType::LongFract:
10527 case BuiltinType::SatLongFract:
10528 return Target.getLongFractScale();
10529 case BuiltinType::UShortFract:
10530 case BuiltinType::SatUShortFract:
10531 return Target.getUnsignedShortFractScale();
10532 case BuiltinType::UFract:
10533 case BuiltinType::SatUFract:
10534 return Target.getUnsignedFractScale();
10535 case BuiltinType::ULongFract:
10536 case BuiltinType::SatULongFract:
10537 return Target.getUnsignedLongFractScale();
10538 }
10539}
10540
10541unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10542 assert(Ty->isFixedPointType());
10543
10544 const auto *BT = Ty->getAs<BuiltinType>();
10545 const TargetInfo &Target = getTargetInfo();
10546 switch (BT->getKind()) {
10547 default:
10548 llvm_unreachable("Not a fixed point type!");
10549 case BuiltinType::ShortAccum:
10550 case BuiltinType::SatShortAccum:
10551 return Target.getShortAccumIBits();
10552 case BuiltinType::Accum:
10553 case BuiltinType::SatAccum:
10554 return Target.getAccumIBits();
10555 case BuiltinType::LongAccum:
10556 case BuiltinType::SatLongAccum:
10557 return Target.getLongAccumIBits();
10558 case BuiltinType::UShortAccum:
10559 case BuiltinType::SatUShortAccum:
10560 return Target.getUnsignedShortAccumIBits();
10561 case BuiltinType::UAccum:
10562 case BuiltinType::SatUAccum:
10563 return Target.getUnsignedAccumIBits();
10564 case BuiltinType::ULongAccum:
10565 case BuiltinType::SatULongAccum:
10566 return Target.getUnsignedLongAccumIBits();
10567 case BuiltinType::ShortFract:
10568 case BuiltinType::SatShortFract:
10569 case BuiltinType::Fract:
10570 case BuiltinType::SatFract:
10571 case BuiltinType::LongFract:
10572 case BuiltinType::SatLongFract:
10573 case BuiltinType::UShortFract:
10574 case BuiltinType::SatUShortFract:
10575 case BuiltinType::UFract:
10576 case BuiltinType::SatUFract:
10577 case BuiltinType::ULongFract:
10578 case BuiltinType::SatULongFract:
10579 return 0;
10580 }
10581}
Leonard Chana6779422018-08-06 16:42:37 +000010582
10583FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
Erich Keane8e772162019-01-18 19:31:54 +000010584 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
10585 "Can only get the fixed point semantics for a "
10586 "fixed point or integer type.");
Leonard Chan2044ac82019-01-16 18:13:59 +000010587 if (Ty->isIntegerType())
10588 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
10589 Ty->isSignedIntegerType());
10590
Leonard Chana6779422018-08-06 16:42:37 +000010591 bool isSigned = Ty->isSignedFixedPointType();
10592 return FixedPointSemantics(
10593 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10594 Ty->isSaturatedFixedPointType(),
10595 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10596}
10597
10598APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10599 assert(Ty->isFixedPointType());
10600 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10601}
10602
10603APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10604 assert(Ty->isFixedPointType());
10605 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10606}
Leonard Chan2044ac82019-01-16 18:13:59 +000010607
10608QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
10609 assert(Ty->isUnsignedFixedPointType() &&
10610 "Expected unsigned fixed point type");
10611 const auto *BTy = Ty->getAs<BuiltinType>();
10612
10613 switch (BTy->getKind()) {
10614 case BuiltinType::UShortAccum:
10615 return ShortAccumTy;
10616 case BuiltinType::UAccum:
10617 return AccumTy;
10618 case BuiltinType::ULongAccum:
10619 return LongAccumTy;
10620 case BuiltinType::SatUShortAccum:
10621 return SatShortAccumTy;
10622 case BuiltinType::SatUAccum:
10623 return SatAccumTy;
10624 case BuiltinType::SatULongAccum:
10625 return SatLongAccumTy;
10626 case BuiltinType::UShortFract:
10627 return ShortFractTy;
10628 case BuiltinType::UFract:
10629 return FractTy;
10630 case BuiltinType::ULongFract:
10631 return LongFractTy;
10632 case BuiltinType::SatUShortFract:
10633 return SatShortFractTy;
10634 case BuiltinType::SatUFract:
10635 return SatFractTy;
10636 case BuiltinType::SatULongFract:
10637 return SatLongFractTy;
10638 default:
10639 llvm_unreachable("Unexpected unsigned fixed point type");
10640 }
10641}