blob: 072cfad5ba2873f4e02da0593537a79b03eabbc3 [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();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000830}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000831
Sam McCall814e7972018-11-14 10:33:30 +0000832class ASTContext::ParentMap {
833 /// Contains parents of a node.
834 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
835
836 /// Maps from a node to its parents. This is used for nodes that have
837 /// pointer identity only, which are more common and we can save space by
838 /// only storing a unique pointer to them.
839 using ParentMapPointers = llvm::DenseMap<
840 const void *,
841 llvm::PointerUnion4<const Decl *, const Stmt *,
842 ast_type_traits::DynTypedNode *, ParentVector *>>;
843
844 /// Parent map for nodes without pointer identity. We store a full
845 /// DynTypedNode for all keys.
846 using ParentMapOtherNodes = llvm::DenseMap<
847 ast_type_traits::DynTypedNode,
848 llvm::PointerUnion4<const Decl *, const Stmt *,
849 ast_type_traits::DynTypedNode *, ParentVector *>>;
850
851 ParentMapPointers PointerParents;
852 ParentMapOtherNodes OtherParents;
853 class ASTVisitor;
854
855 static ast_type_traits::DynTypedNode
856 getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
857 if (const auto *D = U.dyn_cast<const Decl *>())
858 return ast_type_traits::DynTypedNode::create(*D);
859 if (const auto *S = U.dyn_cast<const Stmt *>())
860 return ast_type_traits::DynTypedNode::create(*S);
861 return *U.get<ast_type_traits::DynTypedNode *>();
862 }
863
864 template <typename NodeTy, typename MapTy>
865 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
866 const MapTy &Map) {
867 auto I = Map.find(Node);
868 if (I == Map.end()) {
869 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
870 }
871 if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
872 return llvm::makeArrayRef(*V);
873 }
874 return getSingleDynTypedNodeFromParentMap(I->second);
875 }
876
877public:
878 ParentMap(ASTContext &Ctx);
879 ~ParentMap() {
880 for (const auto &Entry : PointerParents) {
881 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
882 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
883 } else if (Entry.second.is<ParentVector *>()) {
884 delete Entry.second.get<ParentVector *>();
885 }
886 }
887 for (const auto &Entry : OtherParents) {
888 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
889 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
890 } else if (Entry.second.is<ParentVector *>()) {
891 delete Entry.second.get<ParentVector *>();
892 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000893 }
894 }
Sam McCall814e7972018-11-14 10:33:30 +0000895
896 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
897 if (Node.getNodeKind().hasPointerIdentity())
898 return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
899 return getDynNodeFromMap(Node, OtherParents);
Manuel Klimek95403e62014-05-21 13:28:59 +0000900 }
Sam McCall814e7972018-11-14 10:33:30 +0000901};
902
903void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
904 TraversalScope = TopLevelDecls;
905 Parents.reset();
Manuel Klimek95403e62014-05-21 13:28:59 +0000906}
907
Douglas Gregor1a809332010-05-23 18:26:36 +0000908void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000909 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000910}
911
Mike Stump11289f42009-09-09 15:08:12 +0000912void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000913ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000914 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000915}
916
Chris Lattner4eb445d2007-01-26 01:27:23 +0000917void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000918 llvm::errs() << "\n*** AST Context Stats:\n";
919 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000920
Douglas Gregora30d0462009-05-26 14:40:08 +0000921 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000922#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000923#define ABSTRACT_TYPE(Name, Parent)
924#include "clang/AST/TypeNodes.def"
925 0 // Extra
926 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000927
Chris Lattner4eb445d2007-01-26 01:27:23 +0000928 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
929 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000930 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000931 }
932
Douglas Gregora30d0462009-05-26 14:40:08 +0000933 unsigned Idx = 0;
934 unsigned TotalBytes = 0;
935#define TYPE(Name, Parent) \
936 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000937 llvm::errs() << " " << counts[Idx] << " " << #Name \
Bruno Ricci58e03222018-08-06 15:17:32 +0000938 << " types, " << sizeof(Name##Type) << " each " \
939 << "(" << counts[Idx] * sizeof(Name##Type) \
940 << " bytes)\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000941 TotalBytes += counts[Idx] * sizeof(Name##Type); \
942 ++Idx;
943#define ABSTRACT_TYPE(Name, Parent)
944#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000945
Chandler Carruth3c147a72011-07-04 05:32:14 +0000946 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
947
Douglas Gregor7454c562010-07-02 20:37:36 +0000948 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000949 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
950 << NumImplicitDefaultConstructors
951 << " implicit default constructors created\n";
952 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
953 << NumImplicitCopyConstructors
954 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000955 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000956 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
957 << NumImplicitMoveConstructors
958 << " implicit move constructors created\n";
959 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
960 << NumImplicitCopyAssignmentOperators
961 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000962 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000963 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
964 << NumImplicitMoveAssignmentOperators
965 << " implicit move assignment operators created\n";
966 llvm::errs() << NumImplicitDestructorsDeclared << "/"
967 << NumImplicitDestructors
968 << " implicit destructors created\n";
969
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000970 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000971 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000972 ExternalSource->PrintStats();
973 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000974
Douglas Gregor5b11d492010-07-25 17:53:33 +0000975 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000976}
977
Richard Smith42413142015-05-15 20:05:43 +0000978void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
979 bool NotifyListeners) {
980 if (NotifyListeners)
981 if (auto *Listener = getASTMutationListener())
982 Listener->RedefinedHiddenDefinition(ND, M);
983
Richard Smith13897eb2018-09-12 23:37:00 +0000984 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
Richard Smith42413142015-05-15 20:05:43 +0000985}
986
987void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
Richard Smith20fbdb32018-09-12 02:13:46 +0000988 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
Richard Smith42413142015-05-15 20:05:43 +0000989 if (It == MergedDefModules.end())
990 return;
991
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000992 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000993 llvm::DenseSet<Module*> Found;
994 for (Module *&M : Merged)
995 if (!Found.insert(M).second)
996 M = nullptr;
997 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
998}
999
Richard Smithdc1f0422016-07-20 19:10:16 +00001000void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1001 if (LazyInitializers.empty())
1002 return;
1003
1004 auto *Source = Ctx.getExternalSource();
1005 assert(Source && "lazy initializers but no external source");
1006
1007 auto LazyInits = std::move(LazyInitializers);
1008 LazyInitializers.clear();
1009
1010 for (auto ID : LazyInits)
1011 Initializers.push_back(Source->GetExternalDecl(ID));
1012
1013 assert(LazyInitializers.empty() &&
1014 "GetExternalDecl for lazy module initializer added more inits");
1015}
1016
1017void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1018 // One special case: if we add a module initializer that imports another
1019 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001020 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001021 auto It = ModuleInitializers.find(ID->getImportedModule());
1022
1023 // Maybe the ImportDecl does nothing at all. (Common case.)
1024 if (It == ModuleInitializers.end())
1025 return;
1026
1027 // Maybe the ImportDecl only imports another ImportDecl.
1028 auto &Imported = *It->second;
1029 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1030 Imported.resolve(*this);
1031 auto *OnlyDecl = Imported.Initializers.front();
1032 if (isa<ImportDecl>(OnlyDecl))
1033 D = OnlyDecl;
1034 }
1035 }
1036
1037 auto *&Inits = ModuleInitializers[M];
1038 if (!Inits)
1039 Inits = new (*this) PerModuleInitializers;
1040 Inits->Initializers.push_back(D);
1041}
1042
1043void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1044 auto *&Inits = ModuleInitializers[M];
1045 if (!Inits)
1046 Inits = new (*this) PerModuleInitializers;
1047 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1048 IDs.begin(), IDs.end());
1049}
1050
Eugene Zelenko7855e772018-04-03 00:11:50 +00001051ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001052 auto It = ModuleInitializers.find(M);
Fangrui Song6907ce22018-07-30 19:24:48 +00001053 if (It == ModuleInitializers.end())
Richard Smithdc1f0422016-07-20 19:10:16 +00001054 return None;
1055
1056 auto *Inits = It->second;
1057 Inits->resolve(*this);
1058 return Inits->Initializers;
1059}
1060
Richard Smithf19e1272015-03-07 00:04:49 +00001061ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1062 if (!ExternCContext)
1063 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1064
1065 return ExternCContext;
1066}
1067
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001068BuiltinTemplateDecl *
1069ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1070 const IdentifierInfo *II) const {
1071 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1072 BuiltinTemplate->setImplicit();
1073 TUDecl->addDecl(BuiltinTemplate);
1074
1075 return BuiltinTemplate;
1076}
1077
1078BuiltinTemplateDecl *
1079ASTContext::getMakeIntegerSeqDecl() const {
1080 if (!MakeIntegerSeqDecl)
1081 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1082 getMakeIntegerSeqName());
1083 return MakeIntegerSeqDecl;
1084}
1085
Eric Fiselier6ad68552016-07-01 01:24:09 +00001086BuiltinTemplateDecl *
1087ASTContext::getTypePackElementDecl() const {
1088 if (!TypePackElementDecl)
1089 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1090 getTypePackElementName());
1091 return TypePackElementDecl;
1092}
1093
Alp Toker2dea15b2013-12-17 01:22:38 +00001094RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1095 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001096 SourceLocation Loc;
1097 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001098 if (getLangOpts().CPlusPlus)
1099 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1100 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001101 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001102 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1103 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001104 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001105 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1106 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001107 return NewDecl;
1108}
1109
1110TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1111 StringRef Name) const {
1112 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1113 TypedefDecl *NewDecl = TypedefDecl::Create(
1114 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1115 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1116 NewDecl->setImplicit();
1117 return NewDecl;
1118}
1119
Douglas Gregor801c99d2011-08-12 06:49:56 +00001120TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001121 if (!Int128Decl)
1122 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001123 return Int128Decl;
1124}
1125
1126TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001127 if (!UInt128Decl)
1128 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001129 return UInt128Decl;
1130}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001131
John McCall48f2d582009-10-23 23:03:21 +00001132void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001133 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001134 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001135 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001136}
1137
Artem Belevichb5bc9232015-09-22 17:23:22 +00001138void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1139 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001140 assert((!this->Target || this->Target == &Target) &&
1141 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001142 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001143
Douglas Gregore8bbc122011-09-02 00:18:52 +00001144 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001145 this->AuxTarget = AuxTarget;
1146
Douglas Gregore8bbc122011-09-02 00:18:52 +00001147 ABI.reset(createCXXABI(Target));
1148 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001149 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001150
Chris Lattner970e54e2006-11-12 00:37:36 +00001151 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001152 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001153
Chris Lattner970e54e2006-11-12 00:37:36 +00001154 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001155 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001156 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001157 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001158 InitBuiltinType(CharTy, BuiltinType::Char_S);
1159 else
1160 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001161 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001162 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1163 InitBuiltinType(ShortTy, BuiltinType::Short);
1164 InitBuiltinType(IntTy, BuiltinType::Int);
1165 InitBuiltinType(LongTy, BuiltinType::Long);
1166 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001167
Chris Lattner970e54e2006-11-12 00:37:36 +00001168 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001169 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1170 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1171 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1172 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1173 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001174
Chris Lattner970e54e2006-11-12 00:37:36 +00001175 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001176 InitBuiltinType(FloatTy, BuiltinType::Float);
1177 InitBuiltinType(DoubleTy, BuiltinType::Double);
1178 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001179
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001180 // GNU extension, __float128 for IEEE quadruple precision
1181 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1182
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001183 // C11 extension ISO/IEC TS 18661-3
1184 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1185
Leonard Chanf921d852018-06-04 16:07:52 +00001186 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001187 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1188 InitBuiltinType(AccumTy, BuiltinType::Accum);
1189 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1190 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1191 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1192 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1193 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1194 InitBuiltinType(FractTy, BuiltinType::Fract);
1195 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1196 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1197 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1198 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1199 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1200 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1201 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1202 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1203 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1204 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1205 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1206 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1207 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1208 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1209 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1210 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001211
Chris Lattnerf122cef2009-04-30 02:43:43 +00001212 // GNU extension, 128-bit integers.
1213 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1214 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1215
Hans Wennborg0d81e012013-05-10 10:08:40 +00001216 // C++ 3.9.1p5
1217 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1218 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1219 else // -fshort-wchar makes wchar_t be unsigned.
1220 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1221 if (LangOpts.CPlusPlus && LangOpts.WChar)
1222 WideCharTy = WCharTy;
1223 else {
1224 // C99 (or C++ using -fno-wchar).
1225 WideCharTy = getFromTargetType(Target.getWCharType());
1226 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001227
James Molloy36365542012-05-04 10:55:22 +00001228 WIntTy = getFromTargetType(Target.getWIntType());
1229
Richard Smith3a8244d2018-05-01 05:02:45 +00001230 // C++20 (proposed)
1231 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1232
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001233 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1234 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1235 else // C99
1236 Char16Ty = getFromTargetType(Target.getChar16Type());
1237
1238 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1239 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1240 else // C99
1241 Char32Ty = getFromTargetType(Target.getChar32Type());
1242
Douglas Gregor4619e432008-12-05 23:32:09 +00001243 // Placeholder type for type-dependent expressions whose type is
1244 // completely unknown. No code should ever check a type against
1245 // DependentTy and users should never see it; however, it is here to
1246 // help diagnose failures to properly check for type-dependent
1247 // expressions.
1248 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001249
John McCall36e7fe32010-10-12 00:20:44 +00001250 // Placeholder type for functions.
1251 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1252
John McCall0009fcc2011-04-26 20:42:42 +00001253 // Placeholder type for bound members.
1254 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1255
John McCall526ab472011-10-25 17:37:35 +00001256 // Placeholder type for pseudo-objects.
1257 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1258
John McCall31996342011-04-07 08:22:57 +00001259 // "any" type; useful for debugger-like clients.
1260 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1261
John McCall8a6b59a2011-10-17 18:09:15 +00001262 // Placeholder type for unbridged ARC casts.
1263 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1264
Eli Friedman34866c72012-08-31 00:14:07 +00001265 // Placeholder type for builtin functions.
1266 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1267
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001268 // Placeholder type for OMP array sections.
1269 if (LangOpts.OpenMP)
1270 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1271
Chris Lattner970e54e2006-11-12 00:37:36 +00001272 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001273 FloatComplexTy = getComplexType(FloatTy);
1274 DoubleComplexTy = getComplexType(DoubleTy);
1275 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001276 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001277
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001278 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001279 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1280 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001281 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001282
Alexey Bader954ba212016-04-08 13:40:33 +00001283 if (LangOpts.OpenCL) {
1284#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1285 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001286#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001287
Guy Benyei61054192013-02-07 10:55:47 +00001288 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001289 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001290 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1291 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001292 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001293
1294#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1295 InitBuiltinType(Id##Ty, BuiltinType::Id);
1296#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001297 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001298
Ted Kremeneke65b0862012-03-06 20:05:56 +00001299 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001300 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1301 SignedCharTy : BoolTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001302
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001303 ObjCConstantStringType = QualType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001304
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001305 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001306
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001307 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001308 if (LangOpts.OpenCLVersion >= 200) {
1309 auto Q = VoidTy.getQualifiers();
1310 Q.setAddressSpace(LangAS::opencl_generic);
1311 VoidPtrTy = getPointerType(getCanonicalType(
1312 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1313 } else {
1314 VoidPtrTy = getPointerType(VoidTy);
1315 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001316
1317 // nullptr type (C++0x 2.14.7)
1318 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001319
1320 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1321 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001322
1323 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001324 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001325}
1326
David Blaikie9c902b52011-09-25 23:23:43 +00001327DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001328 return SourceMgr.getDiagnostics();
1329}
1330
Douglas Gregor561eceb2010-08-30 16:49:28 +00001331AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1332 AttrVec *&Result = DeclAttrs[D];
1333 if (!Result) {
1334 void *Mem = Allocate(sizeof(AttrVec));
1335 Result = new (Mem) AttrVec;
1336 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001337
Douglas Gregor561eceb2010-08-30 16:49:28 +00001338 return *Result;
1339}
1340
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001341/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001342void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001343 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1344 if (Pos != DeclAttrs.end()) {
1345 Pos->second->~AttrVec();
1346 DeclAttrs.erase(Pos);
1347 }
1348}
1349
Larisse Voufo39a1e502013-08-06 01:03:05 +00001350// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001351MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001352ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001353 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001354 return getTemplateOrSpecializationInfo(Var)
1355 .dyn_cast<MemberSpecializationInfo *>();
1356}
1357
1358ASTContext::TemplateOrSpecializationInfo
1359ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1360 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1361 TemplateOrInstantiation.find(Var);
1362 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001363 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001364
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001365 return Pos->second;
1366}
1367
Mike Stump11289f42009-09-09 15:08:12 +00001368void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001369ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001370 TemplateSpecializationKind TSK,
1371 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001372 assert(Inst->isStaticDataMember() && "Not a static data member");
1373 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001374 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1375 Tmpl, TSK, PointOfInstantiation));
1376}
1377
1378void
1379ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1380 TemplateOrSpecializationInfo TSI) {
1381 assert(!TemplateOrInstantiation[Inst] &&
1382 "Already noted what the variable was instantiated from");
1383 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001384}
1385
John McCalle61f2ba2009-11-18 02:36:19 +00001386NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001387ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1388 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001389 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001390 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001391
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001392 return Pos->second;
1393}
1394
1395void
Richard Smithd8a9e372016-12-18 21:39:37 +00001396ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001397 assert((isa<UsingDecl>(Pattern) ||
1398 isa<UnresolvedUsingValueDecl>(Pattern) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001399 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
John McCallb96ec562009-12-04 22:46:56 +00001400 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001401 assert((isa<UsingDecl>(Inst) ||
1402 isa<UnresolvedUsingValueDecl>(Inst) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001403 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
Richard Smithd8a9e372016-12-18 21:39:37 +00001404 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001405 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1406 InstantiatedFromUsingDecl[Inst] = Pattern;
1407}
1408
1409UsingShadowDecl *
1410ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1411 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1412 = InstantiatedFromUsingShadowDecl.find(Inst);
1413 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001414 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001415
1416 return Pos->second;
1417}
1418
1419void
1420ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1421 UsingShadowDecl *Pattern) {
1422 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1423 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001424}
1425
Anders Carlsson5da84842009-09-01 04:26:58 +00001426FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1427 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1428 = InstantiatedFromUnnamedFieldDecl.find(Field);
1429 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001430 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001431
Anders Carlsson5da84842009-09-01 04:26:58 +00001432 return Pos->second;
1433}
1434
1435void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1436 FieldDecl *Tmpl) {
1437 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1438 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1439 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1440 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001441
Anders Carlsson5da84842009-09-01 04:26:58 +00001442 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1443}
1444
Douglas Gregor832940b2010-03-02 23:58:15 +00001445ASTContext::overridden_cxx_method_iterator
1446ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001447 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001448}
1449
1450ASTContext::overridden_cxx_method_iterator
1451ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001452 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001453}
1454
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001455unsigned
1456ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001457 auto Range = overridden_methods(Method);
1458 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001459}
1460
Clement Courbet6ecaec82016-07-05 07:49:31 +00001461ASTContext::overridden_method_range
1462ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001463 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1464 OverriddenMethods.find(Method->getCanonicalDecl());
1465 if (Pos == OverriddenMethods.end())
1466 return overridden_method_range(nullptr, nullptr);
1467 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001468}
1469
Fangrui Song6907ce22018-07-30 19:24:48 +00001470void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
Douglas Gregor832940b2010-03-02 23:58:15 +00001471 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001472 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001473 OverriddenMethods[Method].push_back(Overridden);
1474}
1475
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001476void ASTContext::getOverriddenMethods(
1477 const NamedDecl *D,
1478 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001479 assert(D);
1480
Eugene Zelenko7855e772018-04-03 00:11:50 +00001481 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001482 Overridden.append(overridden_methods_begin(CXXMethod),
1483 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001484 return;
1485 }
1486
Eugene Zelenko7855e772018-04-03 00:11:50 +00001487 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001488 if (!Method)
1489 return;
1490
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001491 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1492 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001493 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001494}
1495
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001496void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1497 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1498 assert(!Import->isFromASTFile() && "Non-local import declaration");
1499 if (!FirstLocalImport) {
1500 FirstLocalImport = Import;
1501 LastLocalImport = Import;
1502 return;
1503 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001504
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001505 LastLocalImport->NextLocalImport = Import;
1506 LastLocalImport = Import;
1507}
1508
Chris Lattner53cfe802007-07-18 17:52:12 +00001509//===----------------------------------------------------------------------===//
1510// Type Sizing and Analysis
1511//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001512
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001513/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1514/// scalar floating point type.
1515const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001516 const auto *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001517 assert(BT && "Not a floating point type!");
1518 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001519 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001520 case BuiltinType::Float16:
1521 case BuiltinType::Half:
1522 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001523 case BuiltinType::Float: return Target->getFloatFormat();
1524 case BuiltinType::Double: return Target->getDoubleFormat();
1525 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001526 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001527 }
1528}
1529
Rafael Espindola71eccb32013-08-08 19:53:46 +00001530CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001531 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001532
John McCall94268702010-10-08 18:24:19 +00001533 bool UseAlignAttrOnly = false;
1534 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1535 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001536
John McCall94268702010-10-08 18:24:19 +00001537 // __attribute__((aligned)) can increase or decrease alignment
1538 // *except* on a struct or struct member, where it only increases
1539 // alignment unless 'packed' is also specified.
1540 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001541 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001542 // ignore that possibility; Sema should diagnose it.
1543 if (isa<FieldDecl>(D)) {
1544 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1545 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1546 } else {
1547 UseAlignAttrOnly = true;
1548 }
1549 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001550 else if (isa<FieldDecl>(D))
Fangrui Song6907ce22018-07-30 19:24:48 +00001551 UseAlignAttrOnly =
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001552 D->hasAttr<PackedAttr>() ||
1553 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001554
John McCall4e819612011-01-20 07:57:12 +00001555 // If we're using the align attribute only, just ignore everything
1556 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001557 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001558 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001559 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001560 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001561 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001562 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001563 T = RT->getPointeeType();
1564 else
1565 T = getPointerType(RT->getPointeeType());
1566 }
Richard Smithf6d70302014-06-10 23:34:28 +00001567 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001568 if (T->isFunctionType())
1569 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1570 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001571 // Adjust alignments of declarations with array type by the
1572 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001573 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001574 unsigned MinWidth = Target->getLargeArrayMinWidth();
1575 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001576 if (isa<VariableArrayType>(arrayType))
1577 Align = std::max(Align, Target->getLargeArrayAlign());
1578 else if (isa<ConstantArrayType>(arrayType) &&
1579 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1580 Align = std::max(Align, Target->getLargeArrayAlign());
1581 }
John McCall33ddac02011-01-19 10:06:00 +00001582 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001583 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001584 if (BaseT.getQualifiers().hasUnaligned())
1585 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001586 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Tom Tanb7c6d952019-05-02 00:38:14 +00001587 if (VD->hasGlobalStorage() && !ForAlignof) {
1588 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1589 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1590 }
Ulrich Weigandfa806422013-05-06 16:23:57 +00001591 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001592 }
John McCall4e819612011-01-20 07:57:12 +00001593
1594 // Fields can be subject to extra alignment constraints, like if
1595 // the field is packed, the struct is packed, or the struct has a
1596 // a max-field-alignment constraint (#pragma pack). So calculate
1597 // the actual alignment of the field within the struct, and then
1598 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001599 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001600 const RecordDecl *Parent = Field->getParent();
1601 // We can only produce a sensible answer if the record is valid.
1602 if (!Parent->isInvalidDecl()) {
1603 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001604
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001605 // Start with the record's overall alignment.
1606 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001607
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001608 // Use the GCD of that and the offset within the record.
1609 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1610 if (Offset > 0) {
1611 // Alignment is always a power of 2, so the GCD will be a power of 2,
1612 // which means we get to do this crazy thing instead of Euclid's.
1613 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1614 if (LowBitOfOffset < FieldAlign)
1615 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1616 }
1617
1618 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001619 }
Charles Davis3fc51072010-02-23 04:52:00 +00001620 }
Chris Lattner68061312009-01-24 21:53:27 +00001621 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001622
Ken Dyckcc56c542011-01-15 18:38:59 +00001623 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001624}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001625
John McCallf1249922012-08-21 04:10:00 +00001626// getTypeInfoDataSizeInChars - Return the size of a type, in
1627// chars. If the type is a record, its data size is returned. This is
1628// the size of the memcpy that's performed when assigning this type
1629// using a trivial copy/move assignment operator.
1630std::pair<CharUnits, CharUnits>
1631ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1632 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1633
1634 // In C++, objects can sometimes be allocated into the tail padding
1635 // of a base-class subobject. We decide whether that's possible
1636 // during class layout, so here we can just trust the layout results.
1637 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001638 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001639 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1640 sizeAndAlign.first = layout.getDataSize();
1641 }
1642 }
1643
1644 return sizeAndAlign;
1645}
1646
Richard Trieu04d2d942013-05-14 21:59:17 +00001647/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1648/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1649std::pair<CharUnits, CharUnits>
1650static getConstantArrayInfoInChars(const ASTContext &Context,
1651 const ConstantArrayType *CAT) {
1652 std::pair<CharUnits, CharUnits> EltInfo =
1653 Context.getTypeInfoInChars(CAT->getElementType());
1654 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001655 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1656 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001657 "Overflow in array type char size evaluation");
1658 uint64_t Width = EltInfo.first.getQuantity() * Size;
1659 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001660 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1661 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001662 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001663 return std::make_pair(CharUnits::fromQuantity(Width),
1664 CharUnits::fromQuantity(Align));
1665}
1666
John McCall87fe5d52010-05-20 01:18:31 +00001667std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001668ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001669 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001670 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001671 TypeInfo Info = getTypeInfo(T);
1672 return std::make_pair(toCharUnitsFromBits(Info.Width),
1673 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001674}
1675
1676std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001677ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001678 return getTypeInfoInChars(T.getTypePtr());
1679}
1680
David Majnemer34b57492014-07-30 01:30:47 +00001681bool ASTContext::isAlignmentRequired(const Type *T) const {
1682 return getTypeInfo(T).AlignIsRequired;
1683}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001684
David Majnemer34b57492014-07-30 01:30:47 +00001685bool ASTContext::isAlignmentRequired(QualType T) const {
1686 return isAlignmentRequired(T.getTypePtr());
1687}
1688
Richard Smithb2f0f052016-10-10 18:54:32 +00001689unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1690 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001691 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001692 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1693 return Align;
1694
1695 // If we have an (array of) complete type, we're done.
1696 T = getBaseElementType(T);
1697 if (!T->isIncompleteType())
1698 return getTypeAlign(T);
1699
1700 // If we had an array type, its element type might be a typedef
1701 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001702 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001703 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1704 return Align;
1705
1706 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001707 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001708 return TT->getDecl()->getMaxAlignment();
1709
1710 return 0;
1711}
1712
David Majnemer34b57492014-07-30 01:30:47 +00001713TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001714 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1715 if (I != MemoizedTypeInfo.end())
1716 return I->second;
1717
1718 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1719 TypeInfo TI = getTypeInfoImpl(T);
1720 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001721 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001722}
1723
1724/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1725/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001726///
1727/// FIXME: Pointers into different addr spaces could have different sizes and
1728/// alignment requirements: getPointerInfo should take an AddrSpace, this
1729/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001730TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1731 uint64_t Width = 0;
1732 unsigned Align = 8;
1733 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001734 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001735 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001736#define TYPE(Class, Base)
1737#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001738#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001739#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001740#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1741 case Type::Class: \
1742 assert(!T->isDependentType() && "should not see dependent types here"); \
1743 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001744#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001745 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001746
Chris Lattner355332d2007-07-13 22:27:08 +00001747 case Type::FunctionNoProto:
1748 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001749 // GCC extension: alignof(function) = 32 bits
1750 Width = 0;
1751 Align = 32;
1752 break;
1753
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001754 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001755 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001756 Width = 0;
1757 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1758 break;
1759
Steve Naroff5c131802007-08-30 01:06:46 +00001760 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001761 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001762
David Majnemer34b57492014-07-30 01:30:47 +00001763 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001764 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001765 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001766 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001767 Width = EltInfo.Width * Size;
1768 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001769 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1770 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001771 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001772 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001773 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001774 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001775 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001776 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001777 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1778 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001779 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001780 // If the alignment is not a power of 2, round up to the next power of 2.
1781 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001782 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001783 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001784 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001785 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001786 // Adjust the alignment based on the target max.
1787 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1788 if (TargetVectorAlign && TargetVectorAlign < Align)
1789 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001790 break;
1791 }
Chris Lattner647fb222007-07-18 18:26:58 +00001792
Chris Lattner7570e9c2008-03-08 08:52:55 +00001793 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001794 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001795 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001796 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001797 // GCC extension: alignof(void) = 8 bits.
1798 Width = 0;
1799 Align = 8;
1800 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001801 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001802 Width = Target->getBoolWidth();
1803 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001804 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001805 case BuiltinType::Char_S:
1806 case BuiltinType::Char_U:
1807 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001808 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001809 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001810 Width = Target->getCharWidth();
1811 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001812 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001813 case BuiltinType::WChar_S:
1814 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001815 Width = Target->getWCharWidth();
1816 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001817 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001818 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001819 Width = Target->getChar16Width();
1820 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001821 break;
1822 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001823 Width = Target->getChar32Width();
1824 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001825 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001826 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001827 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001828 Width = Target->getShortWidth();
1829 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001830 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001831 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001832 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001833 Width = Target->getIntWidth();
1834 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001835 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001836 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001837 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001838 Width = Target->getLongWidth();
1839 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001840 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001841 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001842 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001843 Width = Target->getLongLongWidth();
1844 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001845 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001846 case BuiltinType::Int128:
1847 case BuiltinType::UInt128:
1848 Width = 128;
1849 Align = 128; // int128_t is 128-bit aligned on all targets.
1850 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001851 case BuiltinType::ShortAccum:
1852 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001853 case BuiltinType::SatShortAccum:
1854 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001855 Width = Target->getShortAccumWidth();
1856 Align = Target->getShortAccumAlign();
1857 break;
1858 case BuiltinType::Accum:
1859 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001860 case BuiltinType::SatAccum:
1861 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001862 Width = Target->getAccumWidth();
1863 Align = Target->getAccumAlign();
1864 break;
1865 case BuiltinType::LongAccum:
1866 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001867 case BuiltinType::SatLongAccum:
1868 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001869 Width = Target->getLongAccumWidth();
1870 Align = Target->getLongAccumAlign();
1871 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00001872 case BuiltinType::ShortFract:
1873 case BuiltinType::UShortFract:
1874 case BuiltinType::SatShortFract:
1875 case BuiltinType::SatUShortFract:
1876 Width = Target->getShortFractWidth();
1877 Align = Target->getShortFractAlign();
1878 break;
1879 case BuiltinType::Fract:
1880 case BuiltinType::UFract:
1881 case BuiltinType::SatFract:
1882 case BuiltinType::SatUFract:
1883 Width = Target->getFractWidth();
1884 Align = Target->getFractAlign();
1885 break;
1886 case BuiltinType::LongFract:
1887 case BuiltinType::ULongFract:
1888 case BuiltinType::SatLongFract:
1889 case BuiltinType::SatULongFract:
1890 Width = Target->getLongFractWidth();
1891 Align = Target->getLongFractAlign();
1892 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001893 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001894 case BuiltinType::Half:
Alexey Bataev123ad192019-02-27 20:29:45 +00001895 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
1896 !getLangOpts().OpenMPIsDevice) {
1897 Width = Target->getHalfWidth();
1898 Align = Target->getHalfAlign();
1899 } else {
1900 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1901 "Expected OpenMP device compilation.");
1902 Width = AuxTarget->getHalfWidth();
1903 Align = AuxTarget->getHalfAlign();
1904 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001905 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001906 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001907 Width = Target->getFloatWidth();
1908 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001909 break;
1910 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001911 Width = Target->getDoubleWidth();
1912 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001913 break;
1914 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001915 Width = Target->getLongDoubleWidth();
1916 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001917 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001918 case BuiltinType::Float128:
Alexey Bataev123ad192019-02-27 20:29:45 +00001919 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
1920 !getLangOpts().OpenMPIsDevice) {
1921 Width = Target->getFloat128Width();
1922 Align = Target->getFloat128Align();
1923 } else {
1924 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1925 "Expected OpenMP device compilation.");
1926 Width = AuxTarget->getFloat128Width();
1927 Align = AuxTarget->getFloat128Align();
1928 }
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001929 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001930 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001931 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1932 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001933 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001934 case BuiltinType::ObjCId:
1935 case BuiltinType::ObjCClass:
1936 case BuiltinType::ObjCSel:
Fangrui Song6907ce22018-07-30 19:24:48 +00001937 Width = Target->getPointerWidth(0);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001938 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001939 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001940 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001941 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001942 case BuiltinType::OCLClkEvent:
1943 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001944 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001945#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1946 case BuiltinType::Id:
1947#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001948#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1949 case BuiltinType::Id:
1950#include "clang/Basic/OpenCLExtensionTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00001951 AS = getTargetAddressSpace(
1952 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001953 Width = Target->getPointerWidth(AS);
1954 Align = Target->getPointerAlign(AS);
1955 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001956 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001957 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001958 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001959 Width = Target->getPointerWidth(0);
1960 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001961 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001962 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001963 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001964 Width = Target->getPointerWidth(AS);
1965 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001966 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001967 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001968 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001969 // alignof and sizeof should never enter this code path here, so we go
1970 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001971 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001972 Width = Target->getPointerWidth(AS);
1973 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001974 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001975 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001976 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001977 Width = Target->getPointerWidth(AS);
1978 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001979 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001980 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001981 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00001982 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1983 Width = MPI.Width;
1984 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00001985 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001986 }
Chris Lattner647fb222007-07-18 18:26:58 +00001987 case Type::Complex: {
1988 // Complex types have the same alignment as their elements, but twice the
1989 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001990 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1991 Width = EltInfo.Width * 2;
1992 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001993 break;
1994 }
John McCall8b07ec22010-05-15 11:32:37 +00001995 case Type::ObjCObject:
1996 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001997 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001998 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001999 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00002000 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002001 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00002002 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00002003 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002004 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00002005 break;
2006 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002007 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002008 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002009 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00002010
2011 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00002012 Width = 8;
2013 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00002014 break;
2015 }
Mike Stump11289f42009-09-09 15:08:12 +00002016
Eugene Zelenko7855e772018-04-03 00:11:50 +00002017 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00002018 const EnumDecl *ED = ET->getDecl();
2019 TypeInfo Info =
2020 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2021 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2022 Info.Align = AttrAlign;
2023 Info.AlignIsRequired = true;
2024 }
2025 return Info;
2026 }
Chris Lattner8b23c252008-04-06 22:05:18 +00002027
Eugene Zelenko7855e772018-04-03 00:11:50 +00002028 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00002029 const RecordDecl *RD = RT->getDecl();
2030 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00002031 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002032 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00002033 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00002034 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00002035 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002036
Chris Lattner63d2b362009-10-22 05:17:15 +00002037 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00002038 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2039 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00002040
Richard Smith600b5262017-01-26 20:40:47 +00002041 case Type::Auto:
2042 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002043 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00002044 assert(!A->getDeducedType().isNull() &&
2045 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00002046 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00002047 }
2048
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002049 case Type::Paren:
2050 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2051
Leonard Chanc72aaf62019-05-07 03:20:17 +00002052 case Type::MacroQualified:
2053 return getTypeInfo(
2054 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2055
Manman Rene6be26c2016-09-13 17:25:08 +00002056 case Type::ObjCTypeParam:
2057 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2058
Douglas Gregoref462e62009-04-30 17:32:17 +00002059 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002060 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002061 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002062 // If the typedef has an aligned attribute on it, it overrides any computed
2063 // alignment we have. This violates the GCC documentation (which says that
2064 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002065 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002066 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002067 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002068 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002069 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002070 AlignIsRequired = Info.AlignIsRequired;
2071 }
David Majnemer34b57492014-07-30 01:30:47 +00002072 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002073 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002074 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002075
Abramo Bagnara6150c882010-05-11 21:36:43 +00002076 case Type::Elaborated:
2077 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002078
John McCall81904512011-01-06 01:58:22 +00002079 case Type::Attributed:
2080 return getTypeInfo(
2081 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2082
Eli Friedman0dfb8892011-10-06 23:00:33 +00002083 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002084 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002085 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2086 Width = Info.Width;
2087 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002088
JF Bastien801fca22018-05-09 03:51:12 +00002089 if (!Width) {
2090 // An otherwise zero-sized type should still generate an
2091 // atomic operation.
2092 Width = Target->getCharWidth();
2093 assert(Align);
2094 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2095 // If the size of the type doesn't exceed the platform's max
2096 // atomic promotion width, make the size and alignment more
2097 // favorable to atomic operations:
2098
John McCalla8ec7eb2013-03-07 21:37:17 +00002099 // Round the size up to a power of 2.
2100 if (!llvm::isPowerOf2_64(Width))
2101 Width = llvm::NextPowerOf2(Width);
2102
2103 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002104 Align = static_cast<unsigned>(Width);
2105 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002106 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002107 break;
2108
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002109 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002110 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2111 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002112 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002113 }
Mike Stump11289f42009-09-09 15:08:12 +00002114
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002115 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002116 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002117}
2118
Momchil Velikov20208cc2018-07-30 17:48:23 +00002119unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2120 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2121 if (I != MemoizedUnadjustedAlign.end())
2122 return I->second;
2123
2124 unsigned UnadjustedAlign;
2125 if (const auto *RT = T->getAs<RecordType>()) {
2126 const RecordDecl *RD = RT->getDecl();
2127 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2128 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2129 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2130 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2131 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2132 } else {
2133 UnadjustedAlign = getTypeAlign(T);
2134 }
2135
2136 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2137 return UnadjustedAlign;
2138}
2139
Alexey Bataev00396512015-07-02 03:40:19 +00002140unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2141 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2142 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2143 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2144 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2145 getTargetInfo().getABI() == "elfv1-qpx" &&
2146 T->isSpecificBuiltinType(BuiltinType::Double))
2147 SimdAlign = 256;
2148 return SimdAlign;
2149}
2150
Ken Dyckcc56c542011-01-15 18:38:59 +00002151/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2152CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2153 return CharUnits::fromQuantity(BitSize / getCharWidth());
2154}
2155
Ken Dyckb0fcc592011-02-11 01:54:29 +00002156/// toBits - Convert a size in characters to a size in characters.
2157int64_t ASTContext::toBits(CharUnits CharSize) const {
2158 return CharSize.getQuantity() * getCharWidth();
2159}
2160
Ken Dyck8c89d592009-12-22 14:23:30 +00002161/// getTypeSizeInChars - Return the size of the specified type, in characters.
2162/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002163CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002164 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002165}
Jay Foad39c79802011-01-12 09:06:06 +00002166CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002167 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002168}
2169
Fangrui Song6907ce22018-07-30 19:24:48 +00002170/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002171/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002172CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002173 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002174}
Jay Foad39c79802011-01-12 09:06:06 +00002175CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002176 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002177}
2178
Momchil Velikov20208cc2018-07-30 17:48:23 +00002179/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2180/// type, in characters, before alignment adustments. This method does
2181/// not work on incomplete types.
2182CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2183 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2184}
2185CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2186 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2187}
2188
Chris Lattnera3402cd2009-01-27 18:08:34 +00002189/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2190/// type for the current target in bits. This can be different than the ABI
2191/// alignment in cases where it is beneficial for performance to overalign
2192/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002193unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002194 TypeInfo TI = getTypeInfo(T);
2195 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002196
David Majnemere1544562015-04-24 01:25:05 +00002197 T = T->getBaseElementTypeUnsafe();
2198
2199 // The preferred alignment of member pointers is that of a pointer.
2200 if (T->isMemberPointerType())
2201 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2202
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002203 if (!Target->allowsLargerPreferedTypeAlignment())
2204 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002205
Eli Friedman7ab09572009-05-25 21:27:19 +00002206 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002207 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002208 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002209 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002210 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002211 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002212 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2213 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002214 // Don't increase the alignment if an alignment attribute was specified on a
2215 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002216 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002217 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002218
Chris Lattnera3402cd2009-01-27 18:08:34 +00002219 return ABIAlign;
2220}
2221
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002222/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2223/// for __attribute__((aligned)) on this target, to be used if no alignment
2224/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002225unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002226 return getTargetInfo().getDefaultAlignForAttributeAligned();
2227}
2228
Ulrich Weigandfa806422013-05-06 16:23:57 +00002229/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2230/// to a global variable of the specified type.
2231unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
Tom Tanb7c6d952019-05-02 00:38:14 +00002232 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2233 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
Ulrich Weigandfa806422013-05-06 16:23:57 +00002234}
2235
2236/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2237/// should be given to a global variable of the specified type.
2238CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2239 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2240}
2241
David Majnemer08ef2ba2015-06-23 20:34:18 +00002242CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2243 CharUnits Offset = CharUnits::Zero();
2244 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2245 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2246 Offset += Layout->getBaseClassOffset(Base);
2247 Layout = &getASTRecordLayout(Base);
2248 }
2249 return Offset;
2250}
2251
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002252/// DeepCollectObjCIvars -
2253/// This routine first collects all declared, but not synthesized, ivars in
2254/// super class and then collects all ivars, including those synthesized for
2255/// current class. This routine is used for implementation of current class
2256/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002257void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2258 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002259 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002260 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2261 DeepCollectObjCIvars(SuperClass, false, Ivars);
2262 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002263 for (const auto *I : OI->ivars())
2264 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002265 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002266 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Fangrui Song6907ce22018-07-30 19:24:48 +00002267 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002268 Iv= Iv->getNextIvar())
2269 Ivars.push_back(Iv);
2270 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002271}
2272
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002273/// CollectInheritedProtocols - Collect all protocols in current class and
2274/// those inherited by it.
2275void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002276 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002277 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002278 // We can use protocol_iterator here instead of
Fangrui Song6907ce22018-07-30 19:24:48 +00002279 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002280 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002281 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002282 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002283
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002284 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002285 for (const auto *Cat : OI->visible_categories())
2286 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002287
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002288 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2289 while (SD) {
2290 CollectInheritedProtocols(SD, Protocols);
2291 SD = SD->getSuperClass();
2292 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002293 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002294 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002295 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002296 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002297 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002298 // Insert the protocol.
2299 if (!Protocols.insert(
2300 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2301 return;
2302
2303 for (auto *Proto : OP->protocols())
2304 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002305 }
2306}
2307
Erich Keane8a6b7402017-11-30 16:37:02 +00002308static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2309 const RecordDecl *RD) {
2310 assert(RD->isUnion() && "Must be union type");
2311 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2312
2313 for (const auto *Field : RD->fields()) {
2314 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2315 return false;
2316 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2317 if (FieldSize != UnionSize)
2318 return false;
2319 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002320 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002321}
2322
Benjamin Kramer802e6252017-12-24 12:46:22 +00002323static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002324 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2325
2326 if (!RD->field_empty())
2327 return false;
2328
2329 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2330 return ClassDecl->isEmpty();
2331
2332 return true;
2333}
2334
2335static llvm::Optional<int64_t>
2336structHasUniqueObjectRepresentations(const ASTContext &Context,
2337 const RecordDecl *RD) {
2338 assert(!RD->isUnion() && "Must be struct/class type");
2339 const auto &Layout = Context.getASTRecordLayout(RD);
2340
2341 int64_t CurOffsetInBits = 0;
2342 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2343 if (ClassDecl->isDynamicClass())
2344 return llvm::None;
2345
2346 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2347 for (const auto Base : ClassDecl->bases()) {
2348 // Empty types can be inherited from, and non-empty types can potentially
2349 // have tail padding, so just make sure there isn't an error.
2350 if (!isStructEmpty(Base.getType())) {
2351 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2352 Context, Base.getType()->getAs<RecordType>()->getDecl());
2353 if (!Size)
2354 return llvm::None;
2355 Bases.emplace_back(Base.getType(), Size.getValue());
2356 }
2357 }
2358
Fangrui Song1d38c132018-09-30 21:41:11 +00002359 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2360 const std::pair<QualType, int64_t> &R) {
2361 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2362 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2363 });
Erich Keane8a6b7402017-11-30 16:37:02 +00002364
2365 for (const auto Base : Bases) {
2366 int64_t BaseOffset = Context.toBits(
2367 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2368 int64_t BaseSize = Base.second;
2369 if (BaseOffset != CurOffsetInBits)
2370 return llvm::None;
2371 CurOffsetInBits = BaseOffset + BaseSize;
2372 }
2373 }
2374
2375 for (const auto *Field : RD->fields()) {
2376 if (!Field->getType()->isReferenceType() &&
2377 !Context.hasUniqueObjectRepresentations(Field->getType()))
2378 return llvm::None;
2379
2380 int64_t FieldSizeInBits =
2381 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2382 if (Field->isBitField()) {
2383 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2384
2385 if (BitfieldSize > FieldSizeInBits)
2386 return llvm::None;
2387 FieldSizeInBits = BitfieldSize;
2388 }
2389
2390 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2391
2392 if (FieldOffsetInBits != CurOffsetInBits)
2393 return llvm::None;
2394
2395 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2396 }
2397
2398 return CurOffsetInBits;
2399}
2400
2401bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2402 // C++17 [meta.unary.prop]:
2403 // The predicate condition for a template specialization
2404 // has_unique_object_representations<T> shall be
2405 // satisfied if and only if:
2406 // (9.1) - T is trivially copyable, and
2407 // (9.2) - any two objects of type T with the same value have the same
2408 // object representation, where two objects
2409 // of array or non-union class type are considered to have the same value
2410 // if their respective sequences of
2411 // direct subobjects have the same values, and two objects of union type
2412 // are considered to have the same
2413 // value if they have the same active member and the corresponding members
2414 // have the same value.
2415 // The set of scalar types for which this condition holds is
2416 // implementation-defined. [ Note: If a type has padding
2417 // bits, the condition does not hold; otherwise, the condition holds true
2418 // for unsigned integral types. -- end note ]
2419 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2420
2421 // Arrays are unique only if their element type is unique.
2422 if (Ty->isArrayType())
2423 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2424
2425 // (9.1) - T is trivially copyable...
2426 if (!Ty.isTriviallyCopyableType(*this))
2427 return false;
2428
2429 // All integrals and enums are unique.
2430 if (Ty->isIntegralOrEnumerationType())
2431 return true;
2432
2433 // All other pointers are unique.
2434 if (Ty->isPointerType())
2435 return true;
2436
2437 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002438 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002439 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2440 }
2441
2442 if (Ty->isRecordType()) {
2443 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2444
Erich Keanebd2197c2017-12-12 16:02:06 +00002445 if (Record->isInvalidDecl())
2446 return false;
2447
Erich Keane8a6b7402017-11-30 16:37:02 +00002448 if (Record->isUnion())
2449 return unionHasUniqueObjectRepresentations(*this, Record);
2450
2451 Optional<int64_t> StructSize =
2452 structHasUniqueObjectRepresentations(*this, Record);
2453
2454 return StructSize &&
2455 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2456 }
2457
2458 // FIXME: More cases to handle here (list by rsmith):
2459 // vectors (careful about, eg, vector of 3 foo)
2460 // _Complex int and friends
2461 // _Atomic T
2462 // Obj-C block pointers
2463 // Obj-C object pointers
2464 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2465 // clk_event_t, queue_t, reserve_id_t)
2466 // There're also Obj-C class types and the Obj-C selector type, but I think it
2467 // makes sense for those to return false here.
2468
2469 return false;
2470}
2471
Jay Foad39c79802011-01-12 09:06:06 +00002472unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002473 unsigned count = 0;
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002474 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002475 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002476 count += Ext->ivar_size();
Fangrui Song6907ce22018-07-30 19:24:48 +00002477
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002478 // Count ivar defined in this class's implementation. This
2479 // includes synthesized ivars.
2480 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002481 count += ImplDecl->ivar_size();
2482
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002483 return count;
2484}
2485
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002486bool ASTContext::isSentinelNullExpr(const Expr *E) {
2487 if (!E)
2488 return false;
2489
2490 // nullptr_t is always treated as null.
2491 if (E->getType()->isNullPtrType()) return true;
2492
2493 if (E->getType()->isAnyPointerType() &&
2494 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2495 Expr::NPC_ValueDependentIsNull))
2496 return true;
2497
2498 // Unfortunately, __null has type 'int'.
2499 if (isa<GNUNullExpr>(E)) return true;
2500
2501 return false;
2502}
2503
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002504/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002505/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002506ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2507 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2508 I = ObjCImpls.find(D);
2509 if (I != ObjCImpls.end())
2510 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002511 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002512}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002513
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002514/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002515/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002516ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2517 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2518 I = ObjCImpls.find(D);
2519 if (I != ObjCImpls.end())
2520 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002521 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002522}
2523
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002524/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002525void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2526 ObjCImplementationDecl *ImplD) {
2527 assert(IFaceD && ImplD && "Passed null params");
2528 ObjCImpls[IFaceD] = ImplD;
2529}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002530
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002531/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002532void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2533 ObjCCategoryImplDecl *ImplD) {
2534 assert(CatD && ImplD && "Passed null params");
2535 ObjCImpls[CatD] = ImplD;
2536}
2537
Chandler Carruth21c90602015-12-30 03:24:14 +00002538const ObjCMethodDecl *
2539ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2540 return ObjCMethodRedecls.lookup(MD);
2541}
2542
2543void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2544 const ObjCMethodDecl *Redecl) {
2545 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2546 ObjCMethodRedecls[MD] = Redecl;
2547}
2548
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002549const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2550 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002551 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002552 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002553 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002554 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002555 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002556 return IMD->getClassInterface();
2557
Craig Topper36250ad2014-05-12 05:36:57 +00002558 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002559}
2560
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002561/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002562/// none exists.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002563ASTContext::BlockVarCopyInit
2564ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002565 assert(VD && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002566 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002567 "getBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002568 auto I = BlockVarCopyInits.find(VD);
2569 if (I != BlockVarCopyInits.end())
2570 return I->second;
2571 return {nullptr, false};
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002572}
2573
JF Bastien0d702a72019-04-30 00:11:53 +00002574/// Set the copy initialization expression of a block var decl.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002575void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2576 bool CanThrow) {
2577 assert(VD && CopyExpr && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002578 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002579 "setBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002580 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002581}
2582
John McCallbcd03502009-12-07 02:54:59 +00002583TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002584 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002585 if (!DataSize)
2586 DataSize = TypeLoc::getFullDataSizeForType(T);
2587 else
2588 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002589 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002590
Eugene Zelenko7855e772018-04-03 00:11:50 +00002591 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002592 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2593 new (TInfo) TypeSourceInfo(T);
2594 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002595}
2596
John McCallbcd03502009-12-07 02:54:59 +00002597TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002598 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002599 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002600 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002601 return DI;
2602}
2603
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002604const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002605ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002606 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002607}
2608
2609const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002610ASTContext::getASTObjCImplementationLayout(
2611 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002612 return getObjCLayout(D->getClassInterface(), D);
2613}
2614
Chris Lattner983a8bb2007-07-13 22:13:22 +00002615//===----------------------------------------------------------------------===//
2616// Type creation/memoization methods
2617//===----------------------------------------------------------------------===//
2618
Jay Foad39c79802011-01-12 09:06:06 +00002619QualType
John McCall33ddac02011-01-19 10:06:00 +00002620ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2621 unsigned fastQuals = quals.getFastQualifiers();
2622 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002623
2624 // Check if we've already instantiated this type.
2625 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002626 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002627 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002628 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2629 assert(eq->getQualifiers() == quals);
2630 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002631 }
2632
John McCall33ddac02011-01-19 10:06:00 +00002633 // If the base type is not canonical, make the appropriate canonical type.
2634 QualType canon;
2635 if (!baseType->isCanonicalUnqualified()) {
2636 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002637 canonSplit.Quals.addConsistentQualifiers(quals);
2638 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002639
2640 // Re-find the insert position.
2641 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2642 }
2643
Eugene Zelenko7855e772018-04-03 00:11:50 +00002644 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002645 ExtQualNodes.InsertNode(eq, insertPos);
2646 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002647}
2648
Alexander Richardson6d989432017-10-15 18:48:14 +00002649QualType ASTContext::getAddrSpaceQualType(QualType T,
2650 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002651 QualType CanT = getCanonicalType(T);
2652 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002653 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002654
John McCall8ccfcb52009-09-24 19:53:00 +00002655 // If we are composing extended qualifiers together, merge together
2656 // into one ExtQuals node.
2657 QualifierCollector Quals;
2658 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002659
John McCall8ccfcb52009-09-24 19:53:00 +00002660 // If this type already has an address space specified, it cannot get
2661 // another one.
2662 assert(!Quals.hasAddressSpace() &&
2663 "Type cannot be in multiple addr spaces!");
2664 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002665
John McCall8ccfcb52009-09-24 19:53:00 +00002666 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002667}
2668
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002669QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2670 // If we are composing extended qualifiers together, merge together
2671 // into one ExtQuals node.
2672 QualifierCollector Quals;
2673 const Type *TypeNode = Quals.strip(T);
2674
2675 // If the qualifier doesn't have an address space just return it.
2676 if (!Quals.hasAddressSpace())
2677 return T;
2678
2679 Quals.removeAddressSpace();
2680
2681 // Removal of the address space can mean there are no longer any
2682 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2683 // or required.
2684 if (Quals.hasNonFastQualifiers())
2685 return getExtQualType(TypeNode, Quals);
2686 else
2687 return QualType(TypeNode, Quals.getFastQualifiers());
2688}
2689
Chris Lattnerd60183d2009-02-18 22:53:11 +00002690QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002691 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002692 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002693 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002694 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002695
Eugene Zelenko7855e772018-04-03 00:11:50 +00002696 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002697 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002698 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002699 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2700 return getPointerType(ResultType);
2701 }
2702 }
Mike Stump11289f42009-09-09 15:08:12 +00002703
John McCall8ccfcb52009-09-24 19:53:00 +00002704 // If we are composing extended qualifiers together, merge together
2705 // into one ExtQuals node.
2706 QualifierCollector Quals;
2707 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002708
John McCall8ccfcb52009-09-24 19:53:00 +00002709 // If this type already has an ObjCGC specified, it cannot get
2710 // another one.
2711 assert(!Quals.hasObjCGCAttr() &&
2712 "Type cannot have multiple ObjCGCs!");
2713 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002714
John McCall8ccfcb52009-09-24 19:53:00 +00002715 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002716}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002717
John McCall4f5019e2010-12-19 02:44:49 +00002718const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2719 FunctionType::ExtInfo Info) {
2720 if (T->getExtInfo() == Info)
2721 return T;
2722
2723 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002724 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002725 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002726 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002727 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002728 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2729 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002730 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002731 }
2732
2733 return cast<FunctionType>(Result.getTypePtr());
2734}
2735
Richard Smith2a7d4812013-05-04 07:00:32 +00002736void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2737 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002738 FD = FD->getMostRecentDecl();
2739 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002740 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002741 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002742 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002743 if (FunctionDecl *Next = FD->getPreviousDecl())
2744 FD = Next;
2745 else
2746 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002747 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002748 if (ASTMutationListener *L = getASTMutationListener())
2749 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002750}
2751
Richard Smith0b3a4622014-11-13 20:01:57 +00002752/// Get a function type and produce the equivalent function type with the
2753/// specified exception specification. Type sugar that can be present on a
2754/// declaration of a function with an exception specification is permitted
2755/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002756QualType ASTContext::getFunctionTypeWithExceptionSpec(
2757 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002758 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002759 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002760 return getParenType(
2761 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002762
Leonard Chandc5d9752019-05-10 18:05:15 +00002763 // Might be wrapped in a macro qualified type.
2764 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2765 return getMacroQualifiedType(
2766 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2767 MQT->getMacroIdentifier());
2768
Richard Smith0b3a4622014-11-13 20:01:57 +00002769 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002770 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002771 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002772 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002773 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2774 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002775
2776 // Anything else must be a function type. Rebuild it with the new exception
2777 // specification.
Stephan Bergmann84dcc8f2019-02-13 09:39:17 +00002778 const auto *Proto = Orig->getAs<FunctionProtoType>();
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002779 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002780 Proto->getReturnType(), Proto->getParamTypes(),
2781 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2782}
2783
Richard Smithdfe85e22016-12-15 02:35:39 +00002784bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2785 QualType U) {
2786 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002787 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002788 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2789 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002790}
2791
Richard Smith0b3a4622014-11-13 20:01:57 +00002792void ASTContext::adjustExceptionSpec(
2793 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2794 bool AsWritten) {
2795 // Update the type.
2796 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002797 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002798 FD->setType(Updated);
2799
2800 if (!AsWritten)
2801 return;
2802
2803 // Update the type in the type source information too.
2804 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2805 // If the type and the type-as-written differ, we may need to update
2806 // the type-as-written too.
2807 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002808 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002809
2810 // FIXME: When we get proper type location information for exceptions,
2811 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2812 // up the TypeSourceInfo;
2813 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2814 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2815 "TypeLoc size mismatch from updating exception specification");
2816 TSInfo->overrideType(Updated);
2817 }
2818}
2819
Chris Lattnerc6395932007-06-22 20:56:16 +00002820/// getComplexType - Return the uniqued reference to the type for a complex
2821/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002822QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002823 // Unique pointers, to guarantee there is only one pointer of a particular
2824 // structure.
2825 llvm::FoldingSetNodeID ID;
2826 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002827
Craig Topper36250ad2014-05-12 05:36:57 +00002828 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002829 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2830 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002831
Chris Lattnerc6395932007-06-22 20:56:16 +00002832 // If the pointee type isn't canonical, this won't be a canonical type either,
2833 // so fill in the canonical type field.
2834 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002835 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002836 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002837
Chris Lattnerc6395932007-06-22 20:56:16 +00002838 // Get the new insert position for the node we care about.
2839 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002840 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002841 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002842 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002843 Types.push_back(New);
2844 ComplexTypes.InsertNode(New, InsertPos);
2845 return QualType(New, 0);
2846}
2847
Chris Lattner970e54e2006-11-12 00:37:36 +00002848/// getPointerType - Return the uniqued reference to the type for a pointer to
2849/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002850QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002851 // Unique pointers, to guarantee there is only one pointer of a particular
2852 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002853 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002854 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002855
Craig Topper36250ad2014-05-12 05:36:57 +00002856 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002857 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002858 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002859
Chris Lattner7ccecb92006-11-12 08:50:50 +00002860 // If the pointee type isn't canonical, this won't be a canonical type either,
2861 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002862 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002863 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002864 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002865
Bob Wilsonc8541f22013-03-15 17:12:43 +00002866 // Get the new insert position for the node we care about.
2867 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002868 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002869 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002870 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002871 Types.push_back(New);
2872 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002873 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002874}
2875
Reid Kleckner0503a872013-12-05 01:23:43 +00002876QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2877 llvm::FoldingSetNodeID ID;
2878 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002879 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002880 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2881 if (AT)
2882 return QualType(AT, 0);
2883
2884 QualType Canonical = getCanonicalType(New);
2885
2886 // Get the new insert position for the node we care about.
2887 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002888 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002889
2890 AT = new (*this, TypeAlignment)
2891 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2892 Types.push_back(AT);
2893 AdjustedTypes.InsertNode(AT, InsertPos);
2894 return QualType(AT, 0);
2895}
2896
Reid Kleckner8a365022013-06-24 17:51:48 +00002897QualType ASTContext::getDecayedType(QualType T) const {
2898 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2899
Reid Kleckner8a365022013-06-24 17:51:48 +00002900 QualType Decayed;
2901
2902 // C99 6.7.5.3p7:
2903 // A declaration of a parameter as "array of type" shall be
2904 // adjusted to "qualified pointer to type", where the type
2905 // qualifiers (if any) are those specified within the [ and ] of
2906 // the array type derivation.
2907 if (T->isArrayType())
2908 Decayed = getArrayDecayedType(T);
2909
2910 // C99 6.7.5.3p8:
2911 // A declaration of a parameter as "function returning type"
2912 // shall be adjusted to "pointer to function returning type", as
2913 // in 6.3.2.1.
2914 if (T->isFunctionType())
2915 Decayed = getPointerType(T);
2916
Reid Kleckner0503a872013-12-05 01:23:43 +00002917 llvm::FoldingSetNodeID ID;
2918 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002919 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002920 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2921 if (AT)
2922 return QualType(AT, 0);
2923
Reid Kleckner8a365022013-06-24 17:51:48 +00002924 QualType Canonical = getCanonicalType(Decayed);
2925
2926 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002927 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002928 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002929
Reid Kleckner0503a872013-12-05 01:23:43 +00002930 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2931 Types.push_back(AT);
2932 AdjustedTypes.InsertNode(AT, InsertPos);
2933 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002934}
2935
Mike Stump11289f42009-09-09 15:08:12 +00002936/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002937/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002938QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002939 assert(T->isFunctionType() && "block of function types only");
2940 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002941 // structure.
2942 llvm::FoldingSetNodeID ID;
2943 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002944
Craig Topper36250ad2014-05-12 05:36:57 +00002945 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002946 if (BlockPointerType *PT =
2947 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2948 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002949
2950 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002951 // type either so fill in the canonical type field.
2952 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002953 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002954 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002955
Steve Naroffec33ed92008-08-27 16:04:49 +00002956 // Get the new insert position for the node we care about.
2957 BlockPointerType *NewIP =
2958 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002959 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002960 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002961 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002962 Types.push_back(New);
2963 BlockPointerTypes.InsertNode(New, InsertPos);
2964 return QualType(New, 0);
2965}
2966
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002967/// getLValueReferenceType - Return the uniqued reference to the type for an
2968/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002969QualType
2970ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002971 assert(getCanonicalType(T) != OverloadTy &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002972 "Unresolved overloaded function type");
Fangrui Song6907ce22018-07-30 19:24:48 +00002973
Bill Wendling3708c182007-05-27 10:15:43 +00002974 // Unique pointers, to guarantee there is only one pointer of a particular
2975 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002976 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002977 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002978
Craig Topper36250ad2014-05-12 05:36:57 +00002979 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002980 if (LValueReferenceType *RT =
2981 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002982 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002983
Eugene Zelenko7855e772018-04-03 00:11:50 +00002984 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002985
Bill Wendling3708c182007-05-27 10:15:43 +00002986 // If the referencee type isn't canonical, this won't be a canonical type
2987 // either, so fill in the canonical type field.
2988 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002989 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2990 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2991 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002992
Bill Wendling3708c182007-05-27 10:15:43 +00002993 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002994 LValueReferenceType *NewIP =
2995 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002996 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002997 }
2998
Eugene Zelenko7855e772018-04-03 00:11:50 +00002999 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3000 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00003001 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003002 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00003003
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003004 return QualType(New, 0);
3005}
3006
3007/// getRValueReferenceType - Return the uniqued reference to the type for an
3008/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003009QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003010 // Unique pointers, to guarantee there is only one pointer of a particular
3011 // structure.
3012 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003013 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003014
Craig Topper36250ad2014-05-12 05:36:57 +00003015 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003016 if (RValueReferenceType *RT =
3017 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3018 return QualType(RT, 0);
3019
Eugene Zelenko7855e772018-04-03 00:11:50 +00003020 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003021
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003022 // If the referencee type isn't canonical, this won't be a canonical type
3023 // either, so fill in the canonical type field.
3024 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003025 if (InnerRef || !T.isCanonical()) {
3026 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3027 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003028
3029 // Get the new insert position for the node we care about.
3030 RValueReferenceType *NewIP =
3031 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003032 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003033 }
3034
Eugene Zelenko7855e772018-04-03 00:11:50 +00003035 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003036 Types.push_back(New);
3037 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00003038 return QualType(New, 0);
3039}
3040
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003041/// getMemberPointerType - Return the uniqued reference to the type for a
3042/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00003043QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003044 // Unique pointers, to guarantee there is only one pointer of a particular
3045 // structure.
3046 llvm::FoldingSetNodeID ID;
3047 MemberPointerType::Profile(ID, T, Cls);
3048
Craig Topper36250ad2014-05-12 05:36:57 +00003049 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003050 if (MemberPointerType *PT =
3051 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3052 return QualType(PT, 0);
3053
3054 // If the pointee or class type isn't canonical, this won't be a canonical
3055 // type either, so fill in the canonical type field.
3056 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00003057 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003058 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3059
3060 // Get the new insert position for the node we care about.
3061 MemberPointerType *NewIP =
3062 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003063 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003064 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003065 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003066 Types.push_back(New);
3067 MemberPointerTypes.InsertNode(New, InsertPos);
3068 return QualType(New, 0);
3069}
3070
Mike Stump11289f42009-09-09 15:08:12 +00003071/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00003072/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00003073QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00003074 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003075 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003076 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00003077 assert((EltTy->isDependentType() ||
3078 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00003079 "Constant array of VLAs is illegal!");
3080
Chris Lattnere2df3f92009-05-13 04:12:56 +00003081 // Convert the array size into a canonical width matching the pointer size for
3082 // the target.
3083 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00003084 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00003085
Chris Lattner23b7eb62007-06-15 23:05:46 +00003086 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00003087 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00003088
Craig Topper36250ad2014-05-12 05:36:57 +00003089 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003090 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003091 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003092 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003093
John McCall33ddac02011-01-19 10:06:00 +00003094 // If the element type isn't canonical or has qualifiers, this won't
3095 // be a canonical type either, so fill in the canonical type field.
3096 QualType Canon;
3097 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3098 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003099 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003100 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003101 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003102
Chris Lattner36f8e652007-01-27 08:31:04 +00003103 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003104 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003105 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003106 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003107 }
Mike Stump11289f42009-09-09 15:08:12 +00003108
Eugene Zelenko7855e772018-04-03 00:11:50 +00003109 auto *New = new (*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003110 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003111 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003112 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003113 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003114}
3115
John McCall06549462011-01-18 08:40:38 +00003116/// getVariableArrayDecayedType - Turns the given type, which may be
3117/// variably-modified, into the corresponding type with all the known
3118/// sizes replaced with [*].
3119QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3120 // Vastly most common case.
3121 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003122
John McCall06549462011-01-18 08:40:38 +00003123 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003124
John McCall06549462011-01-18 08:40:38 +00003125 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003126 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003127 switch (ty->getTypeClass()) {
3128#define TYPE(Class, Base)
3129#define ABSTRACT_TYPE(Class, Base)
3130#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3131#include "clang/AST/TypeNodes.def"
3132 llvm_unreachable("didn't desugar past all non-canonical types?");
3133
3134 // These types should never be variably-modified.
3135 case Type::Builtin:
3136 case Type::Complex:
3137 case Type::Vector:
Erich Keanef702b022018-07-13 19:46:04 +00003138 case Type::DependentVector:
John McCall06549462011-01-18 08:40:38 +00003139 case Type::ExtVector:
3140 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003141 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003142 case Type::ObjCObject:
3143 case Type::ObjCInterface:
3144 case Type::ObjCObjectPointer:
3145 case Type::Record:
3146 case Type::Enum:
3147 case Type::UnresolvedUsing:
3148 case Type::TypeOfExpr:
3149 case Type::TypeOf:
3150 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003151 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003152 case Type::DependentName:
3153 case Type::InjectedClassName:
3154 case Type::TemplateSpecialization:
3155 case Type::DependentTemplateSpecialization:
3156 case Type::TemplateTypeParm:
3157 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003158 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003159 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003160 case Type::PackExpansion:
3161 llvm_unreachable("type should never be variably-modified");
3162
3163 // These types can be variably-modified but should never need to
3164 // further decay.
3165 case Type::FunctionNoProto:
3166 case Type::FunctionProto:
3167 case Type::BlockPointer:
3168 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003169 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003170 return type;
3171
3172 // These types can be variably-modified. All these modifications
3173 // preserve structure except as noted by comments.
3174 // TODO: if we ever care about optimizing VLAs, there are no-op
3175 // optimizations available here.
3176 case Type::Pointer:
3177 result = getPointerType(getVariableArrayDecayedType(
3178 cast<PointerType>(ty)->getPointeeType()));
3179 break;
3180
3181 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003182 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003183 result = getLValueReferenceType(
3184 getVariableArrayDecayedType(lv->getPointeeType()),
3185 lv->isSpelledAsLValue());
3186 break;
3187 }
3188
3189 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003190 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003191 result = getRValueReferenceType(
3192 getVariableArrayDecayedType(lv->getPointeeType()));
3193 break;
3194 }
3195
Eli Friedman0dfb8892011-10-06 23:00:33 +00003196 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003197 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003198 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3199 break;
3200 }
3201
John McCall06549462011-01-18 08:40:38 +00003202 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003203 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003204 result = getConstantArrayType(
3205 getVariableArrayDecayedType(cat->getElementType()),
3206 cat->getSize(),
3207 cat->getSizeModifier(),
3208 cat->getIndexTypeCVRQualifiers());
3209 break;
3210 }
3211
3212 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003213 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003214 result = getDependentSizedArrayType(
3215 getVariableArrayDecayedType(dat->getElementType()),
3216 dat->getSizeExpr(),
3217 dat->getSizeModifier(),
3218 dat->getIndexTypeCVRQualifiers(),
3219 dat->getBracketsRange());
3220 break;
3221 }
3222
3223 // Turn incomplete types into [*] types.
3224 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003225 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003226 result = getVariableArrayType(
3227 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003228 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003229 ArrayType::Normal,
3230 iat->getIndexTypeCVRQualifiers(),
3231 SourceRange());
3232 break;
3233 }
3234
3235 // Turn VLA types into [*] types.
3236 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003237 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003238 result = getVariableArrayType(
3239 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003240 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003241 ArrayType::Star,
3242 vat->getIndexTypeCVRQualifiers(),
3243 vat->getBracketsRange());
3244 break;
3245 }
3246 }
3247
3248 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003249 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003250}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003251
Steve Naroffcadebd02007-08-30 18:14:25 +00003252/// getVariableArrayType - Returns a non-unique reference to the type for a
3253/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003254QualType ASTContext::getVariableArrayType(QualType EltTy,
3255 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003256 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003257 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003258 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003259 // Since we don't unique expressions, it isn't possible to unique VLA's
3260 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003261 QualType Canon;
Fangrui Song6907ce22018-07-30 19:24:48 +00003262
John McCall33ddac02011-01-19 10:06:00 +00003263 // Be sure to pull qualifiers off the element type.
3264 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3265 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003266 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003267 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003268 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003269 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003270
Eugene Zelenko7855e772018-04-03 00:11:50 +00003271 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003272 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003273
3274 VariableArrayTypes.push_back(New);
3275 Types.push_back(New);
3276 return QualType(New, 0);
3277}
3278
Douglas Gregor4619e432008-12-05 23:32:09 +00003279/// getDependentSizedArrayType - Returns a non-unique reference to
3280/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003281/// type.
John McCall33ddac02011-01-19 10:06:00 +00003282QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3283 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003284 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003285 unsigned elementTypeQuals,
3286 SourceRange brackets) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003287 assert((!numElements || numElements->isTypeDependent() ||
John McCall33ddac02011-01-19 10:06:00 +00003288 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003289 "Size must be type- or value-dependent!");
3290
John McCall33ddac02011-01-19 10:06:00 +00003291 // Dependently-sized array types that do not have a specified number
3292 // of elements will have their sizes deduced from a dependent
3293 // initializer. We do no canonicalization here at all, which is okay
3294 // because they can't be used in most locations.
3295 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003296 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003297 = new (*this, TypeAlignment)
3298 DependentSizedArrayType(*this, elementType, QualType(),
3299 numElements, ASM, elementTypeQuals,
3300 brackets);
3301 Types.push_back(newType);
3302 return QualType(newType, 0);
3303 }
3304
3305 // Otherwise, we actually build a new type every time, but we
3306 // also build a canonical type.
3307
3308 SplitQualType canonElementType = getCanonicalType(elementType).split();
3309
Craig Topper36250ad2014-05-12 05:36:57 +00003310 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003311 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003312 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003313 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003314 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003315
John McCall33ddac02011-01-19 10:06:00 +00003316 // Look for an existing type with these properties.
3317 DependentSizedArrayType *canonTy =
3318 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003319
John McCall33ddac02011-01-19 10:06:00 +00003320 // If we don't have one, build one.
3321 if (!canonTy) {
3322 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003323 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003324 QualType(), numElements, ASM, elementTypeQuals,
3325 brackets);
3326 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3327 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003328 }
3329
John McCall33ddac02011-01-19 10:06:00 +00003330 // Apply qualifiers from the element type to the array.
3331 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003332 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003333
David Majnemer16a74702015-07-24 05:54:19 +00003334 // If we didn't need extra canonicalization for the element type or the size
3335 // expression, then just use that as our result.
3336 if (QualType(canonElementType.Ty, 0) == elementType &&
3337 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003338 return canon;
3339
3340 // Otherwise, we need to build a type which follows the spelling
3341 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003342 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003343 = new (*this, TypeAlignment)
3344 DependentSizedArrayType(*this, elementType, canon, numElements,
3345 ASM, elementTypeQuals, brackets);
3346 Types.push_back(sugaredType);
3347 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003348}
3349
John McCall33ddac02011-01-19 10:06:00 +00003350QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003351 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003352 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003353 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003354 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003355
Craig Topper36250ad2014-05-12 05:36:57 +00003356 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003357 if (IncompleteArrayType *iat =
3358 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3359 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003360
3361 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003362 // either, so fill in the canonical type field. We also have to pull
3363 // qualifiers off the element type.
3364 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003365
John McCall33ddac02011-01-19 10:06:00 +00003366 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3367 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003368 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003369 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003370 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003371
3372 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003373 IncompleteArrayType *existing =
3374 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3375 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003376 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003377
Eugene Zelenko7855e772018-04-03 00:11:50 +00003378 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003379 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003380
John McCall33ddac02011-01-19 10:06:00 +00003381 IncompleteArrayTypes.InsertNode(newType, insertPos);
3382 Types.push_back(newType);
3383 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003384}
3385
Steve Naroff91fcddb2007-07-18 18:00:27 +00003386/// getVectorType - Return the unique reference to a vector type of
3387/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003388QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003389 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003390 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003391
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003392 // Check if we've already instantiated a vector of this type.
3393 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003394 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003395
Craig Topper36250ad2014-05-12 05:36:57 +00003396 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003397 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3398 return QualType(VTP, 0);
3399
3400 // If the element type isn't canonical, this won't be a canonical type either,
3401 // so fill in the canonical type field.
3402 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003403 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003404 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003405
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003406 // Get the new insert position for the node we care about.
3407 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003408 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003409 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003410 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003411 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003412 VectorTypes.InsertNode(New, InsertPos);
3413 Types.push_back(New);
3414 return QualType(New, 0);
3415}
3416
Erich Keanef702b022018-07-13 19:46:04 +00003417QualType
3418ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3419 SourceLocation AttrLoc,
3420 VectorType::VectorKind VecKind) const {
3421 llvm::FoldingSetNodeID ID;
3422 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3423 VecKind);
3424 void *InsertPos = nullptr;
3425 DependentVectorType *Canon =
3426 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3427 DependentVectorType *New;
3428
3429 if (Canon) {
3430 New = new (*this, TypeAlignment) DependentVectorType(
3431 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3432 } else {
3433 QualType CanonVecTy = getCanonicalType(VecType);
3434 if (CanonVecTy == VecType) {
3435 New = new (*this, TypeAlignment) DependentVectorType(
3436 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3437
3438 DependentVectorType *CanonCheck =
3439 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3440 assert(!CanonCheck &&
3441 "Dependent-sized vector_size canonical type broken");
3442 (void)CanonCheck;
3443 DependentVectorTypes.InsertNode(New, InsertPos);
3444 } else {
3445 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3446 SourceLocation());
3447 New = new (*this, TypeAlignment) DependentVectorType(
3448 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3449 }
3450 }
3451
3452 Types.push_back(New);
3453 return QualType(New, 0);
3454}
3455
Nate Begemance4d7fc2008-04-18 23:10:10 +00003456/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003457/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003458QualType
3459ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003460 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003461
Steve Naroff91fcddb2007-07-18 18:00:27 +00003462 // Check if we've already instantiated a vector of this type.
3463 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003464 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003465 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003466 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003467 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3468 return QualType(VTP, 0);
3469
3470 // If the element type isn't canonical, this won't be a canonical type either,
3471 // so fill in the canonical type field.
3472 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003473 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003474 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003475
Steve Naroff91fcddb2007-07-18 18:00:27 +00003476 // Get the new insert position for the node we care about.
3477 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003478 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003479 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003480 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003481 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003482 VectorTypes.InsertNode(New, InsertPos);
3483 Types.push_back(New);
3484 return QualType(New, 0);
3485}
3486
Jay Foad39c79802011-01-12 09:06:06 +00003487QualType
3488ASTContext::getDependentSizedExtVectorType(QualType vecType,
3489 Expr *SizeExpr,
3490 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003491 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003492 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003493 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003494
Craig Topper36250ad2014-05-12 05:36:57 +00003495 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003496 DependentSizedExtVectorType *Canon
3497 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3498 DependentSizedExtVectorType *New;
3499 if (Canon) {
3500 // We already have a canonical version of this array type; use it as
3501 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003502 New = new (*this, TypeAlignment)
3503 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3504 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003505 } else {
3506 QualType CanonVecTy = getCanonicalType(vecType);
3507 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003508 New = new (*this, TypeAlignment)
3509 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3510 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003511
3512 DependentSizedExtVectorType *CanonCheck
3513 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3514 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3515 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003516 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3517 } else {
3518 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3519 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003520 New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003521 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003522 }
3523 }
Mike Stump11289f42009-09-09 15:08:12 +00003524
Douglas Gregor758a8692009-06-17 21:51:59 +00003525 Types.push_back(New);
3526 return QualType(New, 0);
3527}
3528
Fangrui Song6907ce22018-07-30 19:24:48 +00003529QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3530 Expr *AddrSpaceExpr,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003531 SourceLocation AttrLoc) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003532 assert(AddrSpaceExpr->isInstantiationDependent());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003533
3534 QualType canonPointeeType = getCanonicalType(PointeeType);
3535
3536 void *insertPos = nullptr;
3537 llvm::FoldingSetNodeID ID;
3538 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3539 AddrSpaceExpr);
3540
3541 DependentAddressSpaceType *canonTy =
3542 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3543
3544 if (!canonTy) {
3545 canonTy = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003546 DependentAddressSpaceType(*this, canonPointeeType,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003547 QualType(), AddrSpaceExpr, AttrLoc);
3548 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3549 Types.push_back(canonTy);
3550 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003551
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003552 if (canonPointeeType == PointeeType &&
3553 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
Fangrui Song6907ce22018-07-30 19:24:48 +00003554 return QualType(canonTy, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003555
Eugene Zelenko7855e772018-04-03 00:11:50 +00003556 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003557 = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003558 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003559 AddrSpaceExpr, AttrLoc);
3560 Types.push_back(sugaredType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003561 return QualType(sugaredType, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003562}
3563
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003564/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003565static bool isCanonicalResultType(QualType T) {
3566 return T.isCanonical() &&
3567 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3568 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3569}
3570
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003571/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003572QualType
3573ASTContext::getFunctionNoProtoType(QualType ResultTy,
3574 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003575 // Unique functions, to guarantee there is only one function of a particular
3576 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003577 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003578 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003579
Craig Topper36250ad2014-05-12 05:36:57 +00003580 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003581 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003582 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003583 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003584
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003585 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003586 if (!isCanonicalResultType(ResultTy)) {
3587 Canonical =
3588 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003589
Chris Lattner47955de2007-01-27 08:37:20 +00003590 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003591 FunctionNoProtoType *NewIP =
3592 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003593 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003594 }
Mike Stump11289f42009-09-09 15:08:12 +00003595
Eugene Zelenko7855e772018-04-03 00:11:50 +00003596 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003597 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003598 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003599 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003600 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003601}
3602
Douglas Gregora602a152015-10-01 20:20:47 +00003603CanQualType
3604ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3605 CanQualType CanResultType = getCanonicalType(ResultType);
3606
3607 // Canonical result types do not have ARC lifetime qualifiers.
3608 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3609 Qualifiers Qs = CanResultType.getQualifiers();
3610 Qs.removeObjCLifetime();
3611 return CanQualType::CreateUnsafe(
3612 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3613 }
3614
3615 return CanResultType;
3616}
3617
Richard Smith3c4f8d22016-10-16 17:54:23 +00003618static bool isCanonicalExceptionSpecification(
3619 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3620 if (ESI.Type == EST_None)
3621 return true;
3622 if (!NoexceptInType)
3623 return false;
3624
3625 // C++17 onwards: exception specification is part of the type, as a simple
3626 // boolean "can this function type throw".
3627 if (ESI.Type == EST_BasicNoexcept)
3628 return true;
3629
Richard Smitheaf11ad2018-05-03 03:58:32 +00003630 // A noexcept(expr) specification is (possibly) canonical if expr is
3631 // value-dependent.
3632 if (ESI.Type == EST_DependentNoexcept)
3633 return true;
3634
Richard Smith3c4f8d22016-10-16 17:54:23 +00003635 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003636 // expansions (so we can't tell whether it's non-throwing) and all its
3637 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003638 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003639 bool AnyPackExpansions = false;
3640 for (QualType ET : ESI.Exceptions) {
3641 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003642 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003643 if (ET->getAs<PackExpansionType>())
3644 AnyPackExpansions = true;
3645 }
3646 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003647 }
3648
Richard Smith3c4f8d22016-10-16 17:54:23 +00003649 return false;
3650}
3651
Richard Smith304b1242016-10-18 20:13:25 +00003652QualType ASTContext::getFunctionTypeInternal(
3653 QualType ResultTy, ArrayRef<QualType> ArgArray,
3654 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003655 size_t NumArgs = ArgArray.size();
3656
Richard Smith2a2cda52016-10-18 19:29:18 +00003657 // Unique functions, to guarantee there is only one function of a particular
3658 // structure.
3659 llvm::FoldingSetNodeID ID;
3660 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3661 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003662
Richard Smith2a2cda52016-10-18 19:29:18 +00003663 QualType Canonical;
3664 bool Unique = false;
3665
3666 void *InsertPos = nullptr;
3667 if (FunctionProtoType *FPT =
3668 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3669 QualType Existing = QualType(FPT, 0);
3670
3671 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3672 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003673 // noexcept expression, or we're just looking for a canonical type.
3674 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003675 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003676 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003677 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3678 return Existing;
3679
3680 // We need a new type sugar node for this one, to hold the new noexcept
3681 // expression. We do no canonicalization here, but that's OK since we don't
3682 // expect to see the same noexcept expression much more than once.
3683 Canonical = getCanonicalType(Existing);
3684 Unique = true;
3685 }
3686
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003687 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003688 bool IsCanonicalExceptionSpec =
3689 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3690
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003691 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003692 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003693 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003694 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003695 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003696 isCanonical = false;
3697
Richard Smith304b1242016-10-18 20:13:25 +00003698 if (OnlyWantCanonical)
3699 assert(isCanonical &&
3700 "given non-canonical parameters constructing canonical type");
3701
Richard Smith2a2cda52016-10-18 19:29:18 +00003702 // If this type isn't canonical, get the canonical version of it if we don't
3703 // already have it. The exception spec is only partially part of the
3704 // canonical type, and only in C++17 onwards.
3705 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003706 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003707 CanonicalArgs.reserve(NumArgs);
3708 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003709 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003710
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003711 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003712 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003713 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003714
3715 if (IsCanonicalExceptionSpec) {
3716 // Exception spec is already OK.
3717 } else if (NoexceptInType) {
3718 switch (EPI.ExceptionSpec.Type) {
3719 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3720 // We don't know yet. It shouldn't matter what we pick here; no-one
3721 // should ever look at this.
3722 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003723 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003724 CanonicalEPI.ExceptionSpec.Type = EST_None;
3725 break;
3726
Richard Smith2a2cda52016-10-18 19:29:18 +00003727 // A dynamic exception specification is almost always "not noexcept",
3728 // with the exception that a pack expansion might expand to no types.
3729 case EST_Dynamic: {
3730 bool AnyPacks = false;
3731 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3732 if (ET->getAs<PackExpansionType>())
3733 AnyPacks = true;
3734 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3735 }
3736 if (!AnyPacks)
3737 CanonicalEPI.ExceptionSpec.Type = EST_None;
3738 else {
3739 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3740 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3741 }
3742 break;
3743 }
3744
Richard Smitheaf11ad2018-05-03 03:58:32 +00003745 case EST_DynamicNone: case EST_BasicNoexcept: case EST_NoexceptTrue:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003746 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3747 break;
3748
Richard Smitheaf11ad2018-05-03 03:58:32 +00003749 case EST_DependentNoexcept:
3750 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003751 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003752 } else {
3753 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3754 }
John McCalldb40c7f2010-12-14 08:05:40 +00003755
Douglas Gregora602a152015-10-01 20:20:47 +00003756 // Adjust the canonical function result type.
3757 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003758 Canonical =
3759 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003760
Chris Lattnerfd4de792007-01-27 01:15:32 +00003761 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003762 FunctionProtoType *NewIP =
3763 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003764 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003765 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003766
Bruno Ricci26a25362018-10-02 11:46:38 +00003767 // Compute the needed size to hold this FunctionProtoType and the
3768 // various trailing objects.
3769 auto ESH = FunctionProtoType::getExceptionSpecSize(
3770 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3771 size_t Size = FunctionProtoType::totalSizeToAlloc<
3772 QualType, FunctionType::FunctionTypeExtraBitfields,
3773 FunctionType::ExceptionType, Expr *, FunctionDecl *,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003774 FunctionProtoType::ExtParameterInfo, Qualifiers>(
Bruno Ricci26a25362018-10-02 11:46:38 +00003775 NumArgs, FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
3776 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003777 EPI.ExtParameterInfos ? NumArgs : 0,
3778 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
John McCall18afab72016-03-01 00:49:02 +00003779
Bruno Ricci26a25362018-10-02 11:46:38 +00003780 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003781 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003782 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003783 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003784 if (!Unique)
3785 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003786 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003787}
Chris Lattneref51c202006-11-10 07:17:23 +00003788
Joey Goulye3c85de2016-12-01 11:30:49 +00003789QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003790 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003791 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003792
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003793 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003794 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003795 return QualType(PT, 0);
3796
3797 // If the pipe element type isn't canonical, this won't be a canonical type
3798 // either, so fill in the canonical type field.
3799 QualType Canonical;
3800 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003801 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003802
3803 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003804 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003805 assert(!NewIP && "Shouldn't be in the map!");
3806 (void)NewIP;
3807 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003808 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003809 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003810 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003811 return QualType(New, 0);
3812}
3813
Anastasia Stulova59055b92018-05-09 13:23:26 +00003814QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3815 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3816 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3817 : Ty;
3818}
3819
Joey Goulye3c85de2016-12-01 11:30:49 +00003820QualType ASTContext::getReadPipeType(QualType T) const {
3821 return getPipeType(T, true);
3822}
3823
Joey Gouly5788b782016-11-18 14:10:54 +00003824QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003825 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003826}
3827
John McCalle78aac42010-03-10 03:28:59 +00003828#ifndef NDEBUG
3829static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3830 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003831 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003832 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3833 return true;
3834 if (RD->getDescribedClassTemplate() &&
3835 !isa<ClassTemplateSpecializationDecl>(RD))
3836 return true;
3837 return false;
3838}
3839#endif
3840
3841/// getInjectedClassNameType - Return the unique reference to the
3842/// injected class name type for the specified templated declaration.
3843QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003844 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003845 assert(NeedsInjectedClassNameType(Decl));
3846 if (Decl->TypeForDecl) {
3847 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003848 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003849 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3850 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3851 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3852 } else {
John McCall424cec92011-01-19 06:33:43 +00003853 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003854 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003855 Decl->TypeForDecl = newType;
3856 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003857 }
3858 return QualType(Decl->TypeForDecl, 0);
3859}
3860
Douglas Gregor83a586e2008-04-13 21:07:44 +00003861/// getTypeDeclType - Return the unique reference to the type for the
3862/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003863QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003864 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003865 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003866
Eugene Zelenko7855e772018-04-03 00:11:50 +00003867 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003868 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003869
John McCall96f0b5f2010-03-10 06:48:02 +00003870 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3871 "Template type parameter types are always available.");
3872
Eugene Zelenko7855e772018-04-03 00:11:50 +00003873 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003874 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003875 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003876 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003877 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003878 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003879 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003880 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003881 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3882 Decl->TypeForDecl = newType;
3883 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003884 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003885 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003886
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003887 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003888}
3889
Chris Lattner32d920b2007-01-26 02:01:53 +00003890/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003891/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003892QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003893ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3894 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003895 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003896
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003897 if (Canonical.isNull())
3898 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00003899 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003900 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003901 Decl->TypeForDecl = newType;
3902 Types.push_back(newType);
3903 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003904}
3905
Jay Foad39c79802011-01-12 09:06:06 +00003906QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003907 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3908
Douglas Gregorec9fd132012-01-14 16:38:05 +00003909 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003910 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003911 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003912
Eugene Zelenko7855e772018-04-03 00:11:50 +00003913 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003914 Decl->TypeForDecl = newType;
3915 Types.push_back(newType);
3916 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003917}
3918
Jay Foad39c79802011-01-12 09:06:06 +00003919QualType ASTContext::getEnumType(const EnumDecl *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 EnumDecl *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) EnumType(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
Richard Smithe43e2b32018-08-20 21:47:29 +00003932QualType ASTContext::getAttributedType(attr::Kind attrKind,
John McCall81904512011-01-06 01:58:22 +00003933 QualType modifiedType,
3934 QualType equivalentType) {
3935 llvm::FoldingSetNodeID id;
3936 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3937
Craig Topper36250ad2014-05-12 05:36:57 +00003938 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003939 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3940 if (type) return QualType(type, 0);
3941
3942 QualType canon = getCanonicalType(equivalentType);
3943 type = new (*this, TypeAlignment)
Leonard Chanc72aaf62019-05-07 03:20:17 +00003944 AttributedType(canon, attrKind, modifiedType, equivalentType);
John McCall81904512011-01-06 01:58:22 +00003945
3946 Types.push_back(type);
3947 AttributedTypes.InsertNode(type, insertPos);
3948
3949 return QualType(type, 0);
3950}
3951
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003952/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00003953QualType
3954ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003955 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003956 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003957 && "replacement types must always be canonical");
3958
3959 llvm::FoldingSetNodeID ID;
3960 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003961 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003962 SubstTemplateTypeParmType *SubstParm
3963 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3964
3965 if (!SubstParm) {
3966 SubstParm = new (*this, TypeAlignment)
3967 SubstTemplateTypeParmType(Parm, Replacement);
3968 Types.push_back(SubstParm);
3969 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3970 }
3971
3972 return QualType(SubstParm, 0);
3973}
3974
Fangrui Song6907ce22018-07-30 19:24:48 +00003975/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00003976QualType ASTContext::getSubstTemplateTypeParmPackType(
3977 const TemplateTypeParmType *Parm,
3978 const TemplateArgument &ArgPack) {
3979#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003980 for (const auto &P : ArgPack.pack_elements()) {
3981 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3982 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003983 }
3984#endif
Fangrui Song6907ce22018-07-30 19:24:48 +00003985
Douglas Gregorada4b792011-01-14 02:55:32 +00003986 llvm::FoldingSetNodeID ID;
3987 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003988 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003989 if (SubstTemplateTypeParmPackType *SubstParm
3990 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3991 return QualType(SubstParm, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00003992
Douglas Gregorada4b792011-01-14 02:55:32 +00003993 QualType Canon;
3994 if (!Parm->isCanonicalUnqualified()) {
3995 Canon = getCanonicalType(QualType(Parm, 0));
3996 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3997 ArgPack);
3998 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3999 }
4000
Eugene Zelenko7855e772018-04-03 00:11:50 +00004001 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00004002 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4003 ArgPack);
4004 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00004005 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00004006 return QualType(SubstParm, 0);
Douglas Gregorada4b792011-01-14 02:55:32 +00004007}
4008
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004009/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00004010/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00004011/// name.
Mike Stump11289f42009-09-09 15:08:12 +00004012QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00004013 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00004014 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00004015 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00004016 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00004017 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004018 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00004019 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4020
4021 if (TypeParm)
4022 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004023
Chandler Carruth08836322011-05-01 00:51:33 +00004024 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00004025 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00004026 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004027
Fangrui Song6907ce22018-07-30 19:24:48 +00004028 TemplateTypeParmType *TypeCheck
Douglas Gregorc42075a2010-02-04 18:10:26 +00004029 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4030 assert(!TypeCheck && "Template type parameter canonical type broken");
4031 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00004032 } else
John McCall90d1c2d2009-09-24 23:30:46 +00004033 TypeParm = new (*this, TypeAlignment)
4034 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00004035
4036 Types.push_back(TypeParm);
4037 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4038
4039 return QualType(TypeParm, 0);
4040}
4041
John McCalle78aac42010-03-10 03:28:59 +00004042TypeSourceInfo *
4043ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4044 SourceLocation NameLoc,
4045 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004046 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004047 assert(!Name.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004048 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004049 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00004050
4051 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00004052 TemplateSpecializationTypeLoc TL =
4053 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00004054 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00004055 TL.setTemplateNameLoc(NameLoc);
4056 TL.setLAngleLoc(Args.getLAngleLoc());
4057 TL.setRAngleLoc(Args.getRAngleLoc());
4058 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4059 TL.setArgLocInfo(i, Args[i].getLocInfo());
4060 return DI;
4061}
4062
Mike Stump11289f42009-09-09 15:08:12 +00004063QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00004064ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00004065 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004066 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004067 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004068 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00004069
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004070 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004071 ArgVec.reserve(Args.size());
4072 for (const TemplateArgumentLoc &Arg : Args.arguments())
4073 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00004074
David Majnemer6fbeee32016-07-07 04:43:07 +00004075 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00004076}
4077
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004078#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00004079static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4080 for (const TemplateArgument &Arg : Args)
4081 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004082 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004083
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004084 return true;
4085}
4086#endif
4087
John McCall0ad16662009-10-29 08:12:44 +00004088QualType
4089ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00004090 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004091 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004092 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004093 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00004094 // Look through qualified template names.
4095 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4096 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004097
4098 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00004099 Template.getAsTemplateDecl() &&
4100 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004101 QualType CanonType;
4102 if (!Underlying.isNull())
4103 CanonType = getCanonicalType(Underlying);
4104 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004105 // We can get here with an alias template when the specialization contains
4106 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00004107 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004108 "Caller must compute aliased type");
4109 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004110 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00004111 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00004112
Douglas Gregora8e02e72009-07-28 23:00:59 +00004113 // Allocate the (non-canonical) template specialization type, but don't
4114 // try to unique it: these types typically have location information that
4115 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004116 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00004117 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004118 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00004119 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004120 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00004121 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004122 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00004123
Douglas Gregor8bf42052009-02-09 18:46:07 +00004124 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00004125 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00004126}
4127
David Majnemer6fbeee32016-07-07 04:43:07 +00004128QualType ASTContext::getCanonicalTemplateSpecializationType(
4129 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004130 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004131 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004132
Douglas Gregore29139c2011-03-03 17:04:51 +00004133 // Look through qualified template names.
4134 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4135 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004136
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004137 // Build the canonical template specialization type.
4138 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004139 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004140 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004141 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004142 for (const TemplateArgument &Arg : Args)
4143 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004144
4145 // Determine whether this canonical template specialization type already
4146 // exists.
4147 llvm::FoldingSetNodeID ID;
4148 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004149 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004150
Craig Topper36250ad2014-05-12 05:36:57 +00004151 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004152 TemplateSpecializationType *Spec
4153 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4154
4155 if (!Spec) {
4156 // Allocate a new canonical template specialization type.
4157 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4158 sizeof(TemplateArgument) * NumArgs),
4159 TypeAlignment);
4160 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004161 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004162 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004163 Types.push_back(Spec);
4164 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4165 }
4166
4167 assert(Spec->isDependentType() &&
4168 "Non-dependent template-id type must have a canonical type");
4169 return QualType(Spec, 0);
4170}
4171
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004172QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4173 NestedNameSpecifier *NNS,
4174 QualType NamedType,
4175 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004176 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004177 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004178
Craig Topper36250ad2014-05-12 05:36:57 +00004179 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004180 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004181 if (T)
4182 return QualType(T, 0);
4183
Douglas Gregorc42075a2010-02-04 18:10:26 +00004184 QualType Canon = NamedType;
4185 if (!Canon.isCanonical()) {
4186 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004187 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4188 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004189 (void)CheckT;
4190 }
4191
Bruno Riccid6bd5982018-08-16 10:48:16 +00004192 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4193 TypeAlignment);
4194 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4195
Douglas Gregor52537682009-03-19 00:18:19 +00004196 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004197 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004198 return QualType(T, 0);
4199}
4200
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004201QualType
Jay Foad39c79802011-01-12 09:06:06 +00004202ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004203 llvm::FoldingSetNodeID ID;
4204 ParenType::Profile(ID, InnerType);
4205
Craig Topper36250ad2014-05-12 05:36:57 +00004206 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004207 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4208 if (T)
4209 return QualType(T, 0);
4210
4211 QualType Canon = InnerType;
4212 if (!Canon.isCanonical()) {
4213 Canon = getCanonicalType(InnerType);
4214 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4215 assert(!CheckT && "Paren canonical type broken");
4216 (void)CheckT;
4217 }
4218
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004219 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004220 Types.push_back(T);
4221 ParenTypes.InsertNode(T, InsertPos);
4222 return QualType(T, 0);
4223}
4224
Leonard Chanc72aaf62019-05-07 03:20:17 +00004225QualType
4226ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4227 const IdentifierInfo *MacroII) const {
4228 QualType Canon = UnderlyingTy;
4229 if (!Canon.isCanonical())
4230 Canon = getCanonicalType(UnderlyingTy);
4231
4232 auto *newType = new (*this, TypeAlignment)
4233 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4234 Types.push_back(newType);
4235 return QualType(newType, 0);
4236}
4237
Douglas Gregor02085352010-03-31 20:19:30 +00004238QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4239 NestedNameSpecifier *NNS,
4240 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004241 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004242 if (Canon.isNull()) {
4243 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004244 if (CanonNNS != NNS)
4245 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004246 }
4247
4248 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004249 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004250
Craig Topper36250ad2014-05-12 05:36:57 +00004251 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004252 DependentNameType *T
4253 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004254 if (T)
4255 return QualType(T, 0);
4256
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004257 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004258 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004259 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004260 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004261}
4262
Mike Stump11289f42009-09-09 15:08:12 +00004263QualType
John McCallc392f372010-06-11 00:33:02 +00004264ASTContext::getDependentTemplateSpecializationType(
4265 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004266 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004267 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004268 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004269 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004270 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004271 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4272 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004273 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004274}
4275
4276QualType
4277ASTContext::getDependentTemplateSpecializationType(
4278 ElaboratedTypeKeyword Keyword,
4279 NestedNameSpecifier *NNS,
4280 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004281 ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004282 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor6e068012011-02-28 00:04:36 +00004283 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004284
Douglas Gregorc42075a2010-02-04 18:10:26 +00004285 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004286 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004287 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004288
Craig Topper36250ad2014-05-12 05:36:57 +00004289 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004290 DependentTemplateSpecializationType *T
4291 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004292 if (T)
4293 return QualType(T, 0);
4294
John McCallc392f372010-06-11 00:33:02 +00004295 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004296
John McCallc392f372010-06-11 00:33:02 +00004297 ElaboratedTypeKeyword CanonKeyword = Keyword;
4298 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4299
4300 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004301 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004302 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004303 for (unsigned I = 0; I != NumArgs; ++I) {
4304 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4305 if (!CanonArgs[I].structurallyEquals(Args[I]))
4306 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004307 }
4308
John McCallc392f372010-06-11 00:33:02 +00004309 QualType Canon;
4310 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4311 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004312 Name,
4313 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004314
4315 // Find the insert position again.
4316 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4317 }
4318
4319 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4320 sizeof(TemplateArgument) * NumArgs),
4321 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004322 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004323 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004324 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004325 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004326 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004327}
4328
Richard Smith32918772017-02-14 00:25:28 +00004329TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4330 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004331 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004332 QualType ArgType = getTypeDeclType(TTP);
4333 if (TTP->isParameterPack())
4334 ArgType = getPackExpansionType(ArgType, None);
4335
4336 Arg = TemplateArgument(ArgType);
4337 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4338 Expr *E = new (*this) DeclRefExpr(
Bruno Ricci5fc4db72018-12-21 14:10:18 +00004339 *this, NTTP, /*enclosing*/ false,
Richard Smith32918772017-02-14 00:25:28 +00004340 NTTP->getType().getNonLValueExprType(*this),
4341 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4342
4343 if (NTTP->isParameterPack())
4344 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4345 None);
4346 Arg = TemplateArgument(E);
4347 } else {
4348 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4349 if (TTP->isParameterPack())
4350 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4351 else
4352 Arg = TemplateArgument(TemplateName(TTP));
4353 }
4354
4355 if (Param->isTemplateParameterPack())
4356 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4357
4358 return Arg;
4359}
4360
Richard Smith43e14d22016-12-23 02:10:11 +00004361void
4362ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4363 SmallVectorImpl<TemplateArgument> &Args) {
4364 Args.reserve(Args.size() + Params->size());
4365
Richard Smith32918772017-02-14 00:25:28 +00004366 for (NamedDecl *Param : *Params)
4367 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004368}
4369
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004370QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004371 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004372 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004373 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004374
4375 assert(Pattern->containsUnexpandedParameterPack() &&
4376 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004377 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004378 PackExpansionType *T
4379 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4380 if (T)
4381 return QualType(T, 0);
4382
4383 QualType Canon;
4384 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004385 Canon = getCanonicalType(Pattern);
4386 // The canonical type might not contain an unexpanded parameter pack, if it
4387 // contains an alias template specialization which ignores one of its
4388 // parameters.
4389 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004390 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004391
Richard Smith68eea502012-07-16 00:20:35 +00004392 // Find the insert position again, in case we inserted an element into
4393 // PackExpansionTypes and invalidated our insert position.
4394 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4395 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004396 }
4397
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004398 T = new (*this, TypeAlignment)
4399 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004400 Types.push_back(T);
4401 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004402 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004403}
4404
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004405/// CmpProtocolNames - Comparison predicate for sorting protocols
4406/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004407static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4408 ObjCProtocolDecl *const *RHS) {
4409 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004410}
4411
Craig Topper1f26d5b2016-01-03 19:43:23 +00004412static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4413 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004414
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004415 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4416 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004417
Craig Topper1f26d5b2016-01-03 19:43:23 +00004418 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004419 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004420 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004421 return false;
4422 return true;
4423}
4424
Craig Topper6a8c1512015-10-22 01:56:18 +00004425static void
4426SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004427 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004428 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004429
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004430 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004431 for (ObjCProtocolDecl *&P : Protocols)
4432 P = P->getCanonicalDecl();
4433
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004434 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004435 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4436 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004437}
4438
John McCall8b07ec22010-05-15 11:32:37 +00004439QualType ASTContext::getObjCObjectType(QualType BaseType,
4440 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004441 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004442 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004443 llvm::makeArrayRef(Protocols, NumProtocols),
4444 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004445}
4446
4447QualType ASTContext::getObjCObjectType(
4448 QualType baseType,
4449 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004450 ArrayRef<ObjCProtocolDecl *> protocols,
4451 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004452 // If the base type is an interface and there aren't any protocols or
4453 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004454 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4455 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004456 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004457
4458 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004459 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004460 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004461 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004462 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4463 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004464
Douglas Gregore9d95f12015-07-07 03:57:35 +00004465 // Determine the type arguments to be used for canonicalization,
4466 // which may be explicitly specified here or written on the base
4467 // type.
4468 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4469 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004470 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004471 effectiveTypeArgs = baseObject->getTypeArgs();
4472 }
John McCallfc93cf92009-10-22 22:37:11 +00004473
Douglas Gregore9d95f12015-07-07 03:57:35 +00004474 // Build the canonical type, which has the canonical base type and a
4475 // sorted-and-uniqued list of protocols and the type arguments
4476 // canonicalized.
4477 QualType canonical;
4478 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4479 effectiveTypeArgs.end(),
4480 [&](QualType type) {
4481 return type.isCanonical();
4482 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004483 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004484 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4485 // Determine the canonical type arguments.
4486 ArrayRef<QualType> canonTypeArgs;
4487 SmallVector<QualType, 4> canonTypeArgsVec;
4488 if (!typeArgsAreCanonical) {
4489 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4490 for (auto typeArg : effectiveTypeArgs)
4491 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4492 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004493 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004494 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004495 }
4496
Douglas Gregore9d95f12015-07-07 03:57:35 +00004497 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4498 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4499 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004500 canonProtocolsVec.append(protocols.begin(), protocols.end());
4501 SortAndUniqueProtocols(canonProtocolsVec);
4502 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004503 } else {
4504 canonProtocols = protocols;
4505 }
4506
4507 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004508 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004509
John McCallfc93cf92009-10-22 22:37:11 +00004510 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004511 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4512 }
4513
Douglas Gregore9d95f12015-07-07 03:57:35 +00004514 unsigned size = sizeof(ObjCObjectTypeImpl);
4515 size += typeArgs.size() * sizeof(QualType);
4516 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4517 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004518 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004519 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4520 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004521
4522 Types.push_back(T);
4523 ObjCObjectTypes.InsertNode(T, InsertPos);
4524 return QualType(T, 0);
4525}
4526
Manman Ren3569eb52016-09-13 17:03:12 +00004527/// Apply Objective-C protocol qualifiers to the given type.
4528/// If this is for the canonical type of a type parameter, we can apply
4529/// protocol qualifiers on the ObjCObjectPointerType.
4530QualType
4531ASTContext::applyObjCProtocolQualifiers(QualType type,
4532 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4533 bool allowOnPointerType) const {
4534 hasError = false;
4535
Eugene Zelenko7855e772018-04-03 00:11:50 +00004536 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004537 return getObjCTypeParamType(objT->getDecl(), protocols);
4538 }
4539
Manman Ren3569eb52016-09-13 17:03:12 +00004540 // Apply protocol qualifiers to ObjCObjectPointerType.
4541 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004542 if (const auto *objPtr =
4543 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004544 const ObjCObjectType *objT = objPtr->getObjectType();
4545 // Merge protocol lists and construct ObjCObjectType.
4546 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4547 protocolsVec.append(objT->qual_begin(),
4548 objT->qual_end());
4549 protocolsVec.append(protocols.begin(), protocols.end());
4550 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4551 type = getObjCObjectType(
4552 objT->getBaseType(),
4553 objT->getTypeArgsAsWritten(),
4554 protocols,
4555 objT->isKindOfTypeAsWritten());
4556 return getObjCObjectPointerType(type);
4557 }
4558 }
4559
4560 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004561 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004562 // FIXME: Check for protocols to which the class type is already
4563 // known to conform.
4564
4565 return getObjCObjectType(objT->getBaseType(),
4566 objT->getTypeArgsAsWritten(),
4567 protocols,
4568 objT->isKindOfTypeAsWritten());
4569 }
4570
4571 // If the canonical type is ObjCObjectType, ...
4572 if (type->isObjCObjectType()) {
4573 // Silently overwrite any existing protocol qualifiers.
4574 // TODO: determine whether that's the right thing to do.
4575
4576 // FIXME: Check for protocols to which the class type is already
4577 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004578 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004579 }
4580
4581 // id<protocol-list>
4582 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004583 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004584 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004585 objPtr->isKindOfType());
4586 return getObjCObjectPointerType(type);
4587 }
4588
4589 // Class<protocol-list>
4590 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004591 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004592 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004593 objPtr->isKindOfType());
4594 return getObjCObjectPointerType(type);
4595 }
4596
4597 hasError = true;
4598 return type;
4599}
4600
Manman Rene6be26c2016-09-13 17:25:08 +00004601QualType
4602ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4603 ArrayRef<ObjCProtocolDecl *> protocols,
4604 QualType Canonical) const {
4605 // Look in the folding set for an existing type.
4606 llvm::FoldingSetNodeID ID;
4607 ObjCTypeParamType::Profile(ID, Decl, protocols);
4608 void *InsertPos = nullptr;
4609 if (ObjCTypeParamType *TypeParam =
4610 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4611 return QualType(TypeParam, 0);
4612
4613 if (Canonical.isNull()) {
4614 // We canonicalize to the underlying type.
4615 Canonical = getCanonicalType(Decl->getUnderlyingType());
4616 if (!protocols.empty()) {
4617 // Apply the protocol qualifers.
4618 bool hasError;
Richard Trieua986a312018-08-30 01:57:52 +00004619 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4620 Canonical, protocols, hasError, true /*allowOnPointerType*/));
Manman Rene6be26c2016-09-13 17:25:08 +00004621 assert(!hasError && "Error when apply protocol qualifier to bound type");
4622 }
4623 }
4624
4625 unsigned size = sizeof(ObjCTypeParamType);
4626 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4627 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004628 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004629
4630 Types.push_back(newType);
4631 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4632 return QualType(newType, 0);
4633}
4634
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004635/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4636/// protocol list adopt all protocols in QT's qualified-id protocol
4637/// list.
4638bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4639 ObjCInterfaceDecl *IC) {
4640 if (!QT->isObjCQualifiedIdType())
4641 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004642
Eugene Zelenko7855e772018-04-03 00:11:50 +00004643 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004644 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004645 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004646 if (!IC->ClassImplementsProtocol(Proto, false))
4647 return false;
4648 }
4649 return true;
4650 }
4651 return false;
4652}
4653
4654/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4655/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4656/// of protocols.
4657bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4658 ObjCInterfaceDecl *IDecl) {
4659 if (!QT->isObjCQualifiedIdType())
4660 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004661 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004662 if (!OPT)
4663 return false;
4664 if (!IDecl->hasDefinition())
4665 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004666 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4667 CollectInheritedProtocols(IDecl, InheritedProtocols);
4668 if (InheritedProtocols.empty())
4669 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004670 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004671 // of IDecl's, then bridge casting is ok.
4672 bool Conforms = false;
4673 for (auto *Proto : OPT->quals()) {
4674 Conforms = false;
4675 for (auto *PI : InheritedProtocols) {
4676 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4677 Conforms = true;
4678 break;
4679 }
4680 }
4681 if (!Conforms)
4682 break;
4683 }
4684 if (Conforms)
4685 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004686
Aaron Ballman83731462014-03-17 16:14:00 +00004687 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004688 // If both the right and left sides have qualifiers.
4689 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004690 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004691 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004692 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004693 break;
4694 }
4695 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004696 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004697 }
4698 return true;
4699}
4700
John McCall8b07ec22010-05-15 11:32:37 +00004701/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4702/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004703QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004704 llvm::FoldingSetNodeID ID;
4705 ObjCObjectPointerType::Profile(ID, ObjectT);
4706
Craig Topper36250ad2014-05-12 05:36:57 +00004707 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004708 if (ObjCObjectPointerType *QT =
4709 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4710 return QualType(QT, 0);
4711
4712 // Find the canonical object type.
4713 QualType Canonical;
4714 if (!ObjectT.isCanonical()) {
4715 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4716
4717 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004718 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4719 }
4720
Douglas Gregorf85bee62010-02-08 22:59:26 +00004721 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004722 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004723 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004724 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004725
Steve Narofffb4330f2009-06-17 22:40:22 +00004726 Types.push_back(QType);
4727 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004728 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004729}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004730
Douglas Gregor1c283312010-08-11 12:19:30 +00004731/// getObjCInterfaceType - Return the unique reference to the type for the
4732/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004733QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4734 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004735 if (Decl->TypeForDecl)
4736 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004737
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004738 if (PrevDecl) {
4739 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4740 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4741 return QualType(PrevDecl->TypeForDecl, 0);
4742 }
4743
Douglas Gregor7671e532011-12-16 16:34:57 +00004744 // Prefer the definition, if there is one.
4745 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4746 Decl = Def;
Fangrui Song6907ce22018-07-30 19:24:48 +00004747
Douglas Gregor1c283312010-08-11 12:19:30 +00004748 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004749 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004750 Decl->TypeForDecl = T;
4751 Types.push_back(T);
4752 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004753}
4754
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004755/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4756/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004757/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004758/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004759/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004760QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004761 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004762 if (tofExpr->isTypeDependent()) {
4763 llvm::FoldingSetNodeID ID;
4764 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004765
Craig Topper36250ad2014-05-12 05:36:57 +00004766 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004767 DependentTypeOfExprType *Canon
4768 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4769 if (Canon) {
4770 // We already have a "canonical" version of an identical, dependent
4771 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004772 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004773 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004774 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004775 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004776 Canon
4777 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004778 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4779 toe = Canon;
4780 }
4781 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004782 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004783 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004784 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004785 Types.push_back(toe);
4786 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004787}
4788
Steve Naroffa773cd52007-08-01 18:02:17 +00004789/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004790/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004791/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004792/// an issue. This doesn't affect the type checker, since it operates
4793/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004794QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004795 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004796 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004797 Types.push_back(tot);
4798 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004799}
4800
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004801/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004802/// nodes. This would never be helpful, since each such type has its own
4803/// expression, and would not give a significant memory saving, since there
4804/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004805QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004806 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004807
4808 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004809 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004810 // unique dependent type. Two such decltype-specifiers refer to the same
4811 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004812 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004813 llvm::FoldingSetNodeID ID;
4814 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004815
Craig Topper36250ad2014-05-12 05:36:57 +00004816 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004817 DependentDecltypeType *Canon
4818 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004819 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004820 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004821 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004822 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004823 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004824 dt = new (*this, TypeAlignment)
4825 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004826 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004827 dt = new (*this, TypeAlignment)
4828 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004829 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004830 Types.push_back(dt);
4831 return QualType(dt, 0);
4832}
4833
Alexis Hunte852b102011-05-24 22:41:36 +00004834/// getUnaryTransformationType - We don't unique these, since the memory
4835/// savings are minimal and these are rare.
4836QualType ASTContext::getUnaryTransformType(QualType BaseType,
4837 QualType UnderlyingType,
4838 UnaryTransformType::UTTKind Kind)
4839 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004840 UnaryTransformType *ut = nullptr;
4841
4842 if (BaseType->isDependentType()) {
4843 // Look in the folding set for an existing type.
4844 llvm::FoldingSetNodeID ID;
4845 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4846
4847 void *InsertPos = nullptr;
4848 DependentUnaryTransformType *Canon
4849 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4850
4851 if (!Canon) {
4852 // Build a new, canonical __underlying_type(type) type.
4853 Canon = new (*this, TypeAlignment)
4854 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4855 Kind);
4856 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4857 }
4858 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4859 QualType(), Kind,
4860 QualType(Canon, 0));
4861 } else {
4862 QualType CanonType = getCanonicalType(UnderlyingType);
4863 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4864 UnderlyingType, Kind,
4865 CanonType);
4866 }
4867 Types.push_back(ut);
4868 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004869}
4870
Richard Smith2a7d4812013-05-04 07:00:32 +00004871/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4872/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4873/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004874QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004875 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004876 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004877 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004878
Richard Smith2a7d4812013-05-04 07:00:32 +00004879 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004880 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004881 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004882 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004883 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4884 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004885
Eugene Zelenko7855e772018-04-03 00:11:50 +00004886 auto *AT = new (*this, TypeAlignment)
4887 AutoType(DeducedType, Keyword, IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004888 Types.push_back(AT);
4889 if (InsertPos)
4890 AutoTypes.InsertNode(AT, InsertPos);
4891 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004892}
4893
Richard Smith600b5262017-01-26 20:40:47 +00004894/// Return the uniqued reference to the deduced template specialization type
4895/// which has been deduced to the given type, or to the canonical undeduced
4896/// such type, or the canonical deduced-but-dependent such type.
4897QualType ASTContext::getDeducedTemplateSpecializationType(
4898 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4899 // Look in the folding set for an existing type.
4900 void *InsertPos = nullptr;
4901 llvm::FoldingSetNodeID ID;
4902 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4903 IsDependent);
4904 if (DeducedTemplateSpecializationType *DTST =
4905 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4906 return QualType(DTST, 0);
4907
Eugene Zelenko7855e772018-04-03 00:11:50 +00004908 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00004909 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4910 Types.push_back(DTST);
4911 if (InsertPos)
4912 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4913 return QualType(DTST, 0);
4914}
4915
Eli Friedman0dfb8892011-10-06 23:00:33 +00004916/// getAtomicType - Return the uniqued reference to the atomic type for
4917/// the given value type.
4918QualType ASTContext::getAtomicType(QualType T) const {
4919 // Unique pointers, to guarantee there is only one pointer of a particular
4920 // structure.
4921 llvm::FoldingSetNodeID ID;
4922 AtomicType::Profile(ID, T);
4923
Craig Topper36250ad2014-05-12 05:36:57 +00004924 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004925 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4926 return QualType(AT, 0);
4927
4928 // If the atomic value type isn't canonical, this won't be a canonical type
4929 // either, so fill in the canonical type field.
4930 QualType Canonical;
4931 if (!T.isCanonical()) {
4932 Canonical = getAtomicType(getCanonicalType(T));
4933
4934 // Get the new insert position for the node we care about.
4935 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004936 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004937 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00004938 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00004939 Types.push_back(New);
4940 AtomicTypes.InsertNode(New, InsertPos);
4941 return QualType(New, 0);
4942}
4943
Richard Smith02e85f32011-04-14 22:09:26 +00004944/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4945QualType ASTContext::getAutoDeductType() const {
4946 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004947 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004948 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004949 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004950 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004951 return AutoDeductTy;
4952}
4953
4954/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4955QualType ASTContext::getAutoRRefDeductType() const {
4956 if (AutoRRefDeductTy.isNull())
4957 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4958 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4959 return AutoRRefDeductTy;
4960}
4961
Chris Lattnerfb072462007-01-23 05:45:31 +00004962/// getTagDeclType - Return the unique reference to the type for the
4963/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004964QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004965 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004966 // FIXME: What is the design on getTagDeclType when it requires casting
4967 // away const? mutable?
4968 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004969}
4970
Mike Stump11289f42009-09-09 15:08:12 +00004971/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4972/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4973/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004974CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004975 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004976}
Chris Lattnerfb072462007-01-23 05:45:31 +00004977
Fangrui Song6907ce22018-07-30 19:24:48 +00004978/// Return the unique signed counterpart of the integer type
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004979/// corresponding to size_t.
4980CanQualType ASTContext::getSignedSizeType() const {
4981 return getFromTargetType(Target->getSignedSizeType());
4982}
4983
Hans Wennborg27541db2011-10-27 08:29:09 +00004984/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4985CanQualType ASTContext::getIntMaxType() const {
4986 return getFromTargetType(Target->getIntMaxType());
4987}
4988
4989/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4990CanQualType ASTContext::getUIntMaxType() const {
4991 return getFromTargetType(Target->getUIntMaxType());
4992}
4993
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004994/// getSignedWCharType - Return the type of "signed wchar_t".
4995/// Used when in C++, as a GCC extension.
4996QualType ASTContext::getSignedWCharType() const {
4997 // FIXME: derive from "Target" ?
4998 return WCharTy;
4999}
5000
5001/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5002/// Used when in C++, as a GCC extension.
5003QualType ASTContext::getUnsignedWCharType() const {
5004 // FIXME: derive from "Target" ?
5005 return UnsignedIntTy;
5006}
5007
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00005008QualType ASTContext::getIntPtrType() const {
5009 return getFromTargetType(Target->getIntPtrType());
5010}
5011
5012QualType ASTContext::getUIntPtrType() const {
5013 return getCorrespondingUnsignedType(getIntPtrType());
5014}
5015
Hans Wennborg27541db2011-10-27 08:29:09 +00005016/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005017/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5018QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005019 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005020}
5021
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005022/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00005023/// integer type. The standard (C11 7.21.6.1p7) refers to this type
5024/// in the definition of %tu format specifier.
5025QualType ASTContext::getUnsignedPointerDiffType() const {
5026 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5027}
5028
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005029/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00005030/// <sys/types.h>. We need this to compute the correct type for vfork().
5031QualType ASTContext::getProcessIDType() const {
5032 return getFromTargetType(Target->getProcessIDType());
5033}
5034
Chris Lattnera21ad802008-04-02 05:18:44 +00005035//===----------------------------------------------------------------------===//
5036// Type Operators
5037//===----------------------------------------------------------------------===//
5038
Jay Foad39c79802011-01-12 09:06:06 +00005039CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00005040 // Push qualifiers into arrays, and then discard any remaining
5041 // qualifiers.
5042 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00005043 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00005044 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00005045 QualType Result;
5046 if (isa<ArrayType>(Ty)) {
5047 Result = getArrayDecayedType(QualType(Ty,0));
5048 } else if (isa<FunctionType>(Ty)) {
5049 Result = getPointerType(QualType(Ty, 0));
5050 } else {
5051 Result = QualType(Ty, 0);
5052 }
5053
5054 return CanQualType::CreateUnsafe(Result);
5055}
5056
John McCall6c9dd522011-01-18 07:41:22 +00005057QualType ASTContext::getUnqualifiedArrayType(QualType type,
5058 Qualifiers &quals) {
5059 SplitQualType splitType = type.getSplitUnqualifiedType();
5060
5061 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5062 // the unqualified desugared type and then drops it on the floor.
5063 // We then have to strip that sugar back off with
5064 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005065 const auto *AT =
5066 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00005067
5068 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005069 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00005070 quals = splitType.Quals;
5071 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005072 }
5073
John McCall6c9dd522011-01-18 07:41:22 +00005074 // Otherwise, recurse on the array's element type.
5075 QualType elementType = AT->getElementType();
5076 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5077
5078 // If that didn't change the element type, AT has no qualifiers, so we
5079 // can just use the results in splitType.
5080 if (elementType == unqualElementType) {
5081 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00005082 quals = splitType.Quals;
5083 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00005084 }
5085
5086 // Otherwise, add in the qualifiers from the outermost type, then
5087 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00005088 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005089
Eugene Zelenko7855e772018-04-03 00:11:50 +00005090 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005091 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005092 CAT->getSizeModifier(), 0);
5093 }
5094
Eugene Zelenko7855e772018-04-03 00:11:50 +00005095 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005096 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005097 }
5098
Eugene Zelenko7855e772018-04-03 00:11:50 +00005099 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005100 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00005101 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005102 VAT->getSizeModifier(),
5103 VAT->getIndexTypeCVRQualifiers(),
5104 VAT->getBracketsRange());
5105 }
5106
Eugene Zelenko7855e772018-04-03 00:11:50 +00005107 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00005108 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005109 DSAT->getSizeModifier(), 0,
5110 SourceRange());
5111}
5112
Richard Smitha3405ff2018-07-11 00:19:19 +00005113/// Attempt to unwrap two types that may both be array types with the same bound
5114/// (or both be array types of unknown bound) for the purpose of comparing the
5115/// cv-decomposition of two types per C++ [conv.qual].
Richard Smith5407d4f2018-07-18 20:13:36 +00005116bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5117 bool UnwrappedAny = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00005118 while (true) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005119 auto *AT1 = getAsArrayType(T1);
5120 if (!AT1) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005121
Richard Smith5407d4f2018-07-18 20:13:36 +00005122 auto *AT2 = getAsArrayType(T2);
5123 if (!AT2) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005124
5125 // If we don't have two array types with the same constant bound nor two
5126 // incomplete array types, we've unwrapped everything we can.
5127 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5128 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5129 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
Richard Smith5407d4f2018-07-18 20:13:36 +00005130 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005131 } else if (!isa<IncompleteArrayType>(AT1) ||
5132 !isa<IncompleteArrayType>(AT2)) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005133 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005134 }
5135
5136 T1 = AT1->getElementType();
5137 T2 = AT2->getElementType();
Richard Smith5407d4f2018-07-18 20:13:36 +00005138 UnwrappedAny = true;
Richard Smitha3405ff2018-07-11 00:19:19 +00005139 }
5140}
5141
5142/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5143///
5144/// If T1 and T2 are both pointer types of the same kind, or both array types
5145/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5146/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5147///
5148/// This function will typically be called in a loop that successively
5149/// "unwraps" pointer and pointer-to-member types to compare them at each
5150/// level.
5151///
5152/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5153/// pair of types that can't be unwrapped further.
5154bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005155 UnwrapSimilarArrayTypes(T1, T2);
Richard Smitha3405ff2018-07-11 00:19:19 +00005156
Eugene Zelenko7855e772018-04-03 00:11:50 +00005157 const auto *T1PtrType = T1->getAs<PointerType>();
5158 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005159 if (T1PtrType && T2PtrType) {
5160 T1 = T1PtrType->getPointeeType();
5161 T2 = T2PtrType->getPointeeType();
5162 return true;
5163 }
Richard Smith5407d4f2018-07-18 20:13:36 +00005164
Eugene Zelenko7855e772018-04-03 00:11:50 +00005165 const auto *T1MPType = T1->getAs<MemberPointerType>();
5166 const auto *T2MPType = T2->getAs<MemberPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00005167 if (T1MPType && T2MPType &&
5168 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005169 QualType(T2MPType->getClass(), 0))) {
5170 T1 = T1MPType->getPointeeType();
5171 T2 = T2MPType->getPointeeType();
5172 return true;
5173 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005174
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005175 if (getLangOpts().ObjC) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005176 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5177 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005178 if (T1OPType && T2OPType) {
5179 T1 = T1OPType->getPointeeType();
5180 T2 = T2OPType->getPointeeType();
5181 return true;
5182 }
5183 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005184
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005185 // FIXME: Block pointers, too?
Fangrui Song6907ce22018-07-30 19:24:48 +00005186
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005187 return false;
5188}
5189
Richard Smitha3405ff2018-07-11 00:19:19 +00005190bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5191 while (true) {
5192 Qualifiers Quals;
5193 T1 = getUnqualifiedArrayType(T1, Quals);
5194 T2 = getUnqualifiedArrayType(T2, Quals);
5195 if (hasSameType(T1, T2))
5196 return true;
5197 if (!UnwrapSimilarTypes(T1, T2))
5198 return false;
5199 }
5200}
5201
5202bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5203 while (true) {
5204 Qualifiers Quals1, Quals2;
5205 T1 = getUnqualifiedArrayType(T1, Quals1);
5206 T2 = getUnqualifiedArrayType(T2, Quals2);
5207
5208 Quals1.removeCVRQualifiers();
5209 Quals2.removeCVRQualifiers();
5210 if (Quals1 != Quals2)
5211 return false;
5212
5213 if (hasSameType(T1, T2))
5214 return true;
5215
5216 if (!UnwrapSimilarTypes(T1, T2))
5217 return false;
5218 }
5219}
5220
Jay Foad39c79802011-01-12 09:06:06 +00005221DeclarationNameInfo
5222ASTContext::getNameForTemplate(TemplateName Name,
5223 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005224 switch (Name.getKind()) {
5225 case TemplateName::QualifiedTemplate:
5226 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005227 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005228 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5229 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005230
John McCalld9dfe3a2011-06-30 08:33:18 +00005231 case TemplateName::OverloadedTemplate: {
5232 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5233 // DNInfo work in progress: CHECKME: what about DNLoc?
5234 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5235 }
5236
Richard Smithb23c5e82019-05-09 03:31:27 +00005237 case TemplateName::AssumedTemplate: {
5238 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5239 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5240 }
5241
John McCalld9dfe3a2011-06-30 08:33:18 +00005242 case TemplateName::DependentTemplate: {
5243 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005244 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005245 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005246 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5247 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005248 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005249 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5250 // DNInfo work in progress: FIXME: source locations?
5251 DeclarationNameLoc DNLoc;
5252 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5253 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5254 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005255 }
5256 }
5257
John McCalld9dfe3a2011-06-30 08:33:18 +00005258 case TemplateName::SubstTemplateTemplateParm: {
5259 SubstTemplateTemplateParmStorage *subst
5260 = Name.getAsSubstTemplateTemplateParm();
5261 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5262 NameLoc);
5263 }
5264
5265 case TemplateName::SubstTemplateTemplateParmPack: {
5266 SubstTemplateTemplateParmPackStorage *subst
5267 = Name.getAsSubstTemplateTemplateParmPack();
5268 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5269 NameLoc);
5270 }
5271 }
5272
5273 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005274}
5275
Jay Foad39c79802011-01-12 09:06:06 +00005276TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005277 switch (Name.getKind()) {
5278 case TemplateName::QualifiedTemplate:
5279 case TemplateName::Template: {
5280 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005281 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005282 Template = getCanonicalTemplateTemplateParmDecl(TTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00005283
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005284 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005285 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005286 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005287
John McCalld9dfe3a2011-06-30 08:33:18 +00005288 case TemplateName::OverloadedTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00005289 case TemplateName::AssumedTemplate:
5290 llvm_unreachable("cannot canonicalize unresolved template");
Mike Stump11289f42009-09-09 15:08:12 +00005291
John McCalld9dfe3a2011-06-30 08:33:18 +00005292 case TemplateName::DependentTemplate: {
5293 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5294 assert(DTN && "Non-dependent template names must refer to template decls.");
5295 return DTN->CanonicalTemplateName;
5296 }
5297
5298 case TemplateName::SubstTemplateTemplateParm: {
5299 SubstTemplateTemplateParmStorage *subst
5300 = Name.getAsSubstTemplateTemplateParm();
5301 return getCanonicalTemplateName(subst->getReplacement());
5302 }
5303
5304 case TemplateName::SubstTemplateTemplateParmPack: {
5305 SubstTemplateTemplateParmPackStorage *subst
5306 = Name.getAsSubstTemplateTemplateParmPack();
5307 TemplateTemplateParmDecl *canonParameter
5308 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5309 TemplateArgument canonArgPack
5310 = getCanonicalTemplateArgument(subst->getArgumentPack());
5311 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5312 }
5313 }
5314
5315 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005316}
5317
Douglas Gregoradee3e32009-11-11 23:06:43 +00005318bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5319 X = getCanonicalTemplateName(X);
5320 Y = getCanonicalTemplateName(Y);
5321 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5322}
5323
Mike Stump11289f42009-09-09 15:08:12 +00005324TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005325ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005326 switch (Arg.getKind()) {
5327 case TemplateArgument::Null:
5328 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005329
Douglas Gregora8e02e72009-07-28 23:00:59 +00005330 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005331 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005332
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005333 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005334 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005335 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005336 }
Mike Stump11289f42009-09-09 15:08:12 +00005337
Eli Friedmanb826a002012-09-26 02:36:12 +00005338 case TemplateArgument::NullPtr:
5339 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5340 /*isNullPtr*/true);
5341
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005342 case TemplateArgument::Template:
5343 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005344
5345 case TemplateArgument::TemplateExpansion:
5346 return TemplateArgument(getCanonicalTemplateName(
5347 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005348 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005349
Douglas Gregora8e02e72009-07-28 23:00:59 +00005350 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005351 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005352
Douglas Gregora8e02e72009-07-28 23:00:59 +00005353 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005354 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005355
Douglas Gregora8e02e72009-07-28 23:00:59 +00005356 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005357 if (Arg.pack_size() == 0)
5358 return Arg;
Fangrui Song6907ce22018-07-30 19:24:48 +00005359
Eugene Zelenko7855e772018-04-03 00:11:50 +00005360 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005361 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005362 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005363 AEnd = Arg.pack_end();
5364 A != AEnd; (void)++A, ++Idx)
5365 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005366
Benjamin Kramercce63472015-08-05 09:40:22 +00005367 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005368 }
5369 }
5370
5371 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005372 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005373}
5374
Douglas Gregor333489b2009-03-27 23:10:48 +00005375NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005376ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005377 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005378 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005379
5380 switch (NNS->getKind()) {
5381 case NestedNameSpecifier::Identifier:
5382 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005383 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005384 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5385 NNS->getAsIdentifier());
5386
5387 case NestedNameSpecifier::Namespace:
5388 // A namespace is canonical; build a nested-name-specifier with
5389 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005390 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005391 NNS->getAsNamespace()->getOriginalNamespace());
5392
5393 case NestedNameSpecifier::NamespaceAlias:
5394 // A namespace is canonical; build a nested-name-specifier with
5395 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005396 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005397 NNS->getAsNamespaceAlias()->getNamespace()
5398 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005399
5400 case NestedNameSpecifier::TypeSpec:
5401 case NestedNameSpecifier::TypeSpecWithTemplate: {
5402 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Fangrui Song6907ce22018-07-30 19:24:48 +00005403
Douglas Gregor3ade5702010-11-04 00:09:33 +00005404 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5405 // break it apart into its prefix and identifier, then reconsititute those
5406 // as the canonical nested-name-specifier. This is required to canonicalize
5407 // a dependent nested-name-specifier involving typedefs of dependent-name
5408 // types, e.g.,
5409 // typedef typename T::type T1;
5410 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005411 if (const auto *DNT = T->getAs<DependentNameType>())
Fangrui Song6907ce22018-07-30 19:24:48 +00005412 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005413 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005414
Eli Friedman5358a0a2012-03-03 04:09:56 +00005415 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5416 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5417 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005418 return NestedNameSpecifier::Create(*this, nullptr, false,
5419 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005420 }
5421
5422 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005423 case NestedNameSpecifier::Super:
5424 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005425 return NNS;
5426 }
5427
David Blaikie8a40f702012-01-17 06:56:22 +00005428 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005429}
5430
Jay Foad39c79802011-01-12 09:06:06 +00005431const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005432 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005433 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005434 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005435 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005436 return AT;
5437 }
Mike Stump11289f42009-09-09 15:08:12 +00005438
John McCall8ccfcb52009-09-24 19:53:00 +00005439 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005440 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005441 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005442
John McCall8ccfcb52009-09-24 19:53:00 +00005443 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005444 // implements C99 6.7.3p8: "If the specification of an array type includes
5445 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005446
Chris Lattner7adf0762008-08-04 07:31:14 +00005447 // If we get here, we either have type qualifiers on the type, or we have
5448 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005449 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005450
John McCall33ddac02011-01-19 10:06:00 +00005451 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005452 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005453
Chris Lattner7adf0762008-08-04 07:31:14 +00005454 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005455 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005456 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005457 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005458
Chris Lattner7adf0762008-08-04 07:31:14 +00005459 // Otherwise, we have an array and we have qualifiers on it. Push the
5460 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005461 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005462
Eugene Zelenko7855e772018-04-03 00:11:50 +00005463 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005464 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5465 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005466 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005467 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005468 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5469 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005470 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005471
Eugene Zelenko7855e772018-04-03 00:11:50 +00005472 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005473 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005474 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005475 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005476 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005477 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005478 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005479
Eugene Zelenko7855e772018-04-03 00:11:50 +00005480 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005481 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005482 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005483 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005484 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005485 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005486}
5487
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005488QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005489 if (T->isArrayType() || T->isFunctionType())
5490 return getDecayedType(T);
5491 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005492}
5493
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005494QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005495 T = getVariableArrayDecayedType(T);
5496 T = getAdjustedParameterType(T);
5497 return T.getUnqualifiedType();
5498}
5499
David Majnemerd09a51c2015-03-03 01:50:05 +00005500QualType ASTContext::getExceptionObjectType(QualType T) const {
5501 // C++ [except.throw]p3:
5502 // A throw-expression initializes a temporary object, called the exception
5503 // object, the type of which is determined by removing any top-level
5504 // cv-qualifiers from the static type of the operand of throw and adjusting
5505 // the type from "array of T" or "function returning T" to "pointer to T"
5506 // or "pointer to function returning T", [...]
5507 T = getVariableArrayDecayedType(T);
5508 if (T->isArrayType() || T->isFunctionType())
5509 T = getDecayedType(T);
5510 return T.getUnqualifiedType();
5511}
5512
Chris Lattnera21ad802008-04-02 05:18:44 +00005513/// getArrayDecayedType - Return the properly qualified result of decaying the
5514/// specified array type to a pointer. This operation is non-trivial when
5515/// handling typedefs etc. The canonical type of "T" must be an array type,
5516/// this returns a pointer to a properly qualified element of the array.
5517///
5518/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005519QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005520 // Get the element type with 'getAsArrayType' so that we don't lose any
5521 // typedefs in the element type of the array. This also handles propagation
5522 // of type qualifiers from the array type into the element type if present
5523 // (C99 6.7.3p8).
5524 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5525 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005526
Chris Lattner7adf0762008-08-04 07:31:14 +00005527 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005528
5529 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005530 QualType Result = getQualifiedType(PtrTy,
5531 PrettyArrayType->getIndexTypeQualifiers());
5532
5533 // int x[_Nullable] -> int * _Nullable
5534 if (auto Nullability = Ty->getNullability(*this)) {
5535 Result = const_cast<ASTContext *>(this)->getAttributedType(
5536 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5537 }
5538 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005539}
5540
John McCall33ddac02011-01-19 10:06:00 +00005541QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5542 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005543}
5544
John McCall33ddac02011-01-19 10:06:00 +00005545QualType ASTContext::getBaseElementType(QualType type) const {
5546 Qualifiers qs;
5547 while (true) {
5548 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005549 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005550 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005551
John McCall33ddac02011-01-19 10:06:00 +00005552 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005553 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005554 }
Mike Stump11289f42009-09-09 15:08:12 +00005555
John McCall33ddac02011-01-19 10:06:00 +00005556 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005557}
5558
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005559/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005560uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005561ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5562 uint64_t ElementCount = 1;
5563 do {
5564 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005565 CA = dyn_cast_or_null<ConstantArrayType>(
5566 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005567 } while (CA);
5568 return ElementCount;
5569}
5570
Steve Naroff0af91202007-04-27 21:51:21 +00005571/// getFloatingRank - Return a relative rank for floating point types.
5572/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005573static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005574 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005575 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005576
John McCall9dd450b2009-09-21 23:43:11 +00005577 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5578 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005579 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005580 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005581 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005582 case BuiltinType::Float: return FloatRank;
5583 case BuiltinType::Double: return DoubleRank;
5584 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005585 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005586 }
5587}
5588
Mike Stump11289f42009-09-09 15:08:12 +00005589/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5590/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005591/// 'typeDomain' is a real floating point or complex type.
5592/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005593QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5594 QualType Domain) const {
5595 FloatingRank EltRank = getFloatingRank(Size);
5596 if (Domain->isComplexType()) {
5597 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005598 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005599 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005600 case FloatRank: return FloatComplexTy;
5601 case DoubleRank: return DoubleComplexTy;
5602 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005603 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005604 }
Steve Naroff0af91202007-04-27 21:51:21 +00005605 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005606
5607 assert(Domain->isRealFloatingType() && "Unknown domain!");
5608 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005609 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005610 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005611 case FloatRank: return FloatTy;
5612 case DoubleRank: return DoubleTy;
5613 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005614 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005615 }
David Blaikief47fa302012-01-17 02:30:50 +00005616 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005617}
5618
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005619/// getFloatingTypeOrder - Compare the rank of the two specified floating
5620/// point types, ignoring the domain of the type (i.e. 'double' ==
5621/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005622/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005623int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005624 FloatingRank LHSR = getFloatingRank(LHS);
5625 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005626
Chris Lattnerb90739d2008-04-06 23:38:49 +00005627 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005628 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005629 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005630 return 1;
5631 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005632}
5633
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +00005634int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
5635 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
5636 return 0;
5637 return getFloatingTypeOrder(LHS, RHS);
5638}
5639
Chris Lattner76a00cf2008-04-06 22:59:24 +00005640/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5641/// routine will assert if passed a built-in type that isn't an integer or enum,
5642/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005643unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005644 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005645
Chris Lattner76a00cf2008-04-06 22:59:24 +00005646 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005647 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005648 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005649 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005650 case BuiltinType::Char_S:
5651 case BuiltinType::Char_U:
5652 case BuiltinType::SChar:
5653 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005654 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005655 case BuiltinType::Short:
5656 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005657 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005658 case BuiltinType::Int:
5659 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005660 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005661 case BuiltinType::Long:
5662 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005663 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005664 case BuiltinType::LongLong:
5665 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005666 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005667 case BuiltinType::Int128:
5668 case BuiltinType::UInt128:
5669 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005670 }
5671}
5672
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005673/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005674/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5675///
5676/// \returns the type this bit-field will promote to, or NULL if no
5677/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005678QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005679 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005680 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005681
Richard Smithaadb2542018-06-28 21:17:55 +00005682 // C++ [conv.prom]p5:
5683 // If the bit-field has an enumerated type, it is treated as any other
5684 // value of that type for promotion purposes.
5685 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5686 return {};
5687
Richard Smith5b571672014-09-24 23:55:00 +00005688 // FIXME: We should not do this unless E->refersToBitField() is true. This
5689 // matters in C where getSourceBitField() will find bit-fields for various
5690 // cases where the source expression is not a bit-field designator.
5691
John McCalld25db7e2013-05-06 21:39:12 +00005692 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005693 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005694 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005695
5696 QualType FT = Field->getType();
5697
Richard Smithcaf33902011-10-10 18:28:20 +00005698 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005699 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005700 // C++ [conv.prom]p5:
5701 // A prvalue for an integral bit-field can be converted to a prvalue of type
5702 // int if int can represent all the values of the bit-field; otherwise, it
5703 // can be converted to unsigned int if unsigned int can represent all the
5704 // values of the bit-field. If the bit-field is larger yet, no integral
5705 // promotion applies to it.
5706 // C11 6.3.1.1/2:
5707 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5708 // If an int can represent all values of the original type (as restricted by
5709 // the width, for a bit-field), the value is converted to an int; otherwise,
5710 // it is converted to an unsigned int.
5711 //
5712 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5713 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005714 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5715 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005716 if (BitWidth < IntSize)
5717 return IntTy;
5718
5719 if (BitWidth == IntSize)
5720 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5721
Richard Smithaadb2542018-06-28 21:17:55 +00005722 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005723 // like the base type. GCC has some weird bugs in this area that we
5724 // deliberately do not follow (GCC follows a pre-standard resolution to
5725 // C's DR315 which treats bit-width as being part of the type, and this leaks
5726 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005727 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005728}
5729
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005730/// getPromotedIntegerType - Returns the type that Promotable will
5731/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5732/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005733QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005734 assert(!Promotable.isNull());
5735 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005736 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005737 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005738
Eugene Zelenko7855e772018-04-03 00:11:50 +00005739 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005740 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5741 // (3.9.1) can be converted to a prvalue of the first of the following
5742 // types that can represent all the values of its underlying type:
5743 // int, unsigned int, long int, unsigned long int, long long int, or
5744 // unsigned long long int [...]
5745 // FIXME: Is there some better way to compute this?
5746 if (BT->getKind() == BuiltinType::WChar_S ||
5747 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005748 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005749 BT->getKind() == BuiltinType::Char16 ||
5750 BT->getKind() == BuiltinType::Char32) {
5751 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5752 uint64_t FromSize = getTypeSize(BT);
5753 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5754 LongLongTy, UnsignedLongLongTy };
5755 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5756 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5757 if (FromSize < ToSize ||
5758 (FromSize == ToSize &&
5759 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5760 return PromoteTypes[Idx];
5761 }
5762 llvm_unreachable("char type should fit into long long");
5763 }
5764 }
5765
5766 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005767 if (Promotable->isSignedIntegerType())
5768 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005769 uint64_t PromotableSize = getIntWidth(Promotable);
5770 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005771 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5772 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5773}
5774
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005775/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005776/// type and returns its ownership.
5777Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5778 while (!T.isNull()) {
5779 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5780 return T.getObjCLifetime();
5781 if (T->isArrayType())
5782 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005783 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005784 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005785 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005786 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005787 else
5788 break;
5789 }
5790
5791 return Qualifiers::OCL_None;
5792}
5793
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005794static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5795 // Incomplete enum types are not treated as integer types.
5796 // FIXME: In C++, enum types are never integer types.
5797 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5798 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005799 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005800}
5801
Mike Stump11289f42009-09-09 15:08:12 +00005802/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005803/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005804/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005805int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005806 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5807 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005808
5809 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005810 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005811 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005812 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005813 RHSC = getIntegerTypeForEnum(ET);
5814
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005815 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005816
Chris Lattner76a00cf2008-04-06 22:59:24 +00005817 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5818 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005819
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005820 unsigned LHSRank = getIntegerRank(LHSC);
5821 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005822
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005823 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5824 if (LHSRank == RHSRank) return 0;
5825 return LHSRank > RHSRank ? 1 : -1;
5826 }
Mike Stump11289f42009-09-09 15:08:12 +00005827
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005828 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5829 if (LHSUnsigned) {
5830 // If the unsigned [LHS] type is larger, return it.
5831 if (LHSRank >= RHSRank)
5832 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005833
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005834 // If the signed type can represent all values of the unsigned type, it
5835 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005836 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005837 return -1;
5838 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005839
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005840 // If the unsigned [RHS] type is larger, return it.
5841 if (RHSRank >= LHSRank)
5842 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005843
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005844 // If the signed type can represent all values of the unsigned type, it
5845 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005846 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005847 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005848}
Anders Carlsson98f07902007-08-17 05:31:46 +00005849
Ben Langmuirf5416742016-02-04 00:55:24 +00005850TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005851 if (CFConstantStringTypeDecl)
5852 return CFConstantStringTypeDecl;
Anders Carlsson6d417272009-11-14 21:45:58 +00005853
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005854 assert(!CFConstantStringTagDecl &&
5855 "tag and typedef should be initialized together");
5856 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5857 CFConstantStringTagDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00005858
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005859 struct {
5860 QualType Type;
5861 const char *Name;
5862 } Fields[5];
5863 unsigned Count = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005864
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005865 /// Objective-C ABI
5866 ///
5867 /// typedef struct __NSConstantString_tag {
Saleem Abdulrasool1f6c41f2018-10-27 06:12:52 +00005868 /// const int *isa;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005869 /// int flags;
5870 /// const char *str;
5871 /// long length;
5872 /// } __NSConstantString;
5873 ///
5874 /// Swift ABI (4.1, 4.2)
5875 ///
5876 /// typedef struct __NSConstantString_tag {
5877 /// uintptr_t _cfisa;
5878 /// uintptr_t _swift_rc;
5879 /// _Atomic(uint64_t) _cfinfoa;
5880 /// const char *_ptr;
5881 /// uint32_t _length;
5882 /// } __NSConstantString;
5883 ///
5884 /// Swift ABI (5.0)
5885 ///
5886 /// typedef struct __NSConstantString_tag {
5887 /// uintptr_t _cfisa;
5888 /// uintptr_t _swift_rc;
5889 /// _Atomic(uint64_t) _cfinfoa;
5890 /// const char *_ptr;
5891 /// uintptr_t _length;
5892 /// } __NSConstantString;
5893
5894 const auto CFRuntime = getLangOpts().CFRuntime;
5895 if (static_cast<unsigned>(CFRuntime) <
5896 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
5897 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
5898 Fields[Count++] = { IntTy, "flags" };
5899 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
5900 Fields[Count++] = { LongTy, "length" };
5901 } else {
5902 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
5903 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
5904 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
5905 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
5906 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5907 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5908 Fields[Count++] = { IntTy, "_ptr" };
5909 else
5910 Fields[Count++] = { getUIntPtrType(), "_ptr" };
5911 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005912
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005913 // Create fields
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005914 for (unsigned i = 0; i < Count; ++i) {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005915 FieldDecl *Field =
5916 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005917 SourceLocation(), &Idents.get(Fields[i].Name),
5918 Fields[i].Type, /*TInfo=*/nullptr,
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005919 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5920 Field->setAccess(AS_public);
5921 CFConstantStringTagDecl->addDecl(Field);
Anders Carlsson98f07902007-08-17 05:31:46 +00005922 }
Mike Stump11289f42009-09-09 15:08:12 +00005923
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005924 CFConstantStringTagDecl->completeDefinition();
5925 // This type is designed to be compatible with NSConstantString, but cannot
5926 // use the same name, since NSConstantString is an interface.
5927 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5928 CFConstantStringTypeDecl =
5929 buildImplicitTypedef(tagType, "__NSConstantString");
5930
Quentin Colombet043406b2016-02-03 22:41:00 +00005931 return CFConstantStringTypeDecl;
5932}
5933
Ben Langmuirf5416742016-02-04 00:55:24 +00005934RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5935 if (!CFConstantStringTagDecl)
5936 getCFConstantStringDecl(); // Build the tag and the typedef.
5937 return CFConstantStringTagDecl;
5938}
5939
Quentin Colombet043406b2016-02-03 22:41:00 +00005940// getCFConstantStringType - Return the type used for constant CFStrings.
5941QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005942 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005943}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005944
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005945QualType ASTContext::getObjCSuperType() const {
5946 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005947 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005948 TUDecl->addDecl(ObjCSuperTypeDecl);
5949 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5950 }
5951 return ObjCSuperType;
5952}
5953
Douglas Gregor512b0772009-04-23 22:29:11 +00005954void ASTContext::setCFConstantStringType(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005955 const auto *TD = T->getAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00005956 assert(TD && "Invalid CFConstantStringType");
5957 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005958 const auto *TagType =
Ben Langmuirf5416742016-02-04 00:55:24 +00005959 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5960 assert(TagType && "Invalid CFConstantStringType");
5961 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005962}
5963
Jay Foad39c79802011-01-12 09:06:06 +00005964QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005965 if (BlockDescriptorType)
5966 return getTagDeclType(BlockDescriptorType);
5967
Alp Toker2dea15b2013-12-17 01:22:38 +00005968 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005969 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005970 RD = buildImplicitRecord("__block_descriptor");
5971 RD->startDefinition();
5972
Mike Stumpd0153282009-10-20 02:12:22 +00005973 QualType FieldTypes[] = {
5974 UnsignedLongTy,
5975 UnsignedLongTy,
5976 };
5977
Craig Topperd6d31ac2013-07-15 08:24:27 +00005978 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005979 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005980 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005981 };
5982
5983 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005984 FieldDecl *Field = FieldDecl::Create(
5985 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005986 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5987 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005988 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005989 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005990 }
5991
Alp Toker2dea15b2013-12-17 01:22:38 +00005992 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005993
Alp Toker2dea15b2013-12-17 01:22:38 +00005994 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005995
5996 return getTagDeclType(BlockDescriptorType);
5997}
5998
Jay Foad39c79802011-01-12 09:06:06 +00005999QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006000 if (BlockDescriptorExtendedType)
6001 return getTagDeclType(BlockDescriptorExtendedType);
6002
Alp Toker2dea15b2013-12-17 01:22:38 +00006003 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006004 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00006005 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6006 RD->startDefinition();
6007
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006008 QualType FieldTypes[] = {
6009 UnsignedLongTy,
6010 UnsignedLongTy,
6011 getPointerType(VoidPtrTy),
6012 getPointerType(VoidPtrTy)
6013 };
6014
Craig Topperd6d31ac2013-07-15 08:24:27 +00006015 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006016 "reserved",
6017 "Size",
6018 "CopyFuncPtr",
6019 "DestroyFuncPtr"
6020 };
6021
6022 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006023 FieldDecl *Field = FieldDecl::Create(
6024 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006025 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6026 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00006027 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006028 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006029 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006030 }
6031
Alp Toker2dea15b2013-12-17 01:22:38 +00006032 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006033
Alp Toker2dea15b2013-12-17 01:22:38 +00006034 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006035 return getTagDeclType(BlockDescriptorExtendedType);
6036}
6037
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006038TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006039 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006040
6041 if (!BT) {
6042 if (isa<PipeType>(T))
6043 return TargetInfo::OCLTK_Pipe;
6044
6045 return TargetInfo::OCLTK_Default;
6046 }
6047
6048 switch (BT->getKind()) {
6049#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6050 case BuiltinType::Id: \
6051 return TargetInfo::OCLTK_Image;
6052#include "clang/Basic/OpenCLImageTypes.def"
6053
6054 case BuiltinType::OCLClkEvent:
6055 return TargetInfo::OCLTK_ClkEvent;
6056
6057 case BuiltinType::OCLEvent:
6058 return TargetInfo::OCLTK_Event;
6059
6060 case BuiltinType::OCLQueue:
6061 return TargetInfo::OCLTK_Queue;
6062
6063 case BuiltinType::OCLReserveID:
6064 return TargetInfo::OCLTK_ReserveID;
6065
6066 case BuiltinType::OCLSampler:
6067 return TargetInfo::OCLTK_Sampler;
6068
6069 default:
6070 return TargetInfo::OCLTK_Default;
6071 }
6072}
6073
6074LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6075 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6076}
6077
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006078/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6079/// requires copy/dispose. Note that this must match the logic
6080/// in buildByrefHelpers.
6081bool ASTContext::BlockRequiresCopying(QualType Ty,
6082 const VarDecl *D) {
6083 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00006084 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006085 if (!copyExpr && record->hasTrivialDestructor()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006086
Mike Stump94967902009-10-21 18:16:27 +00006087 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00006088 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006089
Akira Hatanaka7275da02018-02-28 07:15:55 +00006090 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6091 // move or destroy.
6092 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6093 return true;
6094
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006095 if (!Ty->isObjCRetainableType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006096
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006097 Qualifiers qs = Ty.getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00006098
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006099 // If we have lifetime, that dominates.
6100 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006101 switch (lifetime) {
6102 case Qualifiers::OCL_None: llvm_unreachable("impossible");
Fangrui Song6907ce22018-07-30 19:24:48 +00006103
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006104 // These are just bits as far as the runtime is concerned.
6105 case Qualifiers::OCL_ExplicitNone:
6106 case Qualifiers::OCL_Autoreleasing:
6107 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00006108
6109 // These cases should have been taken care of when checking the type's
6110 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006111 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006112 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00006113 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006114 }
6115 llvm_unreachable("fell out of lifetime switch!");
6116 }
6117 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6118 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00006119}
6120
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006121bool ASTContext::getByrefLifetime(QualType Ty,
6122 Qualifiers::ObjCLifetime &LifeTime,
6123 bool &HasByrefExtendedLayout) const {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00006124 if (!getLangOpts().ObjC ||
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006125 getLangOpts().getGC() != LangOptions::NonGC)
6126 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006127
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006128 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00006129 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006130 HasByrefExtendedLayout = true;
6131 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006132 } else if ((LifeTime = Ty.getObjCLifetime())) {
6133 // Honor the ARC qualifiers.
6134 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6135 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006136 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00006137 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006138 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006139 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006140 return true;
6141}
6142
Douglas Gregorbab8a962011-09-08 01:46:34 +00006143TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6144 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00006145 ObjCInstanceTypeDecl =
6146 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00006147 return ObjCInstanceTypeDecl;
6148}
6149
Anders Carlsson18acd442007-10-29 06:33:42 +00006150// This returns true if a type has been typedefed to BOOL:
6151// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00006152static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006153 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00006154 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6155 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00006156
Anders Carlssond8499822007-10-29 05:01:08 +00006157 return false;
6158}
6159
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006160/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006161/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00006162CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00006163 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6164 return CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00006165
Ken Dyck40775002010-01-11 17:06:35 +00006166 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00006167
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006168 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00006169 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00006170 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006171 // Treat arrays as pointers, since that's how they're passed in.
6172 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00006173 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00006174 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00006175}
6176
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006177bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00006178 return getTargetInfo().getCXXABI().isMicrosoft() &&
6179 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00006180 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00006181 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006182}
6183
Richard Smithd9b90092016-07-02 01:32:16 +00006184ASTContext::InlineVariableDefinitionKind
6185ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6186 if (!VD->isInline())
6187 return InlineVariableDefinitionKind::None;
6188
6189 // In almost all cases, it's a weak definition.
6190 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00006191 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00006192 return InlineVariableDefinitionKind::Weak;
6193
6194 // If there's a file-context declaration in this translation unit, it's a
6195 // non-discardable definition.
6196 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00006197 if (D->getLexicalDeclContext()->isFileContext() &&
6198 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00006199 return InlineVariableDefinitionKind::Strong;
6200
6201 // If we've not seen one yet, we don't know.
6202 return InlineVariableDefinitionKind::WeakUnknown;
6203}
6204
Eugene Zelenko7855e772018-04-03 00:11:50 +00006205static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00006206 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006207}
6208
John McCall351762c2011-02-07 10:33:21 +00006209/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00006210/// declaration.
John McCall351762c2011-02-07 10:33:21 +00006211std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6212 std::string S;
6213
David Chisnall950a9512009-11-17 19:33:30 +00006214 const BlockDecl *Decl = Expr->getBlockDecl();
6215 QualType BlockTy =
6216 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
6217 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006218 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00006219 getObjCEncodingForMethodParameter(
6220 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
6221 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006222 else
Alp Toker314cc812014-01-25 16:55:45 +00006223 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00006224 // Compute size of all parameters.
6225 // Start with computing size of a pointer in number of bytes.
6226 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006227 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6228 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006229 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00006230 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006231 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00006232 if (sz.isZero())
6233 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006234 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00006235 ParmOffset += sz;
6236 }
6237 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00006238 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00006239 // Block pointer and offset.
6240 S += "@?0";
Fangrui Song6907ce22018-07-30 19:24:48 +00006241
David Chisnall950a9512009-11-17 19:33:30 +00006242 // Argument types.
6243 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006244 for (auto PVDecl : Decl->parameters()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006245 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006246 if (const auto *AT =
6247 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00006248 // Use array's original type only if it has known number of
6249 // elements.
6250 if (!isa<ConstantArrayType>(AT))
6251 PType = PVDecl->getType();
6252 } else if (PType->isFunctionType())
6253 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006254 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006255 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6256 S, true /*Extended*/);
6257 else
6258 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006259 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006260 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006261 }
John McCall351762c2011-02-07 10:33:21 +00006262
6263 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006264}
6265
John McCall843dfcc2016-11-29 21:57:00 +00006266std::string
6267ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6268 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006269 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006270 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006271 CharUnits ParmOffset;
6272 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006273 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006274 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006275 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006276 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006277 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006278
6279 assert(sz.isPositive() &&
John McCall843dfcc2016-11-29 21:57:00 +00006280 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006281 ParmOffset += sz;
6282 }
6283 S += charUnitsToString(ParmOffset);
6284 ParmOffset = CharUnits::Zero();
6285
6286 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006287 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006288 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006289 if (const auto *AT =
6290 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006291 // Use array's original type only if it has known number of
6292 // elements.
6293 if (!isa<ConstantArrayType>(AT))
6294 PType = PVDecl->getType();
6295 } else if (PType->isFunctionType())
6296 PType = PVDecl->getType();
6297 getObjCEncodingForType(PType, S);
6298 S += charUnitsToString(ParmOffset);
6299 ParmOffset += getObjCEncodingTypeSize(PType);
6300 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006301
John McCall843dfcc2016-11-29 21:57:00 +00006302 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006303}
6304
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006305/// getObjCEncodingForMethodParameter - Return the encoded type for a single
Fangrui Song6907ce22018-07-30 19:24:48 +00006306/// method parameter or return type. If Extended, include class names and
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006307/// block object types.
6308void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6309 QualType T, std::string& S,
6310 bool Extended) const {
6311 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6312 getObjCEncodingForTypeQualifier(QT, S);
6313 // Encode parameter type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006314 ObjCEncOptions Options = ObjCEncOptions()
6315 .setExpandPointedToStructures()
6316 .setExpandStructures()
6317 .setIsOutermostType();
6318 if (Extended)
6319 Options.setEncodeBlockParameters().setEncodeClassNames();
6320 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006321}
6322
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006323/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006324/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006325std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6326 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006327 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006328 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006329 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006330 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6331 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006332 // Compute size of all parameters.
6333 // Start with computing size of a pointer in number of bytes.
6334 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006335 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006336 // The first two arguments (self and _cmd) are pointers; account for
6337 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006338 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006339 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006340 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006341 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006342 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006343 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006344 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006345
6346 assert(sz.isPositive() &&
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006347 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006348 ParmOffset += sz;
6349 }
Ken Dyck40775002010-01-11 17:06:35 +00006350 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006351 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006352 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006353
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006354 // Argument types.
6355 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006356 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006357 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006358 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006359 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006360 if (const auto *AT =
6361 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006362 // Use array's original type only if it has known number of
6363 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006364 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006365 PType = PVDecl->getType();
6366 } else if (PType->isFunctionType())
6367 PType = PVDecl->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00006368 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006369 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006370 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006371 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006372 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006373
John McCall843dfcc2016-11-29 21:57:00 +00006374 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006375}
6376
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006377ObjCPropertyImplDecl *
6378ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6379 const ObjCPropertyDecl *PD,
6380 const Decl *Container) const {
6381 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006382 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006383 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006384 for (auto *PID : CID->property_impls())
6385 if (PID->getPropertyDecl() == PD)
6386 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006387 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006388 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006389 for (auto *PID : OID->property_impls())
6390 if (PID->getPropertyDecl() == PD)
6391 return PID;
6392 }
6393 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006394}
6395
Daniel Dunbar4932b362008-08-28 04:38:10 +00006396/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006397/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006398/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6399/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006400/// Property attributes are stored as a comma-delimited C string. The simple
6401/// attributes readonly and bycopy are encoded as single characters. The
6402/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6403/// encoded as single characters, followed by an identifier. Property types
6404/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006405/// these attributes are defined by the following enumeration:
6406/// @code
6407/// enum PropertyAttributes {
6408/// kPropertyReadOnly = 'R', // property is read-only.
6409/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6410/// kPropertyByref = '&', // property is a reference to the value last assigned
6411/// kPropertyDynamic = 'D', // property is dynamic
6412/// kPropertyGetter = 'G', // followed by getter selector name
6413/// kPropertySetter = 'S', // followed by setter selector name
6414/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006415/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006416/// kPropertyWeak = 'W' // 'weak' property
6417/// kPropertyStrong = 'P' // property GC'able
6418/// kPropertyNonAtomic = 'N' // property non-atomic
6419/// };
6420/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006421std::string
6422ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6423 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006424 // Collect information from the property implementation decl(s).
6425 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006426 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006427
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006428 if (ObjCPropertyImplDecl *PropertyImpDecl =
6429 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6430 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6431 Dynamic = true;
6432 else
6433 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006434 }
6435
6436 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006437 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006438
6439 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006440 // GCC has some special rules regarding encoding of properties which
6441 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006442 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006443
6444 if (PD->isReadOnly()) {
6445 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006446 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6447 S += ",C";
6448 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6449 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006450 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6451 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006452 } else {
6453 switch (PD->getSetterKind()) {
6454 case ObjCPropertyDecl::Assign: break;
6455 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006456 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006457 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006458 }
6459 }
6460
6461 // It really isn't clear at all what this means, since properties
6462 // are "dynamic by default".
6463 if (Dynamic)
6464 S += ",D";
6465
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006466 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6467 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006468
Daniel Dunbar4932b362008-08-28 04:38:10 +00006469 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6470 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006471 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006472 }
6473
6474 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6475 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006476 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006477 }
6478
6479 if (SynthesizePID) {
6480 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6481 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006482 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006483 }
6484
6485 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006486 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006487}
6488
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006489/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006490/// Another legacy compatibility encoding: 32-bit longs are encoded as
6491/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006492/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006493void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006494 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006495 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006496 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006497 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006498 else
Jay Foad39c79802011-01-12 09:06:06 +00006499 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006500 PointeeTy = IntTy;
6501 }
6502 }
6503}
6504
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006505void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006506 const FieldDecl *Field,
6507 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006508 // We follow the behavior of gcc, expanding structures which are
6509 // directly pointed to, and expanding embedded structures. Note that
6510 // these rules are sufficient to prevent recursive encoding of the
6511 // same type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006512 getObjCEncodingForTypeImpl(T, S,
6513 ObjCEncOptions()
6514 .setExpandPointedToStructures()
6515 .setExpandStructures()
6516 .setIsOutermostType(),
6517 Field, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006518}
6519
Joe Groff98ac7d22014-07-07 22:25:15 +00006520void ASTContext::getObjCEncodingForPropertyType(QualType T,
6521 std::string& S) const {
6522 // Encode result type.
6523 // GCC has some special rules regarding encoding of properties which
6524 // closely resembles encoding of ivars.
Nico Weber2e9591c2019-05-14 12:32:37 +00006525 getObjCEncodingForTypeImpl(T, S,
6526 ObjCEncOptions()
6527 .setExpandPointedToStructures()
6528 .setExpandStructures()
6529 .setIsOutermostType()
6530 .setEncodingProperty(),
6531 /*Field=*/nullptr);
Joe Groff98ac7d22014-07-07 22:25:15 +00006532}
6533
John McCall393a78d2012-12-20 02:45:14 +00006534static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6535 BuiltinType::Kind kind) {
6536 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006537 case BuiltinType::Void: return 'v';
6538 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006539 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006540 case BuiltinType::Char_U:
6541 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006542 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006543 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006544 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006545 case BuiltinType::UInt: return 'I';
6546 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006547 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006548 case BuiltinType::UInt128: return 'T';
6549 case BuiltinType::ULongLong: return 'Q';
6550 case BuiltinType::Char_S:
6551 case BuiltinType::SChar: return 'c';
6552 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006553 case BuiltinType::WChar_S:
6554 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006555 case BuiltinType::Int: return 'i';
6556 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006557 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006558 case BuiltinType::LongLong: return 'q';
6559 case BuiltinType::Int128: return 't';
6560 case BuiltinType::Float: return 'f';
6561 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006562 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006563 case BuiltinType::NullPtr: return '*'; // like char*
6564
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006565 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006566 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006567 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006568 case BuiltinType::ShortAccum:
6569 case BuiltinType::Accum:
6570 case BuiltinType::LongAccum:
6571 case BuiltinType::UShortAccum:
6572 case BuiltinType::UAccum:
6573 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006574 case BuiltinType::ShortFract:
6575 case BuiltinType::Fract:
6576 case BuiltinType::LongFract:
6577 case BuiltinType::UShortFract:
6578 case BuiltinType::UFract:
6579 case BuiltinType::ULongFract:
6580 case BuiltinType::SatShortAccum:
6581 case BuiltinType::SatAccum:
6582 case BuiltinType::SatLongAccum:
6583 case BuiltinType::SatUShortAccum:
6584 case BuiltinType::SatUAccum:
6585 case BuiltinType::SatULongAccum:
6586 case BuiltinType::SatShortFract:
6587 case BuiltinType::SatFract:
6588 case BuiltinType::SatLongFract:
6589 case BuiltinType::SatUShortFract:
6590 case BuiltinType::SatUFract:
6591 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006592 // FIXME: potentially need @encodes for these!
6593 return ' ';
6594
6595 case BuiltinType::ObjCId:
6596 case BuiltinType::ObjCClass:
6597 case BuiltinType::ObjCSel:
6598 llvm_unreachable("@encoding ObjC primitive type");
6599
6600 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006601#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6602 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006603#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006604#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6605 case BuiltinType::Id:
6606#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006607 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006608 case BuiltinType::OCLClkEvent:
6609 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006610 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006611 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006612 case BuiltinType::Dependent:
6613#define BUILTIN_TYPE(KIND, ID)
6614#define PLACEHOLDER_TYPE(KIND, ID) \
6615 case BuiltinType::KIND:
6616#include "clang/AST/BuiltinTypes.def"
6617 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006618 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006619 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006620}
6621
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006622static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6623 EnumDecl *Enum = ET->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00006624
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006625 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6626 if (!Enum->isFixed())
6627 return 'i';
Fangrui Song6907ce22018-07-30 19:24:48 +00006628
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006629 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006630 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006631 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006632}
6633
Jay Foad39c79802011-01-12 09:06:06 +00006634static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006635 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006636 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006637 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006638 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6639 // The GNU runtime requires more information; bitfields are encoded as b,
6640 // then the offset (in bits) of the first element, then the type of the
6641 // bitfield, then the size in bits. For example, in this structure:
6642 //
6643 // struct
6644 // {
6645 // int integer;
6646 // int flags:2;
6647 // };
6648 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6649 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6650 // information is not especially sensible, but we're stuck with it for
6651 // compatibility with GCC, although providing it breaks anything that
6652 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006653 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006654 uint64_t Offset;
6655
6656 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6657 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6658 IVD);
6659 } else {
6660 const RecordDecl *RD = FD->getParent();
6661 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6662 Offset = RL.getFieldOffset(FD->getFieldIndex());
6663 }
6664
6665 S += llvm::utostr(Offset);
6666
Eugene Zelenko7855e772018-04-03 00:11:50 +00006667 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006668 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006669 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006670 const auto *BT = T->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006671 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6672 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006673 }
Richard Smithcaf33902011-10-10 18:28:20 +00006674 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006675}
6676
Daniel Dunbar07d07852009-10-18 21:17:35 +00006677// FIXME: Use SmallString for accumulating string.
Nico Weber2e9591c2019-05-14 12:32:37 +00006678void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
6679 const ObjCEncOptions Options,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006680 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006681 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006682 CanQualType CT = getCanonicalType(T);
6683 switch (CT->getTypeClass()) {
6684 case Type::Builtin:
6685 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006686 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006687 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006688 if (const auto *BT = dyn_cast<BuiltinType>(CT))
John McCall393a78d2012-12-20 02:45:14 +00006689 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6690 else
6691 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006692 return;
Mike Stump11289f42009-09-09 15:08:12 +00006693
John McCall393a78d2012-12-20 02:45:14 +00006694 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006695 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006696 S += 'j';
Nico Weber2e9591c2019-05-14 12:32:37 +00006697 getObjCEncodingForTypeImpl(CT->getElementType(), S, ObjCEncOptions(),
6698 /*Field=*/nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006699 return;
6700 }
John McCall393a78d2012-12-20 02:45:14 +00006701
6702 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006703 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006704 S += 'A';
Nico Weber2e9591c2019-05-14 12:32:37 +00006705 getObjCEncodingForTypeImpl(AT->getValueType(), S, ObjCEncOptions(),
6706 /*Field=*/nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006707 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006708 }
John McCall393a78d2012-12-20 02:45:14 +00006709
6710 // encoding for pointer or reference types.
6711 case Type::Pointer:
6712 case Type::LValueReference:
6713 case Type::RValueReference: {
6714 QualType PointeeTy;
6715 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006716 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006717 if (PT->isObjCSelType()) {
6718 S += ':';
6719 return;
6720 }
6721 PointeeTy = PT->getPointeeType();
6722 } else {
6723 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6724 }
6725
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006726 bool isReadOnly = false;
6727 // For historical/compatibility reasons, the read-only qualifier of the
6728 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6729 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006730 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006731 if (isa<TypedefType>(T.getTypePtr())) {
Nico Weber2e9591c2019-05-14 12:32:37 +00006732 if (Options.IsOutermostType() && T.isConstQualified()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006733 isReadOnly = true;
6734 S += 'r';
6735 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006736 } else if (Options.IsOutermostType()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006737 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006738 while (P->getAs<PointerType>())
6739 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006740 if (P.isConstQualified()) {
6741 isReadOnly = true;
6742 S += 'r';
6743 }
6744 }
6745 if (isReadOnly) {
6746 // Another legacy compatibility encoding. Some ObjC qualifier and type
6747 // combinations need to be rearranged.
6748 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006749 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006750 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006751 }
Mike Stump11289f42009-09-09 15:08:12 +00006752
Anders Carlssond8499822007-10-29 05:01:08 +00006753 if (PointeeTy->isCharType()) {
6754 // char pointer types should be encoded as '*' unless it is a
6755 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006756 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006757 S += '*';
6758 return;
6759 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006760 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006761 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6762 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6763 S += '#';
6764 return;
6765 }
6766 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6767 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6768 S += '@';
6769 return;
6770 }
6771 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006772 }
Anders Carlssond8499822007-10-29 05:01:08 +00006773 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006774 getLegacyIntegralTypeEncoding(PointeeTy);
6775
Nico Weber2e9591c2019-05-14 12:32:37 +00006776 ObjCEncOptions NewOptions;
6777 if (Options.ExpandPointedToStructures())
6778 NewOptions.setExpandStructures();
6779 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
6780 /*Field=*/nullptr, NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006781 return;
6782 }
John McCall393a78d2012-12-20 02:45:14 +00006783
6784 case Type::ConstantArray:
6785 case Type::IncompleteArray:
6786 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006787 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006788
Nico Weber2e9591c2019-05-14 12:32:37 +00006789 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006790 // Incomplete arrays are encoded as a pointer to the array element.
6791 S += '^';
6792
Nico Weber2e9591c2019-05-14 12:32:37 +00006793 getObjCEncodingForTypeImpl(
6794 AT->getElementType(), S,
6795 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006796 } else {
6797 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006798
Eugene Zelenko7855e772018-04-03 00:11:50 +00006799 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006800 S += llvm::utostr(CAT->getSize().getZExtValue());
6801 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006802 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006803 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6804 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006805 S += '0';
6806 }
Mike Stump11289f42009-09-09 15:08:12 +00006807
Nico Weberdf129332019-05-10 13:56:56 +00006808 getObjCEncodingForTypeImpl(
6809 AT->getElementType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006810 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
6811 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006812 S += ']';
6813 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006814 return;
6815 }
Mike Stump11289f42009-09-09 15:08:12 +00006816
John McCall393a78d2012-12-20 02:45:14 +00006817 case Type::FunctionNoProto:
6818 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006819 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006820 return;
Mike Stump11289f42009-09-09 15:08:12 +00006821
John McCall393a78d2012-12-20 02:45:14 +00006822 case Type::Record: {
6823 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006824 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006825 // Anonymous structures print as '?'
6826 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6827 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006828 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006829 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006830 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006831 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6832 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006833 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006834 } else {
6835 S += '?';
6836 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006837 if (Options.ExpandStructures()) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006838 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006839 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006840 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006841 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006842 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006843 if (FD) {
6844 S += '"';
6845 S += Field->getNameAsString();
6846 S += '"';
6847 }
Mike Stump11289f42009-09-09 15:08:12 +00006848
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006849 // Special case bit-fields.
6850 if (Field->isBitField()) {
Nico Weberdf129332019-05-10 13:56:56 +00006851 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006852 ObjCEncOptions().setExpandStructures(),
6853 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006854 } else {
6855 QualType qt = Field->getType();
6856 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00006857 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00006858 qt, S,
6859 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
6860 NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006861 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006862 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006863 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006864 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006865 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006866 return;
6867 }
Mike Stump11289f42009-09-09 15:08:12 +00006868
John McCall393a78d2012-12-20 02:45:14 +00006869 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006870 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006871 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Nico Weber2e9591c2019-05-14 12:32:37 +00006872 if (Options.EncodeBlockParameters()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006873 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00006874
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006875 S += '<';
6876 // Block return type
Nico Weber2e9591c2019-05-14 12:32:37 +00006877 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
6878 Options.forComponentType(), FD, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006879 // Block self
6880 S += "@?";
6881 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00006882 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006883 for (const auto &I : FPT->param_types())
Nico Weber2e9591c2019-05-14 12:32:37 +00006884 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
6885 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006886 }
6887 S += '>';
6888 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006889 return;
6890 }
Mike Stump11289f42009-09-09 15:08:12 +00006891
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006892 case Type::ObjCObject: {
6893 // hack to match legacy encoding of *id and *Class
6894 QualType Ty = getObjCObjectPointerType(CT);
6895 if (Ty->isObjCIdType()) {
6896 S += "{objc_object=}";
6897 return;
6898 }
6899 else if (Ty->isObjCClassType()) {
6900 S += "{objc_class=}";
6901 return;
6902 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006903 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006904 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006905 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006906
John McCall393a78d2012-12-20 02:45:14 +00006907 case Type::ObjCInterface: {
6908 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006909 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006910 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006911 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006912 S += OI->getObjCRuntimeNameAsString();
Nico Weber2e9591c2019-05-14 12:32:37 +00006913 if (Options.ExpandStructures()) {
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006914 S += '=';
6915 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6916 DeepCollectObjCIvars(OI, true, Ivars);
6917 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006918 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006919 if (Field->isBitField())
Nico Weberdf129332019-05-10 13:56:56 +00006920 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006921 ObjCEncOptions().setExpandStructures(),
6922 Field);
6923 else {
6924 ObjCEncOptions NewOptions = ObjCEncOptions().setExpandStructures();
6925 if (Options.EncodePointerToObjCTypedef())
6926 NewOptions.setEncodePointerToObjCTypedef();
6927 getObjCEncodingForTypeImpl(Field->getType(), S, NewOptions, FD,
6928 NotEncodedT);
6929 }
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006930 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006931 }
6932 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006933 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006934 }
Mike Stump11289f42009-09-09 15:08:12 +00006935
John McCall393a78d2012-12-20 02:45:14 +00006936 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006937 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006938 if (OPT->isObjCIdType()) {
6939 S += '@';
6940 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006941 }
Mike Stump11289f42009-09-09 15:08:12 +00006942
Steve Narofff0c86112009-10-28 22:03:49 +00006943 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6944 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
Nico Weberdf129332019-05-10 13:56:56 +00006945 // Since this is a binary compatibility issue, need to consult with
6946 // runtime folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006947 S += '#';
6948 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006949 }
Mike Stump11289f42009-09-09 15:08:12 +00006950
Chris Lattnere7cabb92009-07-13 00:10:46 +00006951 if (OPT->isObjCQualifiedIdType()) {
Nico Weber2e9591c2019-05-14 12:32:37 +00006952 getObjCEncodingForTypeImpl(
6953 getObjCIdType(), S,
6954 Options.keepingOnly(ObjCEncOptions()
6955 .setExpandPointedToStructures()
6956 .setExpandStructures()),
6957 FD);
6958 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006959 // Note that we do extended encoding of protocol qualifer list
6960 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006961 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006962 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006963 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006964 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006965 S += '>';
6966 }
6967 S += '"';
6968 }
6969 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006970 }
Mike Stump11289f42009-09-09 15:08:12 +00006971
Chris Lattnere7cabb92009-07-13 00:10:46 +00006972 QualType PointeeTy = OPT->getPointeeType();
Nico Weber2e9591c2019-05-14 12:32:37 +00006973 if (!Options.EncodingProperty() &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006974 isa<TypedefType>(PointeeTy.getTypePtr()) &&
Nico Weber2e9591c2019-05-14 12:32:37 +00006975 !Options.EncodePointerToObjCTypedef()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006976 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006977 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006978 // {...};
6979 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006980 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006981 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006982 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6983 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6984 DeepCollectObjCIvars(OI, true, Ivars);
6985 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006986 if (Ivars[i] == FD) {
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006987 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006988 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006989 S += '}';
6990 return;
6991 }
6992 }
6993 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006994 ObjCEncOptions NewOptions =
6995 ObjCEncOptions().setEncodePointerToObjCTypedef();
6996 if (Options.ExpandPointedToStructures())
6997 NewOptions.setExpandStructures();
6998 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions, /*Field=*/nullptr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006999 return;
7000 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007001
7002 S += '@';
Fangrui Song6907ce22018-07-30 19:24:48 +00007003 if (OPT->getInterfaceDecl() &&
Nico Weber2e9591c2019-05-14 12:32:37 +00007004 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007005 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007006 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00007007 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007008 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007009 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00007010 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00007011 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007012 S += '"';
7013 }
7014 return;
7015 }
Mike Stump11289f42009-09-09 15:08:12 +00007016
John McCalla9e6e8d2010-05-17 23:56:34 +00007017 // gcc just blithely ignores member pointers.
Nico Weber2e9591c2019-05-14 12:32:37 +00007018 // FIXME: we should do better than that. 'M' is available.
John McCall393a78d2012-12-20 02:45:14 +00007019 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007020 // This matches gcc's encoding, even though technically it is insufficient.
7021 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00007022 case Type::Vector:
7023 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007024 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007025 if (NotEncodedT)
7026 *NotEncodedT = T;
7027 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00007028
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007029 // We could see an undeduced auto type here during error recovery.
7030 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00007031 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007032 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00007033 return;
7034
Xiuli Pan9c14e282016-01-09 12:53:17 +00007035 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00007036#define ABSTRACT_TYPE(KIND, BASE)
7037#define TYPE(KIND, BASE)
7038#define DEPENDENT_TYPE(KIND, BASE) \
7039 case Type::KIND:
7040#define NON_CANONICAL_TYPE(KIND, BASE) \
7041 case Type::KIND:
7042#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7043 case Type::KIND:
7044#include "clang/AST/TypeNodes.def"
7045 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00007046 }
John McCall393a78d2012-12-20 02:45:14 +00007047 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00007048}
7049
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007050void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7051 std::string &S,
7052 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007053 bool includeVBases,
7054 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007055 assert(RDecl && "Expected non-null RecordDecl");
7056 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00007057 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007058 return;
7059
Eugene Zelenko7855e772018-04-03 00:11:50 +00007060 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007061 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7062 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7063
7064 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00007065 for (const auto &BI : CXXRec->bases()) {
7066 if (!BI.isVirtual()) {
7067 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007068 if (base->isEmpty())
7069 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007070 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007071 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7072 std::make_pair(offs, base));
7073 }
7074 }
7075 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007076
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007077 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00007078 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007079 uint64_t offs = layout.getFieldOffset(i);
7080 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00007081 std::make_pair(offs, Field));
7082 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007083 }
7084
7085 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00007086 for (const auto &BI : CXXRec->vbases()) {
7087 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007088 if (base->isEmpty())
7089 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007090 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00007091 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7092 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00007093 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7094 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007095 }
7096 }
7097
7098 CharUnits size;
7099 if (CXXRec) {
7100 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7101 } else {
7102 size = layout.getSize();
7103 }
7104
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007105#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007106 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007107#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007108 std::multimap<uint64_t, NamedDecl *>::iterator
7109 CurLayObj = FieldOrBaseOffsets.begin();
7110
Douglas Gregorf5d6c742012-04-27 22:30:01 +00007111 if (CXXRec && CXXRec->isDynamicClass() &&
7112 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007113 if (FD) {
7114 S += "\"_vptr$";
7115 std::string recname = CXXRec->getNameAsString();
7116 if (recname.empty()) recname = "?";
7117 S += recname;
7118 S += '"';
7119 }
7120 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007121#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007122 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007123#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007124 }
7125
7126 if (!RDecl->hasFlexibleArrayMember()) {
7127 // Mark the end of the structure.
7128 uint64_t offs = toBits(size);
7129 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00007130 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007131 }
7132
7133 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007134#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007135 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007136 if (CurOffs < CurLayObj->first) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007137 uint64_t padding = CurLayObj->first - CurOffs;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007138 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7139 // packing/alignment of members is different that normal, in which case
7140 // the encoding will be out-of-sync with the real layout.
7141 // If the runtime switches to just consider the size of types without
7142 // taking into account alignment, we could make padding explicit in the
7143 // encoding (e.g. using arrays of chars). The encoding strings would be
7144 // longer then though.
7145 CurOffs += padding;
7146 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007147#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007148
7149 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00007150 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007151 break; // reached end of structure.
7152
Eugene Zelenko7855e772018-04-03 00:11:50 +00007153 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007154 // We expand the bases without their virtual bases since those are going
7155 // in the initial structure. Note that this differs from gcc which
7156 // expands virtual bases each time one is encountered in the hierarchy,
7157 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007158 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7159 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007160 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007161#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007162 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007163#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007164 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007165 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007166 if (FD) {
7167 S += '"';
7168 S += field->getNameAsString();
7169 S += '"';
7170 }
7171
7172 if (field->isBitField()) {
7173 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007174#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00007175 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007176#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007177 } else {
7178 QualType qt = field->getType();
7179 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00007180 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00007181 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7182 FD, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007183#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007184 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007185#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007186 }
7187 }
7188 }
7189}
7190
Mike Stump11289f42009-09-09 15:08:12 +00007191void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00007192 std::string& S) const {
7193 if (QT & Decl::OBJC_TQ_In)
7194 S += 'n';
7195 if (QT & Decl::OBJC_TQ_Inout)
7196 S += 'N';
7197 if (QT & Decl::OBJC_TQ_Out)
7198 S += 'o';
7199 if (QT & Decl::OBJC_TQ_Bycopy)
7200 S += 'O';
7201 if (QT & Decl::OBJC_TQ_Byref)
7202 S += 'R';
7203 if (QT & Decl::OBJC_TQ_Oneway)
7204 S += 'V';
7205}
7206
Douglas Gregor3ea72692011-08-12 05:46:01 +00007207TypedefDecl *ASTContext::getObjCIdDecl() const {
7208 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007209 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00007210 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007211 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00007212 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00007213 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00007214}
7215
Douglas Gregor52e02802011-08-12 06:17:30 +00007216TypedefDecl *ASTContext::getObjCSelDecl() const {
7217 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007218 QualType T = getPointerType(ObjCBuiltinSelTy);
7219 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00007220 }
7221 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00007222}
7223
Douglas Gregor0a586182011-08-12 05:59:41 +00007224TypedefDecl *ASTContext::getObjCClassDecl() const {
7225 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007226 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00007227 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007228 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00007229 }
Douglas Gregor0a586182011-08-12 05:59:41 +00007230 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00007231}
7232
Douglas Gregord53ae832012-01-17 18:09:05 +00007233ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7234 if (!ObjCProtocolClassDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007235 ObjCProtocolClassDecl
7236 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregord53ae832012-01-17 18:09:05 +00007237 SourceLocation(),
7238 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00007239 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00007240 /*PrevDecl=*/nullptr,
Fangrui Song6907ce22018-07-30 19:24:48 +00007241 SourceLocation(), true);
Douglas Gregord53ae832012-01-17 18:09:05 +00007242 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007243
Douglas Gregord53ae832012-01-17 18:09:05 +00007244 return ObjCProtocolClassDecl;
7245}
7246
Meador Inge5d3fb222012-06-16 03:34:49 +00007247//===----------------------------------------------------------------------===//
7248// __builtin_va_list Construction Functions
7249//===----------------------------------------------------------------------===//
7250
Charles Davisc7d5c942015-09-17 20:55:33 +00007251static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7252 StringRef Name) {
7253 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007254 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00007255 return Context->buildImplicitTypedef(T, Name);
7256}
7257
7258static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7259 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7260}
7261
7262static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7263 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007264}
7265
7266static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7267 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007268 QualType T = Context->getPointerType(Context->VoidTy);
7269 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007270}
7271
Tim Northover9bb857a2013-01-31 12:13:10 +00007272static TypedefDecl *
7273CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007274 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007275 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007276 if (Context->getLangOpts().CPlusPlus) {
7277 // namespace std { struct __va_list {
7278 NamespaceDecl *NS;
7279 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7280 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007281 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007282 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007283 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007284 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007285 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007286 }
7287
7288 VaListTagDecl->startDefinition();
7289
7290 const size_t NumFields = 5;
7291 QualType FieldTypes[NumFields];
7292 const char *FieldNames[NumFields];
7293
7294 // void *__stack;
7295 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7296 FieldNames[0] = "__stack";
7297
7298 // void *__gr_top;
7299 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7300 FieldNames[1] = "__gr_top";
7301
7302 // void *__vr_top;
7303 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7304 FieldNames[2] = "__vr_top";
7305
7306 // int __gr_offs;
7307 FieldTypes[3] = Context->IntTy;
7308 FieldNames[3] = "__gr_offs";
7309
7310 // int __vr_offs;
7311 FieldTypes[4] = Context->IntTy;
7312 FieldNames[4] = "__vr_offs";
7313
7314 // Create fields
7315 for (unsigned i = 0; i < NumFields; ++i) {
7316 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7317 VaListTagDecl,
7318 SourceLocation(),
7319 SourceLocation(),
7320 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007321 FieldTypes[i], /*TInfo=*/nullptr,
7322 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007323 /*Mutable=*/false,
7324 ICIS_NoInit);
7325 Field->setAccess(AS_public);
7326 VaListTagDecl->addDecl(Field);
7327 }
7328 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007329 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007330 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007331
7332 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007333 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007334}
7335
Meador Inge5d3fb222012-06-16 03:34:49 +00007336static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7337 // typedef struct __va_list_tag {
7338 RecordDecl *VaListTagDecl;
7339
Alp Toker2dea15b2013-12-17 01:22:38 +00007340 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007341 VaListTagDecl->startDefinition();
7342
7343 const size_t NumFields = 5;
7344 QualType FieldTypes[NumFields];
7345 const char *FieldNames[NumFields];
7346
7347 // unsigned char gpr;
7348 FieldTypes[0] = Context->UnsignedCharTy;
7349 FieldNames[0] = "gpr";
7350
7351 // unsigned char fpr;
7352 FieldTypes[1] = Context->UnsignedCharTy;
7353 FieldNames[1] = "fpr";
7354
7355 // unsigned short reserved;
7356 FieldTypes[2] = Context->UnsignedShortTy;
7357 FieldNames[2] = "reserved";
7358
7359 // void* overflow_arg_area;
7360 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7361 FieldNames[3] = "overflow_arg_area";
7362
7363 // void* reg_save_area;
7364 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7365 FieldNames[4] = "reg_save_area";
7366
7367 // Create fields
7368 for (unsigned i = 0; i < NumFields; ++i) {
7369 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7370 SourceLocation(),
7371 SourceLocation(),
7372 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007373 FieldTypes[i], /*TInfo=*/nullptr,
7374 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007375 /*Mutable=*/false,
7376 ICIS_NoInit);
7377 Field->setAccess(AS_public);
7378 VaListTagDecl->addDecl(Field);
7379 }
7380 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007381 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007382 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7383
7384 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007385 TypedefDecl *VaListTagTypedefDecl =
7386 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7387
Meador Inge5d3fb222012-06-16 03:34:49 +00007388 QualType VaListTagTypedefType =
7389 Context->getTypedefType(VaListTagTypedefDecl);
7390
7391 // typedef __va_list_tag __builtin_va_list[1];
7392 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7393 QualType VaListTagArrayType
7394 = Context->getConstantArrayType(VaListTagTypedefType,
7395 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007396 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007397}
7398
7399static TypedefDecl *
7400CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007401 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007402 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007403 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007404 VaListTagDecl->startDefinition();
7405
7406 const size_t NumFields = 4;
7407 QualType FieldTypes[NumFields];
7408 const char *FieldNames[NumFields];
7409
7410 // unsigned gp_offset;
7411 FieldTypes[0] = Context->UnsignedIntTy;
7412 FieldNames[0] = "gp_offset";
7413
7414 // unsigned fp_offset;
7415 FieldTypes[1] = Context->UnsignedIntTy;
7416 FieldNames[1] = "fp_offset";
7417
7418 // void* overflow_arg_area;
7419 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7420 FieldNames[2] = "overflow_arg_area";
7421
7422 // void* reg_save_area;
7423 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7424 FieldNames[3] = "reg_save_area";
7425
7426 // Create fields
7427 for (unsigned i = 0; i < NumFields; ++i) {
7428 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7429 VaListTagDecl,
7430 SourceLocation(),
7431 SourceLocation(),
7432 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007433 FieldTypes[i], /*TInfo=*/nullptr,
7434 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007435 /*Mutable=*/false,
7436 ICIS_NoInit);
7437 Field->setAccess(AS_public);
7438 VaListTagDecl->addDecl(Field);
7439 }
7440 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007441 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007442 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7443
Richard Smith9b88a4c2015-07-27 05:40:23 +00007444 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007445
Richard Smith9b88a4c2015-07-27 05:40:23 +00007446 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007447 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007448 QualType VaListTagArrayType =
7449 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007450 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007451}
7452
7453static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7454 // typedef int __builtin_va_list[4];
7455 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007456 QualType IntArrayType =
7457 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007458 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007459}
7460
Logan Chien57086ce2012-10-10 06:56:20 +00007461static TypedefDecl *
7462CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007463 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007464 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007465 if (Context->getLangOpts().CPlusPlus) {
7466 // namespace std { struct __va_list {
7467 NamespaceDecl *NS;
7468 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7469 Context->getTranslationUnitDecl(),
7470 /*Inline*/false, SourceLocation(),
7471 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007472 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007473 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007474 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007475 }
7476
7477 VaListDecl->startDefinition();
7478
7479 // void * __ap;
7480 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7481 VaListDecl,
7482 SourceLocation(),
7483 SourceLocation(),
7484 &Context->Idents.get("__ap"),
7485 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007486 /*TInfo=*/nullptr,
7487 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007488 /*Mutable=*/false,
7489 ICIS_NoInit);
7490 Field->setAccess(AS_public);
7491 VaListDecl->addDecl(Field);
7492
7493 // };
7494 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007495 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007496
7497 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007498 QualType T = Context->getRecordType(VaListDecl);
7499 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007500}
7501
Ulrich Weigand47445072013-05-06 16:26:41 +00007502static TypedefDecl *
7503CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007504 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007505 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007506 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007507 VaListTagDecl->startDefinition();
7508
7509 const size_t NumFields = 4;
7510 QualType FieldTypes[NumFields];
7511 const char *FieldNames[NumFields];
7512
7513 // long __gpr;
7514 FieldTypes[0] = Context->LongTy;
7515 FieldNames[0] = "__gpr";
7516
7517 // long __fpr;
7518 FieldTypes[1] = Context->LongTy;
7519 FieldNames[1] = "__fpr";
7520
7521 // void *__overflow_arg_area;
7522 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7523 FieldNames[2] = "__overflow_arg_area";
7524
7525 // void *__reg_save_area;
7526 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7527 FieldNames[3] = "__reg_save_area";
7528
7529 // Create fields
7530 for (unsigned i = 0; i < NumFields; ++i) {
7531 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7532 VaListTagDecl,
7533 SourceLocation(),
7534 SourceLocation(),
7535 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007536 FieldTypes[i], /*TInfo=*/nullptr,
7537 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007538 /*Mutable=*/false,
7539 ICIS_NoInit);
7540 Field->setAccess(AS_public);
7541 VaListTagDecl->addDecl(Field);
7542 }
7543 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007544 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007545 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007546
Richard Smith9b88a4c2015-07-27 05:40:23 +00007547 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007548
7549 // typedef __va_list_tag __builtin_va_list[1];
7550 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007551 QualType VaListTagArrayType =
7552 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007553
Alp Toker56b5cc92013-12-15 10:36:26 +00007554 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007555}
7556
Meador Inge5d3fb222012-06-16 03:34:49 +00007557static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7558 TargetInfo::BuiltinVaListKind Kind) {
7559 switch (Kind) {
7560 case TargetInfo::CharPtrBuiltinVaList:
7561 return CreateCharPtrBuiltinVaListDecl(Context);
7562 case TargetInfo::VoidPtrBuiltinVaList:
7563 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007564 case TargetInfo::AArch64ABIBuiltinVaList:
7565 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007566 case TargetInfo::PowerABIBuiltinVaList:
7567 return CreatePowerABIBuiltinVaListDecl(Context);
7568 case TargetInfo::X86_64ABIBuiltinVaList:
7569 return CreateX86_64ABIBuiltinVaListDecl(Context);
7570 case TargetInfo::PNaClABIBuiltinVaList:
7571 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007572 case TargetInfo::AAPCSABIBuiltinVaList:
7573 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007574 case TargetInfo::SystemZBuiltinVaList:
7575 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007576 }
7577
7578 llvm_unreachable("Unhandled __builtin_va_list type kind");
7579}
7580
7581TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007582 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007583 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007584 assert(BuiltinVaListDecl->isImplicit());
7585 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007586
7587 return BuiltinVaListDecl;
7588}
7589
Richard Smith9b88a4c2015-07-27 05:40:23 +00007590Decl *ASTContext::getVaListTagDecl() const {
7591 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007592 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007593 if (!VaListTagDecl)
7594 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007595
Richard Smith9b88a4c2015-07-27 05:40:23 +00007596 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007597}
7598
Charles Davisc7d5c942015-09-17 20:55:33 +00007599TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7600 if (!BuiltinMSVaListDecl)
7601 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7602
7603 return BuiltinMSVaListDecl;
7604}
7605
Erich Keane41af9712018-04-16 21:30:08 +00007606bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7607 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7608}
7609
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007610void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007611 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007612 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007613
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007614 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007615}
7616
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007617/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007618/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007619TemplateName
7620ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7621 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007622 unsigned size = End - Begin;
7623 assert(size > 1 && "set is not overloaded!");
7624
7625 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7626 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007627 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007628
7629 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007630 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007631 NamedDecl *D = *I;
7632 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007633 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007634 (isa<UsingShadowDecl>(D) &&
7635 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7636 *Storage++ = D;
7637 }
7638
7639 return TemplateName(OT);
7640}
7641
Richard Smithb23c5e82019-05-09 03:31:27 +00007642/// Retrieve a template name representing an unqualified-id that has been
7643/// assumed to name a template for ADL purposes.
7644TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
7645 auto *OT = new (*this) AssumedTemplateStorage(Name);
7646 return TemplateName(OT);
7647}
7648
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007649/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007650/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007651TemplateName
7652ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7653 bool TemplateKeyword,
7654 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007655 assert(NNS && "Missing nested-name-specifier in qualified template name");
Fangrui Song6907ce22018-07-30 19:24:48 +00007656
Douglas Gregorc42075a2010-02-04 18:10:26 +00007657 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007658 llvm::FoldingSetNodeID ID;
7659 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7660
Craig Topper36250ad2014-05-12 05:36:57 +00007661 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007662 QualifiedTemplateName *QTN =
7663 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7664 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007665 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007666 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007667 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7668 }
7669
7670 return TemplateName(QTN);
7671}
7672
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007673/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007674/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007675TemplateName
7676ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7677 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007678 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007679 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007680
7681 llvm::FoldingSetNodeID ID;
7682 DependentTemplateName::Profile(ID, NNS, Name);
7683
Craig Topper36250ad2014-05-12 05:36:57 +00007684 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007685 DependentTemplateName *QTN =
7686 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7687
7688 if (QTN)
7689 return TemplateName(QTN);
7690
7691 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7692 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007693 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007694 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007695 } else {
7696 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007697 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007698 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007699 DependentTemplateName *CheckQTN =
7700 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7701 assert(!CheckQTN && "Dependent type name canonicalization broken");
7702 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007703 }
7704
7705 DependentTemplateNames.InsertNode(QTN, InsertPos);
7706 return TemplateName(QTN);
7707}
7708
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007709/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007710/// template name such as \c MetaFun::template operator+.
Fangrui Song6907ce22018-07-30 19:24:48 +00007711TemplateName
Douglas Gregor71395fa2009-11-04 00:56:37 +00007712ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007713 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007714 assert((!NNS || NNS->isDependent()) &&
7715 "Nested name specifier must be dependent");
Fangrui Song6907ce22018-07-30 19:24:48 +00007716
Douglas Gregor71395fa2009-11-04 00:56:37 +00007717 llvm::FoldingSetNodeID ID;
7718 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007719
7720 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007721 DependentTemplateName *QTN
7722 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007723
Douglas Gregor71395fa2009-11-04 00:56:37 +00007724 if (QTN)
7725 return TemplateName(QTN);
Fangrui Song6907ce22018-07-30 19:24:48 +00007726
Douglas Gregor71395fa2009-11-04 00:56:37 +00007727 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7728 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007729 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007730 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007731 } else {
7732 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007733 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007734 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007735
Douglas Gregorc42075a2010-02-04 18:10:26 +00007736 DependentTemplateName *CheckQTN
7737 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7738 assert(!CheckQTN && "Dependent template name canonicalization broken");
7739 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007740 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007741
Douglas Gregor71395fa2009-11-04 00:56:37 +00007742 DependentTemplateNames.InsertNode(QTN, InsertPos);
7743 return TemplateName(QTN);
7744}
7745
Fangrui Song6907ce22018-07-30 19:24:48 +00007746TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007747ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7748 TemplateName replacement) const {
7749 llvm::FoldingSetNodeID ID;
7750 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007751
7752 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007753 SubstTemplateTemplateParmStorage *subst
7754 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007755
John McCalld9dfe3a2011-06-30 08:33:18 +00007756 if (!subst) {
7757 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7758 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7759 }
7760
7761 return TemplateName(subst);
7762}
7763
Fangrui Song6907ce22018-07-30 19:24:48 +00007764TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007765ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7766 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007767 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007768 llvm::FoldingSetNodeID ID;
7769 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007770
7771 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007772 SubstTemplateTemplateParmPackStorage *Subst
7773 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007774
Douglas Gregor5590be02011-01-15 06:45:20 +00007775 if (!Subst) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007776 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007777 ArgPack.pack_size(),
7778 ArgPack.pack_begin());
7779 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7780 }
7781
7782 return TemplateName(Subst);
7783}
7784
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007785/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007786/// TargetInfo, produce the corresponding type. The unsigned @p Type
7787/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007788CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007789 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007790 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007791 case TargetInfo::SignedChar: return SignedCharTy;
7792 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007793 case TargetInfo::SignedShort: return ShortTy;
7794 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7795 case TargetInfo::SignedInt: return IntTy;
7796 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7797 case TargetInfo::SignedLong: return LongTy;
7798 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7799 case TargetInfo::SignedLongLong: return LongLongTy;
7800 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7801 }
7802
David Blaikie83d382b2011-09-23 05:06:16 +00007803 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007804}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007805
7806//===----------------------------------------------------------------------===//
7807// Type Predicates.
7808//===----------------------------------------------------------------------===//
7809
Fariborz Jahanian96207692009-02-18 21:49:28 +00007810/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7811/// garbage collection attribute.
7812///
John McCall553d45a2011-01-12 00:34:59 +00007813Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007814 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007815 return Qualifiers::GCNone;
7816
Erik Pilkingtonfa983902018-10-30 20:31:30 +00007817 assert(getLangOpts().ObjC);
John McCall553d45a2011-01-12 00:34:59 +00007818 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7819
7820 // Default behaviour under objective-C's gc is for ObjC pointers
7821 // (or pointers to them) be treated as though they were declared
7822 // as __strong.
7823 if (GCAttrs == Qualifiers::GCNone) {
7824 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7825 return Qualifiers::Strong;
7826 else if (Ty->isPointerType())
7827 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7828 } else {
7829 // It's not valid to set GC attributes on anything that isn't a
7830 // pointer.
7831#ifndef NDEBUG
7832 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007833 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007834 CT = AT->getElementType();
7835 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7836#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007837 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007838 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007839}
7840
Chris Lattner49af6a42008-04-07 06:51:04 +00007841//===----------------------------------------------------------------------===//
7842// Type Compatibility Testing
7843//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007844
Mike Stump11289f42009-09-09 15:08:12 +00007845/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007846/// compatible.
7847static bool areCompatVectorTypes(const VectorType *LHS,
7848 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007849 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007850 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007851 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007852}
7853
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007854bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7855 QualType SecondVec) {
7856 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7857 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7858
7859 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7860 return true;
7861
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007862 // Treat Neon vector types and most AltiVec vector types as if they are the
7863 // equivalent GCC vector types.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007864 const auto *First = FirstVec->getAs<VectorType>();
7865 const auto *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007866 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007867 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007868 First->getVectorKind() != VectorType::AltiVecPixel &&
7869 First->getVectorKind() != VectorType::AltiVecBool &&
7870 Second->getVectorKind() != VectorType::AltiVecPixel &&
7871 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007872 return true;
7873
7874 return false;
7875}
7876
Steve Naroff8e6aee52009-07-23 01:01:38 +00007877//===----------------------------------------------------------------------===//
7878// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7879//===----------------------------------------------------------------------===//
7880
7881/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7882/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007883bool
7884ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7885 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007886 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007887 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007888 for (auto *PI : rProto->protocols())
7889 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007890 return true;
7891 return false;
7892}
7893
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007894/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7895/// Class<pr1, ...>.
Fangrui Song6907ce22018-07-30 19:24:48 +00007896bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007897 QualType rhs) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007898 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7899 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007900 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fangrui Song6907ce22018-07-30 19:24:48 +00007901
Aaron Ballman83731462014-03-17 16:14:00 +00007902 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007903 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007904 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007905 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7906 match = true;
7907 break;
7908 }
7909 }
7910 if (!match)
7911 return false;
7912 }
7913 return true;
7914}
7915
Steve Naroff8e6aee52009-07-23 01:01:38 +00007916/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7917/// ObjCQualifiedIDType.
7918bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7919 bool compare) {
7920 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007921 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007922 lhs->isObjCIdType() || lhs->isObjCClassType())
7923 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007924 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007925 rhs->isObjCIdType() || rhs->isObjCClassType())
7926 return true;
7927
7928 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007929 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007930
Steve Naroff8e6aee52009-07-23 01:01:38 +00007931 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007932
Steve Naroff8e6aee52009-07-23 01:01:38 +00007933 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007934 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007935 // make sure we check the class hierarchy.
7936 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007937 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007938 // when comparing an id<P> on lhs with a static type on rhs,
7939 // see if static class implements all of id's protocols, directly or
7940 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007941 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007942 return false;
7943 }
7944 }
7945 // If there are no qualifiers and no interface, we have an 'id'.
7946 return true;
7947 }
Mike Stump11289f42009-09-09 15:08:12 +00007948 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007949 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007950 bool match = false;
7951
7952 // when comparing an id<P> on lhs with a static type on rhs,
7953 // see if static class implements all of id's protocols, directly or
7954 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007955 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007956 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7957 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7958 match = true;
7959 break;
7960 }
7961 }
Mike Stump11289f42009-09-09 15:08:12 +00007962 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007963 // make sure we check the class hierarchy.
7964 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007965 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007966 // when comparing an id<P> on lhs with a static type on rhs,
7967 // see if static class implements all of id's protocols, directly or
7968 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007969 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007970 match = true;
7971 break;
7972 }
7973 }
7974 }
7975 if (!match)
7976 return false;
7977 }
Mike Stump11289f42009-09-09 15:08:12 +00007978
Steve Naroff8e6aee52009-07-23 01:01:38 +00007979 return true;
7980 }
Mike Stump11289f42009-09-09 15:08:12 +00007981
Steve Naroff8e6aee52009-07-23 01:01:38 +00007982 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7983 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7984
Mike Stump11289f42009-09-09 15:08:12 +00007985 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007986 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007987 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007988 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007989 bool match = false;
7990
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007991 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007992 // see if static class implements all of id's protocols, directly or
7993 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007994 // First, lhs protocols in the qualifier list must be found, direct
7995 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007996 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007997 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7998 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7999 match = true;
8000 break;
8001 }
8002 }
8003 if (!match)
8004 return false;
8005 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008006
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008007 // Static class's protocols, or its super class or category protocols
8008 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8009 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
8010 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8011 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8012 // This is rather dubious but matches gcc's behavior. If lhs has
8013 // no type qualifier and its class has no static protocol(s)
8014 // assume that it is mismatch.
8015 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
8016 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00008017 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008018 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00008019 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008020 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8021 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8022 match = true;
8023 break;
8024 }
8025 }
8026 if (!match)
8027 return false;
8028 }
8029 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00008030 return true;
8031 }
8032 return false;
8033}
8034
Eli Friedman47f77112008-08-22 00:56:42 +00008035/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00008036/// compatible for assignment from RHS to LHS. This handles validation of any
8037/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00008038bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8039 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00008040 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8041 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8042
Steve Naroff1329fa02009-07-15 18:40:39 +00008043 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00008044 if (LHS->isObjCUnqualifiedIdOrClass() ||
8045 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00008046 return true;
8047
Douglas Gregorab209d82015-07-07 03:58:42 +00008048 // Function object that propagates a successful result or handles
8049 // __kindof types.
8050 auto finish = [&](bool succeeded) -> bool {
8051 if (succeeded)
8052 return true;
8053
8054 if (!RHS->isKindOfType())
8055 return false;
8056
8057 // Strip off __kindof and protocol qualifiers, then check whether
8058 // we can assign the other way.
8059 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8060 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8061 };
8062
8063 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8064 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8065 QualType(RHSOPT,0),
8066 false));
8067 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008068
Douglas Gregorab209d82015-07-07 03:58:42 +00008069 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8070 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
8071 QualType(RHSOPT,0)));
8072 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008073
John McCall8b07ec22010-05-15 11:32:37 +00008074 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00008075 if (LHS->getInterface() && RHS->getInterface()) {
8076 return finish(canAssignObjCInterfaces(LHS, RHS));
8077 }
Mike Stump11289f42009-09-09 15:08:12 +00008078
Steve Naroff8e6aee52009-07-23 01:01:38 +00008079 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008080}
8081
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008082/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Fangrui Song6907ce22018-07-30 19:24:48 +00008083/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008084/// arguments in block literals. When passed as arguments, passing 'A*' where
8085/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8086/// not OK. For the return type, the opposite is not OK.
8087bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8088 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008089 const ObjCObjectPointerType *RHSOPT,
8090 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008091
8092 // Function object that propagates a successful result or handles
8093 // __kindof types.
8094 auto finish = [&](bool succeeded) -> bool {
8095 if (succeeded)
8096 return true;
8097
8098 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8099 if (!Expected->isKindOfType())
8100 return false;
8101
8102 // Strip off __kindof and protocol qualifiers, then check whether
8103 // we can assign the other way.
8104 return canAssignObjCInterfacesInBlockPointer(
8105 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8106 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8107 BlockReturnType);
8108 };
8109
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008110 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008111 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008112
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008113 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008114 return finish(RHSOPT->isObjCBuiltinType() ||
8115 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008116 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008117
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008118 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00008119 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8120 QualType(RHSOPT,0),
8121 false));
Fangrui Song6907ce22018-07-30 19:24:48 +00008122
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008123 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8124 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8125 if (LHS && RHS) { // We have 2 user-defined types.
8126 if (LHS != RHS) {
8127 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008128 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008129 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008130 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008131 }
8132 else
8133 return true;
8134 }
8135 return false;
8136}
8137
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008138/// Comparison routine for Objective-C protocols to be used with
8139/// llvm::array_pod_sort.
8140static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8141 ObjCProtocolDecl * const *rhs) {
8142 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008143}
8144
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008145/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008146/// of protocols inherited from two distinct objective-c pointer objects with
8147/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008148/// It is used to build composite qualifier list of the composite type of
8149/// the conditional expression involving two objective-c pointer objects.
Fangrui Song6907ce22018-07-30 19:24:48 +00008150static
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008151void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008152 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008153 const ObjCObjectPointerType *LHSOPT,
8154 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008155 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008156
John McCall8b07ec22010-05-15 11:32:37 +00008157 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8158 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8159 assert(LHS->getInterface() && "LHS must have an interface base");
8160 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008161
8162 // Add all of the protocols for the LHS.
8163 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8164
8165 // Start with the protocol qualifiers.
8166 for (auto proto : LHS->quals()) {
8167 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008168 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008169
8170 // Also add the protocols associated with the LHS interface.
8171 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8172
Raphael Isemannb23ccec2018-12-10 12:37:46 +00008173 // Add all of the protocols for the RHS.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008174 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8175
8176 // Start with the protocol qualifiers.
8177 for (auto proto : RHS->quals()) {
8178 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008179 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008180
8181 // Also add the protocols associated with the RHS interface.
8182 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8183
8184 // Compute the intersection of the collected protocol sets.
8185 for (auto proto : LHSProtocolSet) {
8186 if (RHSProtocolSet.count(proto))
8187 IntersectionSet.push_back(proto);
8188 }
8189
8190 // Compute the set of protocols that is implied by either the common type or
8191 // the protocols within the intersection.
8192 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8193 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8194
8195 // Remove any implied protocols from the list of inherited protocols.
8196 if (!ImpliedProtocols.empty()) {
8197 IntersectionSet.erase(
8198 std::remove_if(IntersectionSet.begin(),
8199 IntersectionSet.end(),
8200 [&](ObjCProtocolDecl *proto) -> bool {
8201 return ImpliedProtocols.count(proto) > 0;
8202 }),
8203 IntersectionSet.end());
8204 }
8205
8206 // Sort the remaining protocols by name.
8207 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8208 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008209}
8210
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008211/// Determine whether the first type is a subtype of the second.
8212static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8213 QualType rhs) {
8214 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008215 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8216 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008217 if (lhsOPT && rhsOPT)
8218 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8219
8220 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008221 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8222 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008223 if (lhsBlock && rhsBlock)
8224 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8225
8226 // If either is an unqualified 'id' and the other is a block, it's
8227 // acceptable.
8228 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8229 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8230 return true;
8231
8232 return false;
8233}
8234
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008235// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008236static bool sameObjCTypeArgs(ASTContext &ctx,
8237 const ObjCInterfaceDecl *iface,
8238 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00008239 ArrayRef<QualType> rhsArgs,
8240 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008241 if (lhsArgs.size() != rhsArgs.size())
8242 return false;
8243
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008244 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008245 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008246 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8247 continue;
8248
8249 switch (typeParams->begin()[i]->getVariance()) {
8250 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00008251 if (!stripKindOf ||
8252 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8253 rhsArgs[i].stripObjCKindOfType(ctx))) {
8254 return false;
8255 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008256 break;
8257
8258 case ObjCTypeParamVariance::Covariant:
8259 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8260 return false;
8261 break;
8262
8263 case ObjCTypeParamVariance::Contravariant:
8264 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8265 return false;
8266 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00008267 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008268 }
8269
8270 return true;
8271}
8272
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008273QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008274 const ObjCObjectPointerType *Lptr,
8275 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008276 const ObjCObjectType *LHS = Lptr->getObjectType();
8277 const ObjCObjectType *RHS = Rptr->getObjectType();
8278 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8279 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008280
8281 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008282 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008283
Manman Renc46f7d12016-05-06 19:35:02 +00008284 // When either LHS or RHS is a kindof type, we should return a kindof type.
8285 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8286 // kindof(A).
8287 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8288
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008289 // Follow the left-hand side up the class hierarchy until we either hit a
8290 // root or find the RHS. Record the ancestors in case we don't find it.
8291 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8292 LHSAncestors;
8293 while (true) {
8294 // Record this ancestor. We'll need this if the common type isn't in the
8295 // path from the LHS to the root.
8296 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008297
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008298 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8299 // Get the type arguments.
8300 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8301 bool anyChanges = false;
8302 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8303 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008304 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8305 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008306 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008307 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008308 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8309 // If only one has type arguments, the result will not have type
8310 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008311 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008312 anyChanges = true;
8313 }
8314
8315 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008316 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008317 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8318 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008319 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008320 anyChanges = true;
8321
8322 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008323 // If we need to return a kindof type but LHS is not a kindof type, we
8324 // build a new result type.
8325 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008326 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008327 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008328 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008329 return getObjCObjectPointerType(Result);
8330 }
8331
8332 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008333 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008334
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008335 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008336 QualType LHSSuperType = LHS->getSuperClassType();
8337 if (LHSSuperType.isNull())
8338 break;
8339
8340 LHS = LHSSuperType->castAs<ObjCObjectType>();
8341 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008342
8343 // We didn't find anything by following the LHS to its root; now check
8344 // the RHS against the cached set of ancestors.
8345 while (true) {
8346 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8347 if (KnownLHS != LHSAncestors.end()) {
8348 LHS = KnownLHS->second;
8349
8350 // Get the type arguments.
8351 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8352 bool anyChanges = false;
8353 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8354 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008355 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8356 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008357 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008358 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008359 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8360 // If only one has type arguments, the result will not have type
8361 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008362 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008363 anyChanges = true;
8364 }
8365
8366 // Compute the intersection of protocols.
8367 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8368 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8369 Protocols);
8370 if (!Protocols.empty())
8371 anyChanges = true;
8372
Manman Renc46f7d12016-05-06 19:35:02 +00008373 // If we need to return a kindof type but RHS is not a kindof type, we
8374 // build a new result type.
8375 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008376 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008377 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008378 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008379 return getObjCObjectPointerType(Result);
8380 }
8381
8382 return getObjCObjectPointerType(QualType(RHS, 0));
8383 }
8384
8385 // Find the superclass of the RHS.
8386 QualType RHSSuperType = RHS->getSuperClassType();
8387 if (RHSSuperType.isNull())
8388 break;
8389
8390 RHS = RHSSuperType->castAs<ObjCObjectType>();
8391 }
8392
Eugene Zelenko7855e772018-04-03 00:11:50 +00008393 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008394}
8395
John McCall8b07ec22010-05-15 11:32:37 +00008396bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8397 const ObjCObjectType *RHS) {
8398 assert(LHS->getInterface() && "LHS is not an interface type");
8399 assert(RHS->getInterface() && "RHS is not an interface type");
8400
Chris Lattner49af6a42008-04-07 06:51:04 +00008401 // Verify that the base decls are compatible: the RHS must be a subclass of
8402 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008403 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8404 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8405 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008406 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008407
Douglas Gregore83b9562015-07-07 03:57:53 +00008408 // If the LHS has protocol qualifiers, determine whether all of them are
8409 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8410 // LHS).
8411 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008412 // OK if conversion of LHS to SuperClass results in narrowing of types
8413 // ; i.e., SuperClass may implement at least one of the protocols
8414 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8415 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8416 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8417 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8418 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8419 // qualifiers.
8420 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008421 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008422 // If there is no protocols associated with RHS, it is not a match.
8423 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008424 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008425
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008426 for (const auto *LHSProto : LHS->quals()) {
8427 bool SuperImplementsProtocol = false;
8428 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8429 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8430 SuperImplementsProtocol = true;
8431 break;
8432 }
8433 if (!SuperImplementsProtocol)
8434 return false;
8435 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008436 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008437
8438 // If the LHS is specialized, we may need to check type arguments.
8439 if (LHS->isSpecialized()) {
8440 // Follow the superclass chain until we've matched the LHS class in the
8441 // hierarchy. This substitutes type arguments through.
8442 const ObjCObjectType *RHSSuper = RHS;
8443 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8444 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8445
8446 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008447 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008448 !sameObjCTypeArgs(*this, LHS->getInterface(),
8449 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008450 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008451 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008452 }
8453 }
8454
8455 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008456}
8457
Steve Naroffb7605152009-02-12 17:52:19 +00008458bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8459 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008460 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8461 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008462
Steve Naroff7cae42b2009-07-10 23:34:53 +00008463 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008464 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008465
8466 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8467 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008468}
8469
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008470bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8471 return canAssignObjCInterfaces(
8472 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8473 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8474}
8475
Mike Stump11289f42009-09-09 15:08:12 +00008476/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008477/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008478/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008479/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008480bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8481 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008482 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008483 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008484
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008485 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008486}
8487
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008488bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008489 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008490}
8491
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008492bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8493 return !mergeTypes(LHS, RHS, true).isNull();
8494}
8495
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008496/// mergeTransparentUnionType - if T is a transparent union type and a member
8497/// of T is compatible with SubType, return the merged type, else return
8498/// QualType()
8499QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8500 bool OfBlockPointer,
8501 bool Unqualified) {
8502 if (const RecordType *UT = T->getAsUnionType()) {
8503 RecordDecl *UD = UT->getDecl();
8504 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008505 for (const auto *I : UD->fields()) {
8506 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008507 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8508 if (!MT.isNull())
8509 return MT;
8510 }
8511 }
8512 }
8513
Eugene Zelenko7855e772018-04-03 00:11:50 +00008514 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008515}
8516
Alp Toker9cacbab2014-01-20 20:26:09 +00008517/// mergeFunctionParameterTypes - merge two types which appear as function
8518/// parameter types
8519QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8520 bool OfBlockPointer,
8521 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008522 // GNU extension: two types are compatible if they appear as a function
8523 // argument, one of the types is a transparent union type and the other
8524 // type is compatible with a union member
8525 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8526 Unqualified);
8527 if (!lmerge.isNull())
8528 return lmerge;
8529
8530 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8531 Unqualified);
8532 if (!rmerge.isNull())
8533 return rmerge;
8534
8535 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8536}
8537
Fangrui Song6907ce22018-07-30 19:24:48 +00008538QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008539 bool OfBlockPointer,
8540 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008541 const auto *lbase = lhs->getAs<FunctionType>();
8542 const auto *rbase = rhs->getAs<FunctionType>();
8543 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8544 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008545 bool allLTypes = true;
8546 bool allRTypes = true;
8547
8548 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008549 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008550 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008551 QualType RHS = rbase->getReturnType();
8552 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008553 bool UnqualifiedResult = Unqualified;
8554 if (!UnqualifiedResult)
8555 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008556 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008557 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008558 else
Alp Toker314cc812014-01-25 16:55:45 +00008559 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008560 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008561 if (retType.isNull())
8562 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00008563
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008564 if (Unqualified)
8565 retType = retType.getUnqualifiedType();
8566
Alp Toker314cc812014-01-25 16:55:45 +00008567 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8568 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008569 if (Unqualified) {
8570 LRetType = LRetType.getUnqualifiedType();
8571 RRetType = RRetType.getUnqualifiedType();
8572 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008573
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008574 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008575 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008576 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008577 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008578
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008579 // FIXME: double check this
8580 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8581 // rbase->getRegParmAttr() != 0 &&
8582 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008583 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8584 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008585
Douglas Gregor8c940862010-01-18 17:14:39 +00008586 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008587 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008588 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008589
John McCall8c6b56f2010-12-15 01:06:38 +00008590 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008591 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008592 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008593 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008594 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008595
John McCall31168b02011-06-15 23:02:42 +00008596 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008597 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008598 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008599 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008600 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008601 return {};
John McCall31168b02011-06-15 23:02:42 +00008602
John McCall8c6b56f2010-12-15 01:06:38 +00008603 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8604 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008605
Rafael Espindola8778c282012-11-29 16:09:03 +00008606 if (lbaseInfo.getNoReturn() != NoReturn)
8607 allLTypes = false;
8608 if (rbaseInfo.getNoReturn() != NoReturn)
8609 allRTypes = false;
8610
John McCall31168b02011-06-15 23:02:42 +00008611 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008612
Eli Friedman47f77112008-08-22 00:56:42 +00008613 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008614 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8615 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008616 // Compatible functions must have the same number of parameters
8617 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008618 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008619
8620 // Variadic and non-variadic functions aren't compatible
8621 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008622 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008623
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008624 if (lproto->getMethodQuals() != rproto->getMethodQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008625 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008626
Akira Hatanaka98a49332017-09-22 00:41:05 +00008627 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8628 bool canUseLeft, canUseRight;
8629 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8630 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008631 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008632
Akira Hatanaka98a49332017-09-22 00:41:05 +00008633 if (!canUseLeft)
8634 allLTypes = false;
8635 if (!canUseRight)
8636 allRTypes = false;
8637
Alp Toker601b22c2014-01-21 23:35:24 +00008638 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008639 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008640 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8641 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8642 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8643 QualType paramType = mergeFunctionParameterTypes(
8644 lParamType, rParamType, OfBlockPointer, Unqualified);
8645 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008646 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008647
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008648 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008649 paramType = paramType.getUnqualifiedType();
8650
8651 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008652 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008653 lParamType = lParamType.getUnqualifiedType();
8654 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008655 }
Alp Toker601b22c2014-01-21 23:35:24 +00008656
8657 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008658 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008659 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008660 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008661 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008662
Eli Friedman47f77112008-08-22 00:56:42 +00008663 if (allLTypes) return lhs;
8664 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008665
8666 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8667 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008668 EPI.ExtParameterInfos =
8669 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008670 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008671 }
8672
8673 if (lproto) allRTypes = false;
8674 if (rproto) allLTypes = false;
8675
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008676 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008677 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008678 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008679 if (proto->isVariadic())
8680 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008681 // Check that the types are compatible with the types that
8682 // would result from default argument promotions (C99 6.7.5.3p15).
8683 // The only types actually affected are promotable integer
8684 // types and floats, which would be passed as a different
8685 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008686 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8687 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008688
Eli Friedman448ce402012-08-30 00:44:15 +00008689 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008690 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008691 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008692 paramTy = Enum->getDecl()->getIntegerType();
8693 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008694 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008695 }
Alp Toker601b22c2014-01-21 23:35:24 +00008696
8697 if (paramTy->isPromotableIntegerType() ||
8698 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008699 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008700 }
8701
8702 if (allLTypes) return lhs;
8703 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008704
8705 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8706 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008707 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008708 }
8709
8710 if (allLTypes) return lhs;
8711 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008712 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008713}
8714
John McCall433c2e62013-03-21 00:10:07 +00008715/// Given that we have an enum type and a non-enum type, try to merge them.
8716static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8717 QualType other, bool isBlockReturnType) {
8718 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8719 // a signed integer type, or an unsigned integer type.
8720 // Compatibility is based on the underlying type, not the promotion
8721 // type.
8722 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008723 if (underlyingType.isNull())
8724 return {};
John McCall433c2e62013-03-21 00:10:07 +00008725 if (Context.hasSameType(underlyingType, other))
8726 return other;
8727
8728 // In block return types, we're more permissive and accept any
8729 // integral type of the same size.
8730 if (isBlockReturnType && other->isIntegerType() &&
8731 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8732 return other;
8733
Eugene Zelenko7855e772018-04-03 00:11:50 +00008734 return {};
John McCall433c2e62013-03-21 00:10:07 +00008735}
8736
Fangrui Song6907ce22018-07-30 19:24:48 +00008737QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008738 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008739 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008740 // C++ [expr]: If an expression initially has the type "reference to T", the
8741 // type is adjusted to "T" prior to any further analysis, the expression
8742 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008743 // expression is an lvalue unless the reference is an rvalue reference and
8744 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008745 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8746 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008747
8748 if (Unqualified) {
8749 LHS = LHS.getUnqualifiedType();
8750 RHS = RHS.getUnqualifiedType();
8751 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008752
Eli Friedman47f77112008-08-22 00:56:42 +00008753 QualType LHSCan = getCanonicalType(LHS),
8754 RHSCan = getCanonicalType(RHS);
8755
8756 // If two types are identical, they are compatible.
8757 if (LHSCan == RHSCan)
8758 return LHS;
8759
John McCall8ccfcb52009-09-24 19:53:00 +00008760 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008761 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8762 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008763 if (LQuals != RQuals) {
8764 // If any of these qualifiers are different, we have a type
8765 // mismatch.
8766 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008767 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008768 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8769 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008770 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008771
8772 // Exactly one GC qualifier difference is allowed: __strong is
8773 // okay if the other type has no GC qualifier but is an Objective
8774 // C object pointer (i.e. implicitly strong by default). We fix
8775 // this by pretending that the unqualified type was actually
8776 // qualified __strong.
8777 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8778 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8779 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8780
8781 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008782 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008783
8784 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8785 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8786 }
8787 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8788 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8789 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008790 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008791 }
8792
8793 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008794
Eli Friedmandcca6332009-06-01 01:22:52 +00008795 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8796 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008797
Chris Lattnerfd652912008-01-14 05:45:46 +00008798 // We want to consider the two function types to be the same for these
8799 // comparisons, just force one to the other.
8800 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8801 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008802
8803 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008804 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8805 LHSClass = Type::ConstantArray;
8806 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8807 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008808
John McCall8b07ec22010-05-15 11:32:37 +00008809 // ObjCInterfaces are just specialized ObjCObjects.
8810 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8811 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8812
Nate Begemance4d7fc2008-04-18 23:10:10 +00008813 // Canonicalize ExtVector -> Vector.
8814 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8815 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008816
Chris Lattner95554662008-04-07 05:43:21 +00008817 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008818 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008819 // Note that we only have special rules for turning block enum
8820 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008821 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008822 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008823 }
John McCall9dd450b2009-09-21 23:43:11 +00008824 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008825 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008826 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008827 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008828 if (OfBlockPointer && !BlockReturnType) {
8829 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8830 return LHS;
8831 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8832 return RHS;
8833 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008834
Eugene Zelenko7855e772018-04-03 00:11:50 +00008835 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008836 }
Eli Friedman47f77112008-08-22 00:56:42 +00008837
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008838 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008839 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008840#define TYPE(Class, Base)
8841#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008842#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008843#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8844#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8845#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008846 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008847
Richard Smith27d807c2013-04-30 13:56:41 +00008848 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008849 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008850 case Type::LValueReference:
8851 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008852 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008853 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008854
John McCall8b07ec22010-05-15 11:32:37 +00008855 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008856 case Type::IncompleteArray:
8857 case Type::VariableArray:
8858 case Type::FunctionProto:
8859 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008860 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008861
Chris Lattnerfd652912008-01-14 05:45:46 +00008862 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008863 {
8864 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008865 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8866 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008867 if (Unqualified) {
8868 LHSPointee = LHSPointee.getUnqualifiedType();
8869 RHSPointee = RHSPointee.getUnqualifiedType();
8870 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008871 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008872 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008873 if (ResultType.isNull())
8874 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008875 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008876 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008877 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008878 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008879 return getPointerType(ResultType);
8880 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008881 case Type::BlockPointer:
8882 {
8883 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008884 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8885 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008886 if (Unqualified) {
8887 LHSPointee = LHSPointee.getUnqualifiedType();
8888 RHSPointee = RHSPointee.getUnqualifiedType();
8889 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008890 if (getLangOpts().OpenCL) {
8891 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8892 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8893 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8894 // 6.12.5) thus the following check is asymmetric.
8895 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008896 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008897 LHSPteeQual.removeAddressSpace();
8898 RHSPteeQual.removeAddressSpace();
8899 LHSPointee =
8900 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8901 RHSPointee =
8902 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8903 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008904 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8905 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008906 if (ResultType.isNull())
8907 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00008908 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8909 return LHS;
8910 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8911 return RHS;
8912 return getBlockPointerType(ResultType);
8913 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008914 case Type::Atomic:
8915 {
8916 // Merge two pointer types, while trying to preserve typedef info
8917 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8918 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8919 if (Unqualified) {
8920 LHSValue = LHSValue.getUnqualifiedType();
8921 RHSValue = RHSValue.getUnqualifiedType();
8922 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008923 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
Eli Friedman0dfb8892011-10-06 23:00:33 +00008924 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008925 if (ResultType.isNull())
8926 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00008927 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8928 return LHS;
8929 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8930 return RHS;
8931 return getAtomicType(ResultType);
8932 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008933 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008934 {
8935 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8936 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8937 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008938 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008939
8940 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8941 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008942 if (Unqualified) {
8943 LHSElem = LHSElem.getUnqualifiedType();
8944 RHSElem = RHSElem.getUnqualifiedType();
8945 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008946
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008947 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008948 if (ResultType.isNull())
8949 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00008950
8951 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8952 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8953
8954 // If either side is a variable array, and both are complete, check whether
8955 // the current dimension is definite.
8956 if (LVAT || RVAT) {
8957 auto SizeFetch = [this](const VariableArrayType* VAT,
8958 const ConstantArrayType* CAT)
8959 -> std::pair<bool,llvm::APInt> {
8960 if (VAT) {
8961 llvm::APSInt TheInt;
8962 Expr *E = VAT->getSizeExpr();
8963 if (E && E->isIntegerConstantExpr(TheInt, *this))
8964 return std::make_pair(true, TheInt);
8965 else
8966 return std::make_pair(false, TheInt);
8967 } else if (CAT) {
8968 return std::make_pair(true, CAT->getSize());
8969 } else {
8970 return std::make_pair(false, llvm::APInt());
8971 }
8972 };
8973
8974 bool HaveLSize, HaveRSize;
8975 llvm::APInt LSize, RSize;
8976 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
8977 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
8978 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
8979 return {}; // Definite, but unequal, array dimension
8980 }
8981
Chris Lattner465fa322008-10-05 17:34:18 +00008982 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8983 return LHS;
8984 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8985 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008986 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8987 ArrayType::ArraySizeModifier(), 0);
8988 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8989 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00008990 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8991 return LHS;
8992 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8993 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008994 if (LVAT) {
8995 // FIXME: This isn't correct! But tricky to implement because
8996 // the array's size has to be the size of LHS, but the type
8997 // has to be different.
8998 return LHS;
8999 }
9000 if (RVAT) {
9001 // FIXME: This isn't correct! But tricky to implement because
9002 // the array's size has to be the size of RHS, but the type
9003 // has to be different.
9004 return RHS;
9005 }
Eli Friedman3e62c212008-08-22 01:48:21 +00009006 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9007 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00009008 return getIncompleteArrayType(ResultType,
9009 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00009010 }
Chris Lattnerfd652912008-01-14 05:45:46 +00009011 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009012 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009013 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009014 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00009015 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00009016 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009017 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009018 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00009019 case Type::Complex:
9020 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009021 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009022 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00009023 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00009024 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
9025 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00009026 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009027 return {};
John McCall8b07ec22010-05-15 11:32:37 +00009028 case Type::ObjCObject: {
9029 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00009030 // FIXME: This should be type compatibility, e.g. whether
9031 // "LHS x; RHS x;" at global scope is legal.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009032 const auto *LHSIface = LHS->getAs<ObjCObjectType>();
9033 const auto *RHSIface = RHS->getAs<ObjCObjectType>();
John McCall8b07ec22010-05-15 11:32:37 +00009034 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00009035 return LHS;
9036
Eugene Zelenko7855e772018-04-03 00:11:50 +00009037 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00009038 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009039 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009040 if (OfBlockPointer) {
9041 if (canAssignObjCInterfacesInBlockPointer(
9042 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00009043 RHS->getAs<ObjCObjectPointerType>(),
9044 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00009045 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009046 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009047 }
John McCall9dd450b2009-09-21 23:43:11 +00009048 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
9049 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00009050 return LHS;
9051
Eugene Zelenko7855e772018-04-03 00:11:50 +00009052 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009053 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00009054 assert(LHS != RHS &&
9055 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00009056 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009057 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009058
David Blaikie8a40f702012-01-17 06:56:22 +00009059 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00009060}
Ted Kremenekfc581a92007-10-31 17:10:13 +00009061
Akira Hatanaka98a49332017-09-22 00:41:05 +00009062bool ASTContext::mergeExtParameterInfo(
9063 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9064 bool &CanUseFirst, bool &CanUseSecond,
9065 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9066 assert(NewParamInfos.empty() && "param info list not empty");
9067 CanUseFirst = CanUseSecond = true;
9068 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9069 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9070
John McCall18afab72016-03-01 00:49:02 +00009071 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00009072 // we match if and only if the second type also doesn't have them.
9073 if (!FirstHasInfo && !SecondHasInfo)
9074 return true;
John McCall18afab72016-03-01 00:49:02 +00009075
Akira Hatanaka98a49332017-09-22 00:41:05 +00009076 bool NeedParamInfo = false;
9077 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9078 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00009079
Akira Hatanaka98a49332017-09-22 00:41:05 +00009080 for (size_t I = 0; I < E; ++I) {
9081 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9082 if (FirstHasInfo)
9083 FirstParam = FirstFnType->getExtParameterInfo(I);
9084 if (SecondHasInfo)
9085 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00009086
Akira Hatanaka98a49332017-09-22 00:41:05 +00009087 // Cannot merge unless everything except the noescape flag matches.
9088 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00009089 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00009090
9091 bool FirstNoEscape = FirstParam.isNoEscape();
9092 bool SecondNoEscape = SecondParam.isNoEscape();
9093 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9094 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9095 if (NewParamInfos.back().getOpaqueValue())
9096 NeedParamInfo = true;
9097 if (FirstNoEscape != IsNoEscape)
9098 CanUseFirst = false;
9099 if (SecondNoEscape != IsNoEscape)
9100 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00009101 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00009102
9103 if (!NeedParamInfo)
9104 NewParamInfos.clear();
9105
Fariborz Jahanian97676972011-09-28 21:52:05 +00009106 return true;
9107}
9108
Chandler Carruth21c90602015-12-30 03:24:14 +00009109void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9110 ObjCLayouts[CD] = nullptr;
9111}
9112
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009113/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9114/// 'RHS' attributes and returns the merged version; including for function
9115/// return types.
9116QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9117 QualType LHSCan = getCanonicalType(LHS),
9118 RHSCan = getCanonicalType(RHS);
9119 // If two types are identical, they are compatible.
9120 if (LHSCan == RHSCan)
9121 return LHS;
9122 if (RHSCan->isFunctionType()) {
9123 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009124 return {};
Alp Toker314cc812014-01-25 16:55:45 +00009125 QualType OldReturnType =
9126 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009127 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00009128 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009129 QualType ResReturnType =
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009130 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9131 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009132 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009133 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9134 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9135 // In either case, use OldReturnType to build the new function type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009136 const auto *F = LHS->getAs<FunctionType>();
9137 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009138 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9139 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00009140 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00009141 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009142 return ResultType;
9143 }
9144 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009145 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009146 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009147
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009148 // If the qualifiers are different, the types can still be merged.
9149 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9150 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9151 if (LQuals != RQuals) {
9152 // If any of these qualifiers are different, we have a type mismatch.
9153 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9154 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009155 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009156
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009157 // Exactly one GC qualifier difference is allowed: __strong is
9158 // okay if the other type has no GC qualifier but is an Objective
9159 // C object pointer (i.e. implicitly strong by default). We fix
9160 // this by pretending that the unqualified type was actually
9161 // qualified __strong.
9162 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9163 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9164 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
Fangrui Song6907ce22018-07-30 19:24:48 +00009165
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009166 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009167 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009168
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009169 if (GC_L == Qualifiers::Strong)
9170 return LHS;
9171 if (GC_R == Qualifiers::Strong)
9172 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009173 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009174 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009175
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009176 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9177 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9178 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9179 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9180 if (ResQT == LHSBaseQT)
9181 return LHS;
9182 if (ResQT == RHSBaseQT)
9183 return RHS;
9184 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009185 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009186}
9187
Chris Lattner4ba0cef2008-04-07 07:01:58 +00009188//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009189// Integer Predicates
9190//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00009191
Jay Foad39c79802011-01-12 09:06:06 +00009192unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009193 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00009194 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009195 if (T->isBooleanType())
9196 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00009197 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009198 return (unsigned)getTypeSize(T);
9199}
9200
Abramo Bagnara13640492012-09-09 10:21:24 +00009201QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00009202 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9203 "Unexpected type");
Fangrui Song6907ce22018-07-30 19:24:48 +00009204
Chris Lattnerec3a1562009-10-17 20:33:28 +00009205 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00009206 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00009207 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00009208 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00009209
9210 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009211 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009212 T = ETy->getDecl()->getIntegerType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009213
Eugene Zelenko7855e772018-04-03 00:11:50 +00009214 const auto *BTy = T->getAs<BuiltinType>();
Leonard Chanab80f3c2018-06-14 14:53:51 +00009215 assert(BTy && "Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009216 switch (BTy->getKind()) {
9217 case BuiltinType::Char_S:
9218 case BuiltinType::SChar:
9219 return UnsignedCharTy;
9220 case BuiltinType::Short:
9221 return UnsignedShortTy;
9222 case BuiltinType::Int:
9223 return UnsignedIntTy;
9224 case BuiltinType::Long:
9225 return UnsignedLongTy;
9226 case BuiltinType::LongLong:
9227 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00009228 case BuiltinType::Int128:
9229 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00009230
9231 case BuiltinType::ShortAccum:
9232 return UnsignedShortAccumTy;
9233 case BuiltinType::Accum:
9234 return UnsignedAccumTy;
9235 case BuiltinType::LongAccum:
9236 return UnsignedLongAccumTy;
9237 case BuiltinType::SatShortAccum:
9238 return SatUnsignedShortAccumTy;
9239 case BuiltinType::SatAccum:
9240 return SatUnsignedAccumTy;
9241 case BuiltinType::SatLongAccum:
9242 return SatUnsignedLongAccumTy;
9243 case BuiltinType::ShortFract:
9244 return UnsignedShortFractTy;
9245 case BuiltinType::Fract:
9246 return UnsignedFractTy;
9247 case BuiltinType::LongFract:
9248 return UnsignedLongFractTy;
9249 case BuiltinType::SatShortFract:
9250 return SatUnsignedShortFractTy;
9251 case BuiltinType::SatFract:
9252 return SatUnsignedFractTy;
9253 case BuiltinType::SatLongFract:
9254 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009255 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009256 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009257 }
9258}
9259
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009260ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00009261
Richard Smith1fa5d642013-05-11 05:45:24 +00009262void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9263 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00009264
9265//===----------------------------------------------------------------------===//
9266// Builtin Type Computation
9267//===----------------------------------------------------------------------===//
9268
9269/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00009270/// pointer over the consumed characters. This returns the resultant type. If
9271/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9272/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9273/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009274///
9275/// RequiresICE is filled in on return to indicate whether the value is required
9276/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009277static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009278 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009279 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009280 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009281 // Modifiers.
9282 int HowLong = 0;
9283 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009284 RequiresICE = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009285
Chris Lattnerdc226c22010-10-01 22:42:38 +00009286 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009287 bool Done = false;
9288 #ifndef NDEBUG
9289 bool IsSpecialLong = false;
9290 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009291 while (!Done) {
9292 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009293 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009294 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009295 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009296 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009297 case 'S':
9298 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9299 assert(!Signed && "Can't use 'S' modifier multiple times!");
9300 Signed = true;
9301 break;
9302 case 'U':
9303 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009304 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009305 Unsigned = true;
9306 break;
9307 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009308 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009309 assert(HowLong <= 2 && "Can't have LLLL modifier");
9310 ++HowLong;
9311 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009312 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009313 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
9314 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
9315 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009316 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009317 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009318 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009319 if (Context.getTargetInfo().getLongWidth() == 32)
9320 ++HowLong;
9321 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009322 case 'W':
9323 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009324 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009325 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009326 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009327 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009328 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009329 switch (Context.getTargetInfo().getInt64Type()) {
9330 default:
9331 llvm_unreachable("Unexpected integer type");
9332 case TargetInfo::SignedLong:
9333 HowLong = 1;
9334 break;
9335 case TargetInfo::SignedLongLong:
9336 HowLong = 2;
9337 break;
9338 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009339 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009340 }
9341 }
9342
9343 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009344
Chris Lattnerecd79c62009-06-14 00:45:47 +00009345 // Read the base type.
9346 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009347 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009348 case 'v':
9349 assert(HowLong == 0 && !Signed && !Unsigned &&
9350 "Bad modifiers used with 'v'!");
9351 Type = Context.VoidTy;
9352 break;
Jack Carter24bef982013-08-15 15:16:57 +00009353 case 'h':
9354 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009355 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009356 Type = Context.HalfTy;
9357 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009358 case 'f':
9359 assert(HowLong == 0 && !Signed && !Unsigned &&
9360 "Bad modifiers used with 'f'!");
9361 Type = Context.FloatTy;
9362 break;
9363 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009364 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009365 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009366 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009367 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009368 else if (HowLong == 2)
9369 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009370 else
9371 Type = Context.DoubleTy;
9372 break;
9373 case 's':
9374 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9375 if (Unsigned)
9376 Type = Context.UnsignedShortTy;
9377 else
9378 Type = Context.ShortTy;
9379 break;
9380 case 'i':
9381 if (HowLong == 3)
9382 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9383 else if (HowLong == 2)
9384 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9385 else if (HowLong == 1)
9386 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9387 else
9388 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9389 break;
9390 case 'c':
9391 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9392 if (Signed)
9393 Type = Context.SignedCharTy;
9394 else if (Unsigned)
9395 Type = Context.UnsignedCharTy;
9396 else
9397 Type = Context.CharTy;
9398 break;
9399 case 'b': // boolean
9400 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9401 Type = Context.BoolTy;
9402 break;
9403 case 'z': // size_t.
9404 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9405 Type = Context.getSizeType();
9406 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009407 case 'w': // wchar_t.
9408 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9409 Type = Context.getWideCharType();
9410 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009411 case 'F':
9412 Type = Context.getCFConstantStringType();
9413 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009414 case 'G':
9415 Type = Context.getObjCIdType();
9416 break;
9417 case 'H':
9418 Type = Context.getObjCSelType();
9419 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009420 case 'M':
9421 Type = Context.getObjCSuperType();
9422 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009423 case 'a':
9424 Type = Context.getBuiltinVaListType();
9425 assert(!Type.isNull() && "builtin va list type not initialized!");
9426 break;
9427 case 'A':
9428 // This is a "reference" to a va_list; however, what exactly
9429 // this means depends on how va_list is defined. There are two
9430 // different kinds of va_list: ones passed by value, and ones
9431 // passed by reference. An example of a by-value va_list is
9432 // x86, where va_list is a char*. An example of by-ref va_list
9433 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9434 // we want this argument to be a char*&; for x86-64, we want
9435 // it to be a __va_list_tag*.
9436 Type = Context.getBuiltinVaListType();
9437 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009438 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009439 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009440 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009441 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009442 break;
9443 case 'V': {
9444 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009445 unsigned NumElements = strtoul(Str, &End, 10);
9446 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009447 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009448
Fangrui Song6907ce22018-07-30 19:24:48 +00009449 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009450 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009451 assert(!RequiresICE && "Can't require vector ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009452
Chris Lattnerdc226c22010-10-01 22:42:38 +00009453 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009454 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009455 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009456 break;
9457 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009458 case 'E': {
9459 char *End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009460
Douglas Gregorfed66992012-06-07 18:08:25 +00009461 unsigned NumElements = strtoul(Str, &End, 10);
9462 assert(End != Str && "Missing vector size");
Fangrui Song6907ce22018-07-30 19:24:48 +00009463
Douglas Gregorfed66992012-06-07 18:08:25 +00009464 Str = End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009465
Douglas Gregorfed66992012-06-07 18:08:25 +00009466 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009467 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009468 Type = Context.getExtVectorType(ElementType, NumElements);
Fangrui Song6907ce22018-07-30 19:24:48 +00009469 break;
Douglas Gregorfed66992012-06-07 18:08:25 +00009470 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009471 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009472 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009473 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009474 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009475 Type = Context.getComplexType(ElementType);
9476 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00009477 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009478 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009479 Type = Context.getPointerDiffType();
9480 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009481 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009482 Type = Context.getFILEType();
9483 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009484 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009485 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009486 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009487 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009488 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009489 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009490 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009491 else
9492 Type = Context.getjmp_bufType();
9493
Mike Stump2adb4da2009-07-28 23:47:15 +00009494 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009495 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009496 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009497 }
9498 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009499 case 'K':
9500 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9501 Type = Context.getucontext_tType();
9502
9503 if (Type.isNull()) {
9504 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009505 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009506 }
9507 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009508 case 'p':
9509 Type = Context.getProcessIDType();
9510 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009511 }
Mike Stump11289f42009-09-09 15:08:12 +00009512
Chris Lattnerdc226c22010-10-01 22:42:38 +00009513 // If there are modifiers and if we're allowed to parse them, go for it.
9514 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009515 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009516 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009517 default: Done = true; --Str; break;
9518 case '*':
9519 case '&': {
9520 // Both pointers and references can have their pointee types
9521 // qualified with an address space.
9522 char *End;
9523 unsigned AddrSpace = strtoul(Str, &End, 10);
Matt Arsenaultc65f9662018-08-02 12:14:28 +00009524 if (End != Str) {
9525 // Note AddrSpace == 0 is not the same as an unspecified address space.
9526 Type = Context.getAddrSpaceQualType(
9527 Type,
9528 Context.getLangASForBuiltinAddressSpace(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009529 Str = End;
9530 }
9531 if (c == '*')
9532 Type = Context.getPointerType(Type);
9533 else
9534 Type = Context.getLValueReferenceType(Type);
9535 break;
9536 }
9537 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9538 case 'C':
9539 Type = Type.withConst();
9540 break;
9541 case 'D':
9542 Type = Context.getVolatileType(Type);
9543 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009544 case 'R':
9545 Type = Type.withRestrict();
9546 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009547 }
9548 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009549
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009550 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Fangrui Song6907ce22018-07-30 19:24:48 +00009551 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009552
Chris Lattnerecd79c62009-06-14 00:45:47 +00009553 return Type;
9554}
9555
9556/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009557QualType ASTContext::GetBuiltinType(unsigned Id,
9558 GetBuiltinTypeError &Error,
9559 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009560 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00009561 if (TypeStr[0] == '\0') {
9562 Error = GE_Missing_type;
9563 return {};
9564 }
Mike Stump11289f42009-09-09 15:08:12 +00009565
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009566 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009567
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009568 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009569 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009570 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9571 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009572 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009573 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009574
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009575 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009576
Chris Lattnerecd79c62009-06-14 00:45:47 +00009577 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009578 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009579 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009580 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009581
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009582 // If this argument is required to be an IntegerConstantExpression and the
9583 // caller cares, fill in the bitmask we return.
9584 if (RequiresICE && IntegerConstantArgs)
9585 *IntegerConstantArgs |= 1 << ArgTypes.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00009586
Chris Lattnerecd79c62009-06-14 00:45:47 +00009587 // Do array -> pointer decay. The builtin should use the decayed type.
9588 if (Ty->isArrayType())
9589 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009590
Chris Lattnerecd79c62009-06-14 00:45:47 +00009591 ArgTypes.push_back(Ty);
9592 }
9593
David Majnemerba3e5ec2015-03-13 18:26:17 +00009594 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009595 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009596
Chris Lattnerecd79c62009-06-14 00:45:47 +00009597 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9598 "'.' should only occur at end of builtin type list!");
9599
Erich Keane881e83d2019-03-04 14:54:52 +00009600 bool Variadic = (TypeStr[0] == '.');
9601
9602 FunctionType::ExtInfo EI(
9603 getDefaultCallingConvention(Variadic, /*IsCXXMethod=*/false));
John McCall991eb4b2010-12-21 00:44:39 +00009604 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9605
John McCall991eb4b2010-12-21 00:44:39 +00009606
Richard Smith836de6b2016-12-19 23:59:34 +00009607 // We really shouldn't be making a no-proto type here.
9608 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009609 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009610
John McCalldb40c7f2010-12-14 08:05:40 +00009611 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009612 EPI.ExtInfo = EI;
9613 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009614 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9615 EPI.ExceptionSpec.Type =
9616 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009617
Jordan Rose5c382722013-03-08 21:51:21 +00009618 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009619}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009620
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009621static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9622 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009623 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009624 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009625
Richard Smithe2467b72017-11-16 23:54:56 +00009626 // Non-user-provided functions get emitted as weak definitions with every
9627 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009628 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009629 if (!MD->isUserProvided())
9630 return GVA_DiscardableODR;
9631
Yaron Keren4cd211b2017-02-22 14:32:39 +00009632 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009633 switch (FD->getTemplateSpecializationKind()) {
9634 case TSK_Undeclared:
9635 case TSK_ExplicitSpecialization:
9636 External = GVA_StrongExternal;
9637 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009638
Rafael Espindola3ae00052013-05-13 00:12:11 +00009639 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009640 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009641
David Majnemerc3d07332014-05-15 06:25:57 +00009642 // C++11 [temp.explicit]p10:
9643 // [ Note: The intent is that an inline function that is the subject of
9644 // an explicit instantiation declaration will still be implicitly
9645 // instantiated when used so that the body can be considered for
9646 // inlining, but that no out-of-line copy of the inline function would be
9647 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009648 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009649 return GVA_AvailableExternally;
9650
Rafael Espindola3ae00052013-05-13 00:12:11 +00009651 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009652 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009653 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009654 }
9655
9656 if (!FD->isInlined())
9657 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009658
David Majnemer3f021502015-10-08 04:53:31 +00009659 if ((!Context.getLangOpts().CPlusPlus &&
9660 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009661 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009662 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009663 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9664
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009665 // GNU or C99 inline semantics. Determine whether this symbol should be
9666 // externally visible.
9667 if (FD->isInlineDefinitionExternallyVisible())
9668 return External;
9669
9670 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009671 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009672 }
9673
David Majnemer54e3ba52014-04-02 23:17:29 +00009674 // Functions specified with extern and inline in -fms-compatibility mode
9675 // forcibly get emitted. While the body of the function cannot be later
9676 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009677 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009678 return GVA_StrongODR;
9679
David Majnemer27d69db2014-04-28 22:17:59 +00009680 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009681}
9682
Artem Belevichca2b9512016-05-02 20:30:03 +00009683static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009684 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009685 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9686 // dllexport/dllimport on inline functions.
9687 if (D->hasAttr<DLLImportAttr>()) {
9688 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9689 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009690 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009691 if (L == GVA_DiscardableODR)
9692 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009693 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9694 D->hasAttr<CUDAGlobalAttr>()) {
9695 // Device-side functions with __global__ attribute must always be
9696 // visible externally so they can be launched from host.
9697 if (L == GVA_DiscardableODR || L == GVA_Internal)
9698 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009699 }
9700 return L;
9701}
9702
Richard Smitha4653622017-09-06 20:01:14 +00009703/// Adjust the GVALinkage for a declaration based on what an external AST source
9704/// knows about whether there can be other definitions of this declaration.
9705static GVALinkage
9706adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9707 GVALinkage L) {
9708 ExternalASTSource *Source = Ctx.getExternalSource();
9709 if (!Source)
9710 return L;
9711
9712 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009713 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009714 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009715 if (L == GVA_DiscardableODR)
9716 return GVA_StrongODR;
9717 break;
Richard Smitha4653622017-09-06 20:01:14 +00009718
David Blaikie9ffe5a32017-01-30 05:00:26 +00009719 case ExternalASTSource::EK_Always:
9720 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009721
David Blaikie9ffe5a32017-01-30 05:00:26 +00009722 case ExternalASTSource::EK_ReplyHazy:
9723 break;
9724 }
9725 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009726}
9727
Richard Smitha4653622017-09-06 20:01:14 +00009728GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9729 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9730 adjustGVALinkageForAttributes(*this, FD,
9731 basicGVALinkageForFunction(*this, FD)));
9732}
9733
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009734static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9735 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009736 if (!VD->isExternallyVisible())
9737 return GVA_Internal;
9738
David Majnemer27d69db2014-04-28 22:17:59 +00009739 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009740 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9741 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9742 LexicalContext = LexicalContext->getLexicalParent();
9743
David Blaikieeb210012017-01-27 23:11:10 +00009744 // ObjC Blocks can create local variables that don't have a FunctionDecl
9745 // LexicalContext.
9746 if (!LexicalContext)
9747 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009748
David Blaikieeb210012017-01-27 23:11:10 +00009749 // Otherwise, let the static local variable inherit its linkage from the
9750 // nearest enclosing function.
9751 auto StaticLocalLinkage =
9752 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9753
9754 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9755 // be emitted in any object with references to the symbol for the object it
9756 // contains, whether inline or out-of-line."
9757 // Similar behavior is observed with MSVC. An alternative ABI could use
9758 // StrongODR/AvailableExternally to match the function, but none are
9759 // known/supported currently.
9760 if (StaticLocalLinkage == GVA_StrongODR ||
9761 StaticLocalLinkage == GVA_AvailableExternally)
9762 return GVA_DiscardableODR;
9763 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009764 }
9765
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009766 // MSVC treats in-class initialized static data members as definitions.
9767 // By giving them non-strong linkage, out-of-line definitions won't
9768 // cause link errors.
9769 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9770 return GVA_DiscardableODR;
9771
Richard Smithd9b90092016-07-02 01:32:16 +00009772 // Most non-template variables have strong linkage; inline variables are
9773 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9774 GVALinkage StrongLinkage;
9775 switch (Context.getInlineVariableDefinitionKind(VD)) {
9776 case ASTContext::InlineVariableDefinitionKind::None:
9777 StrongLinkage = GVA_StrongExternal;
9778 break;
9779 case ASTContext::InlineVariableDefinitionKind::Weak:
9780 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009781 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009782 break;
9783 case ASTContext::InlineVariableDefinitionKind::Strong:
9784 StrongLinkage = GVA_StrongODR;
9785 break;
9786 }
Richard Smith62f19e72016-06-25 00:15:56 +00009787
Richard Smith8809a0c2013-09-27 20:14:12 +00009788 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009789 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009790 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009791
David Majnemer6d1780c2015-07-17 23:36:49 +00009792 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00009793 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9794 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00009795 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00009796 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009797
Rafael Espindola3ae00052013-05-13 00:12:11 +00009798 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009799 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009800
David Majnemer27d69db2014-04-28 22:17:59 +00009801 case TSK_ExplicitInstantiationDeclaration:
9802 return GVA_AvailableExternally;
9803
Rafael Espindola3ae00052013-05-13 00:12:11 +00009804 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009805 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009806 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009807
9808 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009809}
9810
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009811GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009812 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9813 adjustGVALinkageForAttributes(*this, VD,
9814 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009815}
9816
David Blaikiee6b7c282017-04-11 20:46:34 +00009817bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009818 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009819 if (!VD->isFileVarDecl())
9820 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009821 // Global named register variables (GNU extension) are never emitted.
9822 if (VD->getStorageClass() == SC_Register)
9823 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009824 if (VD->getDescribedVarTemplate() ||
9825 isa<VarTemplatePartialSpecializationDecl>(VD))
9826 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009827 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +00009828 // We never need to emit an uninstantiated function template.
9829 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9830 return false;
Nico Weber66220292016-03-02 17:28:48 +00009831 } else if (isa<PragmaCommentDecl>(D))
9832 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009833 else if (isa<PragmaDetectMismatchDecl>(D))
9834 return true;
Nico Weber66220292016-03-02 17:28:48 +00009835 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009836 return !D->getDeclContext()->isDependentContext();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009837 else if (isa<OMPAllocateDecl>(D))
9838 return !D->getDeclContext()->isDependentContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009839 else if (isa<OMPDeclareReductionDecl>(D))
9840 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009841 else if (isa<ImportDecl>(D))
9842 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009843 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009844 return false;
9845
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009846 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9847 assert(getExternalSource() && "It's from an AST file; must have a source.");
9848 // On Windows, PCH files are built together with an object file. If this
9849 // declaration comes from such a PCH and DeclMustBeEmitted would return
9850 // true, it would have returned true and the decl would have been emitted
9851 // into that object file, so it doesn't need to be emitted here.
9852 // Note that decls are still emitted if they're referenced, as usual;
9853 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9854 // if it's not referenced.
9855 //
9856 // Explicit template instantiation definitions are tricky. If there was an
9857 // explicit template instantiation decl in the PCH before, it will look like
9858 // the definition comes from there, even if that was just the declaration.
9859 // (Explicit instantiation defs of variable templates always get emitted.)
9860 bool IsExpInstDef =
9861 isa<FunctionDecl>(D) &&
9862 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
9863 TSK_ExplicitInstantiationDefinition;
9864
Hans Wennborgb51a7032018-09-14 15:18:30 +00009865 // Implicit member function definitions, such as operator= might not be
9866 // marked as template specializations, since they're not coming from a
9867 // template but synthesized directly on the class.
9868 IsExpInstDef |=
9869 isa<CXXMethodDecl>(D) &&
9870 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
9871 TSK_ExplicitInstantiationDefinition;
9872
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009873 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
9874 return false;
9875 }
9876
Richard Smith5205a8c2013-04-01 20:22:16 +00009877 // If this is a member of a class template, we do not need to emit it.
9878 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009879 return false;
9880
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009881 // Weak references don't produce any output by themselves.
9882 if (D->hasAttr<WeakRefAttr>())
9883 return false;
9884
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009885 // Aliases and used decls are required.
9886 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9887 return true;
9888
Eugene Zelenko7855e772018-04-03 00:11:50 +00009889 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009890 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009891 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009892 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009893
9894 // Constructors and destructors are required.
9895 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9896 return true;
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009897
John McCall6bd2a892013-01-25 22:31:03 +00009898 // The key function for a class is required. This rule only comes
9899 // into play when inline functions can be key functions, though.
9900 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009901 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +00009902 const CXXRecordDecl *RD = MD->getParent();
9903 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9904 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9905 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9906 return true;
9907 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009908 }
9909 }
9910
David Blaikie9ffe5a32017-01-30 05:00:26 +00009911 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9912
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009913 // static, static inline, always_inline, and extern inline functions can
9914 // always be deferred. Normal inline functions can be deferred in C99/C++.
9915 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009916 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009917 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009918
Eugene Zelenko7855e772018-04-03 00:11:50 +00009919 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009920 assert(VD->isFileVarDecl() && "Expected file scoped var");
9921
Alexey Bataevd01b7492018-08-15 19:45:12 +00009922 // If the decl is marked as `declare target to`, it should be emitted for the
9923 // host and for the device.
9924 if (LangOpts.OpenMP &&
9925 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
9926 return true;
9927
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009928 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9929 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009930 return false;
9931
Richard Smitha0e5e542012-11-12 21:38:00 +00009932 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009933 auto Linkage = GetGVALinkageForVariable(VD);
9934 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009935 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009936
Richard Smitha4653622017-09-06 20:01:14 +00009937 // We never need to emit a variable that is available in another TU.
9938 if (Linkage == GVA_AvailableExternally)
9939 return false;
9940
Richard Smitha0e5e542012-11-12 21:38:00 +00009941 // Variables that have destruction with side-effects are required.
9942 if (VD->getType().isDestructedType())
9943 return true;
9944
9945 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009946 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009947 // We can get a value-dependent initializer during error recovery.
9948 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009949 return true;
9950
Richard Smithda383632016-08-15 01:33:41 +00009951 // Likewise, variables with tuple-like bindings are required if their
9952 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009953 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
9954 for (const auto *BD : DD->bindings())
9955 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +00009956 if (DeclMustBeEmitted(BindingVD))
9957 return true;
9958
Richard Smitha0e5e542012-11-12 21:38:00 +00009959 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009960}
Charles Davis53c59df2010-08-16 03:33:14 +00009961
Erich Keane281d20b2018-01-08 21:34:17 +00009962void ASTContext::forEachMultiversionedFunctionVersion(
9963 const FunctionDecl *FD,
Erich Keane0fb16482018-08-13 18:33:20 +00009964 llvm::function_ref<void(FunctionDecl *)> Pred) const {
Erich Keane281d20b2018-01-08 21:34:17 +00009965 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
9966 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
Erich Keane7304f0a2018-11-28 20:58:43 +00009967 FD = FD->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00009968 for (auto *CurDecl :
9969 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
Erich Keane7304f0a2018-11-28 20:58:43 +00009970 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00009971 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
9972 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
9973 SeenDecls.insert(CurFD);
9974 Pred(CurFD);
9975 }
9976 }
9977}
9978
Reid Kleckner78af0702013-08-27 23:08:25 +00009979CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9980 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009981 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009982 if (IsCXXMethod)
9983 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009984
Alexey Bataeva7547182016-05-18 09:06:38 +00009985 switch (LangOpts.getDefaultCallingConv()) {
9986 case LangOptions::DCC_None:
9987 break;
9988 case LangOptions::DCC_CDecl:
9989 return CC_C;
9990 case LangOptions::DCC_FastCall:
Erich Keane5759fa72017-10-24 23:12:01 +00009991 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
Alexey Bataeva7547182016-05-18 09:06:38 +00009992 return CC_X86FastCall;
9993 break;
9994 case LangOptions::DCC_StdCall:
9995 if (!IsVariadic)
9996 return CC_X86StdCall;
9997 break;
9998 case LangOptions::DCC_VectorCall:
9999 // __vectorcall cannot be applied to variadic functions.
10000 if (!IsVariadic)
10001 return CC_X86VectorCall;
10002 break;
Erich Keanea957ffb2017-11-02 21:08:00 +000010003 case LangOptions::DCC_RegCall:
10004 // __regcall cannot be applied to variadic functions.
10005 if (!IsVariadic)
10006 return CC_X86RegCall;
10007 break;
Alexey Bataeva7547182016-05-18 09:06:38 +000010008 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000010009 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +000010010}
10011
Jay Foad39c79802011-01-12 09:06:06 +000010012bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +000010013 // Pass through to the C++ ABI object
10014 return ABI->isNearlyEmpty(RD);
10015}
10016
Reid Kleckner96f8f932014-02-05 17:27:08 +000010017VTableContextBase *ASTContext::getVTableContext() {
10018 if (!VTContext.get()) {
10019 if (Target->getCXXABI().isMicrosoft())
10020 VTContext.reset(new MicrosoftVTableContext(*this));
10021 else
10022 VTContext.reset(new ItaniumVTableContext(*this));
10023 }
10024 return VTContext.get();
10025}
10026
Yaxun Liuc18e9ec2019-02-14 02:00:09 +000010027MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10028 if (!T)
10029 T = Target;
10030 switch (T->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000010031 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +000010032 case TargetCXXABI::GenericItanium:
10033 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000010034 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +000010035 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000010036 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +000010037 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +000010038 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010039 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +000010040 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010041 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010042 }
David Blaikie83d382b2011-09-23 05:06:16 +000010043 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010044}
10045
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010046CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010047
10048size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +000010049 return ASTRecordLayouts.getMemorySize() +
10050 llvm::capacity_in_bytes(ObjCLayouts) +
10051 llvm::capacity_in_bytes(KeyFunctions) +
10052 llvm::capacity_in_bytes(ObjCImpls) +
10053 llvm::capacity_in_bytes(BlockVarCopyInits) +
10054 llvm::capacity_in_bytes(DeclAttrs) +
10055 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10056 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10057 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10058 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10059 llvm::capacity_in_bytes(OverriddenMethods) +
10060 llvm::capacity_in_bytes(Types) +
Richard Smithf19a8b02019-05-02 00:49:14 +000010061 llvm::capacity_in_bytes(VariableArrayTypes);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010062}
Ted Kremenek540017e2011-10-06 05:00:56 +000010063
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010064/// getIntTypeForBitwidth -
10065/// sets integer QualTy according to specified details:
10066/// bitwidth, signed/unsigned.
10067/// Returns empty type if there is no appropriate target types.
10068QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10069 unsigned Signed) const {
10070 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10071 CanQualType QualTy = getFromTargetType(Ty);
10072 if (!QualTy && DestWidth == 128)
10073 return Signed ? Int128Ty : UnsignedInt128Ty;
10074 return QualTy;
10075}
10076
10077/// getRealTypeForBitwidth -
10078/// sets floating point QualTy according to specified bitwidth.
10079/// Returns empty type if there is no appropriate target types.
10080QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
10081 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
10082 switch (Ty) {
10083 case TargetInfo::Float:
10084 return FloatTy;
10085 case TargetInfo::Double:
10086 return DoubleTy;
10087 case TargetInfo::LongDouble:
10088 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000010089 case TargetInfo::Float128:
10090 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010091 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +000010092 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010093 }
10094
10095 llvm_unreachable("Unhandled TargetInfo::RealType value");
10096}
10097
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010098void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10099 if (Number > 1)
10100 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +000010101}
10102
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010103unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010104 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010105 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +000010106}
10107
David Majnemer2206bf52014-03-05 08:57:59 +000010108void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10109 if (Number > 1)
10110 StaticLocalNumbers[VD] = Number;
10111}
10112
10113unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010114 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +000010115 return I != StaticLocalNumbers.end() ? I->second : 1;
10116}
10117
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010118MangleNumberingContext &
10119ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010120 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +000010121 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +000010122 if (!MCtx)
10123 MCtx = createMangleNumberingContext();
10124 return *MCtx;
10125}
10126
Justin Lebar20ebffc2016-10-10 16:26:19 +000010127std::unique_ptr<MangleNumberingContext>
10128ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010129 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +000010130}
10131
David Majnemere7a818f2015-03-06 18:53:55 +000010132const CXXConstructorDecl *
10133ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10134 return ABI->getCopyConstructorForExceptionObject(
10135 cast<CXXRecordDecl>(RD->getFirstDecl()));
10136}
10137
10138void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10139 CXXConstructorDecl *CD) {
10140 return ABI->addCopyConstructorForExceptionObject(
10141 cast<CXXRecordDecl>(RD->getFirstDecl()),
10142 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10143}
10144
David Majnemer00350522015-08-31 18:48:39 +000010145void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10146 TypedefNameDecl *DD) {
10147 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10148}
10149
10150TypedefNameDecl *
10151ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10152 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10153}
10154
10155void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10156 DeclaratorDecl *DD) {
10157 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10158}
10159
10160DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10161 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10162}
10163
Ted Kremenek540017e2011-10-06 05:00:56 +000010164void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10165 ParamIndices[D] = index;
10166}
10167
10168unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10169 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
Fangrui Song6907ce22018-07-30 19:24:48 +000010170 assert(I != ParamIndices.end() &&
Ted Kremenek540017e2011-10-06 05:00:56 +000010171 "ParmIndices lacks entry set by ParmVarDecl");
10172 return I->second;
10173}
Fariborz Jahanian615de762013-05-28 17:37:39 +000010174
Richard Smithe6c01442013-06-05 00:46:14 +000010175APValue *
10176ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
10177 bool MayCreate) {
10178 assert(E && E->getStorageDuration() == SD_Static &&
10179 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +000010180 if (MayCreate) {
10181 APValue *&MTVI = MaterializedTemporaryValues[E];
10182 if (!MTVI)
10183 MTVI = new (*this) APValue;
10184 return MTVI;
10185 }
Richard Smithe6c01442013-06-05 00:46:14 +000010186
David Majnemer2dcef9e2015-08-13 23:50:15 +000010187 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +000010188}
10189
Fariborz Jahanian615de762013-05-28 17:37:39 +000010190bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10191 const llvm::Triple &T = getTargetInfo().getTriple();
10192 if (!T.isOSDarwin())
10193 return false;
10194
Bob Wilson2c82c3d2013-11-02 23:27:49 +000010195 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10196 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10197 return false;
10198
Fariborz Jahanian615de762013-05-28 17:37:39 +000010199 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10200 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10201 uint64_t Size = sizeChars.getQuantity();
10202 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10203 unsigned Align = alignChars.getQuantity();
10204 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10205 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10206}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010207
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010208/// Template specializations to abstract away from pointers and TypeLocs.
10209/// @{
10210template <typename T>
Sam McCall814e7972018-11-14 10:33:30 +000010211static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010212 return ast_type_traits::DynTypedNode::create(*Node);
10213}
10214template <>
10215ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10216 return ast_type_traits::DynTypedNode::create(Node);
10217}
10218template <>
10219ast_type_traits::DynTypedNode
10220createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10221 return ast_type_traits::DynTypedNode::create(Node);
10222}
10223/// @}
10224
Sam McCall814e7972018-11-14 10:33:30 +000010225/// A \c RecursiveASTVisitor that builds a map from nodes to their
10226/// parents as defined by the \c RecursiveASTVisitor.
10227///
10228/// Note that the relationship described here is purely in terms of AST
10229/// traversal - there are other relationships (for example declaration context)
10230/// in the AST that are better modeled by special matchers.
10231///
10232/// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10233class ASTContext::ParentMap::ASTVisitor
10234 : public RecursiveASTVisitor<ASTVisitor> {
10235public:
10236 ASTVisitor(ParentMap &Map) : Map(Map) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010237
Sam McCall814e7972018-11-14 10:33:30 +000010238private:
10239 friend class RecursiveASTVisitor<ASTVisitor>;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010240
Sam McCall814e7972018-11-14 10:33:30 +000010241 using VisitorBase = RecursiveASTVisitor<ASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010242
Sam McCall814e7972018-11-14 10:33:30 +000010243 bool shouldVisitTemplateInstantiations() const { return true; }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010244
Sam McCall814e7972018-11-14 10:33:30 +000010245 bool shouldVisitImplicitCode() const { return true; }
10246
10247 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10248 typename MapTy>
10249 bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
10250 MapTy *Parents) {
10251 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010252 return true;
Sam McCall814e7972018-11-14 10:33:30 +000010253 if (ParentStack.size() > 0) {
10254 // FIXME: Currently we add the same parent multiple times, but only
10255 // when no memoization data is available for the type.
10256 // For example when we visit all subexpressions of template
10257 // instantiations; this is suboptimal, but benign: the only way to
10258 // visit those is with hasAncestor / hasParent, and those do not create
10259 // new matches.
10260 // The plan is to enable DynTypedNode to be storable in a map or hash
10261 // map. The main problem there is to implement hash functions /
10262 // comparison operators for all types that DynTypedNode supports that
10263 // do not have pointer identity.
10264 auto &NodeOrVector = (*Parents)[MapNode];
10265 if (NodeOrVector.isNull()) {
10266 if (const auto *D = ParentStack.back().get<Decl>())
10267 NodeOrVector = D;
10268 else if (const auto *S = ParentStack.back().get<Stmt>())
10269 NodeOrVector = S;
10270 else
10271 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
10272 } else {
10273 if (!NodeOrVector.template is<ParentVector *>()) {
10274 auto *Vector = new ParentVector(
10275 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10276 delete NodeOrVector
10277 .template dyn_cast<ast_type_traits::DynTypedNode *>();
10278 NodeOrVector = Vector;
Manuel Klimek95403e62014-05-21 13:28:59 +000010279 }
Sam McCall814e7972018-11-14 10:33:30 +000010280
10281 auto *Vector = NodeOrVector.template get<ParentVector *>();
10282 // Skip duplicates for types that have memoization data.
10283 // We must check that the type has memoization data before calling
10284 // std::find() because DynTypedNode::operator== can't compare all
10285 // types.
10286 bool Found = ParentStack.back().getMemoizationData() &&
10287 std::find(Vector->begin(), Vector->end(),
10288 ParentStack.back()) != Vector->end();
10289 if (!Found)
10290 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010291 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010292 }
Sam McCall814e7972018-11-14 10:33:30 +000010293 ParentStack.push_back(createDynTypedNode(Node));
10294 bool Result = BaseTraverse();
10295 ParentStack.pop_back();
10296 return Result;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010297 }
Sam McCall814e7972018-11-14 10:33:30 +000010298
10299 bool TraverseDecl(Decl *DeclNode) {
10300 return TraverseNode(
10301 DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
10302 &Map.PointerParents);
Manuel Klimek95403e62014-05-21 13:28:59 +000010303 }
Sam McCall814e7972018-11-14 10:33:30 +000010304
10305 bool TraverseStmt(Stmt *StmtNode) {
10306 return TraverseNode(
10307 StmtNode, StmtNode, [&] { return VisitorBase::TraverseStmt(StmtNode); },
10308 &Map.PointerParents);
10309 }
10310
10311 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10312 return TraverseNode(
10313 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10314 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10315 &Map.OtherParents);
10316 }
10317
10318 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10319 return TraverseNode(
10320 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10321 [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
10322 &Map.OtherParents);
10323 }
10324
10325 ParentMap &Map;
10326 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
10327};
10328
10329ASTContext::ParentMap::ParentMap(ASTContext &Ctx) {
10330 ASTVisitor(*this).TraverseAST(Ctx);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010331}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010332
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010333ASTContext::DynTypedNodeList
10334ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
Sam McCall814e7972018-11-14 10:33:30 +000010335 if (!Parents)
10336 // We build the parent map for the traversal scope (usually whole TU), as
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010337 // hasAncestor can escape any subtree.
Sam McCall814e7972018-11-14 10:33:30 +000010338 Parents = llvm::make_unique<ParentMap>(*this);
10339 return Parents->getParents(Node);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010340}
10341
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010342bool
10343ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10344 const ObjCMethodDecl *MethodImpl) {
10345 // No point trying to match an unavailable/deprecated mothod.
10346 if (MethodDecl->hasAttr<UnavailableAttr>()
10347 || MethodDecl->hasAttr<DeprecatedAttr>())
10348 return false;
10349 if (MethodDecl->getObjCDeclQualifier() !=
10350 MethodImpl->getObjCDeclQualifier())
10351 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010352 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010353 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010354
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010355 if (MethodDecl->param_size() != MethodImpl->param_size())
10356 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010357
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010358 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10359 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10360 EF = MethodDecl->param_end();
10361 IM != EM && IF != EF; ++IM, ++IF) {
10362 const ParmVarDecl *DeclVar = (*IF);
10363 const ParmVarDecl *ImplVar = (*IM);
10364 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10365 return false;
10366 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10367 return false;
10368 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010369
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010370 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010371}
Richard Smith053f6c62014-05-16 23:01:30 +000010372
Yaxun Liu402804b2016-12-15 08:09:08 +000010373uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010374 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010375 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010376 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010377 else
10378 AS = QT->getPointeeType().getAddressSpace();
10379
10380 return getTargetInfo().getNullPointerValue(AS);
10381}
10382
Alexander Richardson6d989432017-10-15 18:48:14 +000010383unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10384 if (isTargetAddressSpace(AS))
10385 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010386 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010387 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010388}
10389
Leonard Chanab80f3c2018-06-14 14:53:51 +000010390QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10391 assert(Ty->isFixedPointType());
10392
10393 if (Ty->isSaturatedFixedPointType()) return Ty;
10394
10395 const auto &BT = Ty->getAs<BuiltinType>();
10396 switch (BT->getKind()) {
10397 default:
10398 llvm_unreachable("Not a fixed point type!");
10399 case BuiltinType::ShortAccum:
10400 return SatShortAccumTy;
10401 case BuiltinType::Accum:
10402 return SatAccumTy;
10403 case BuiltinType::LongAccum:
10404 return SatLongAccumTy;
10405 case BuiltinType::UShortAccum:
10406 return SatUnsignedShortAccumTy;
10407 case BuiltinType::UAccum:
10408 return SatUnsignedAccumTy;
10409 case BuiltinType::ULongAccum:
10410 return SatUnsignedLongAccumTy;
10411 case BuiltinType::ShortFract:
10412 return SatShortFractTy;
10413 case BuiltinType::Fract:
10414 return SatFractTy;
10415 case BuiltinType::LongFract:
10416 return SatLongFractTy;
10417 case BuiltinType::UShortFract:
10418 return SatUnsignedShortFractTy;
10419 case BuiltinType::UFract:
10420 return SatUnsignedFractTy;
10421 case BuiltinType::ULongFract:
10422 return SatUnsignedLongFractTy;
10423 }
10424}
10425
Matt Arsenaultc65f9662018-08-02 12:14:28 +000010426LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10427 if (LangOpts.OpenCL)
10428 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10429
10430 if (LangOpts.CUDA)
10431 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10432
10433 return getLangASFromTargetAS(AS);
10434}
10435
Richard Smith053f6c62014-05-16 23:01:30 +000010436// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10437// doesn't include ASTContext.h
10438template
10439clang::LazyGenerationalUpdatePtr<
10440 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10441clang::LazyGenerationalUpdatePtr<
10442 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10443 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010444
10445unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10446 assert(Ty->isFixedPointType());
10447
10448 const auto *BT = Ty->getAs<BuiltinType>();
10449 const TargetInfo &Target = getTargetInfo();
10450 switch (BT->getKind()) {
10451 default:
10452 llvm_unreachable("Not a fixed point type!");
10453 case BuiltinType::ShortAccum:
10454 case BuiltinType::SatShortAccum:
10455 return Target.getShortAccumScale();
10456 case BuiltinType::Accum:
10457 case BuiltinType::SatAccum:
10458 return Target.getAccumScale();
10459 case BuiltinType::LongAccum:
10460 case BuiltinType::SatLongAccum:
10461 return Target.getLongAccumScale();
10462 case BuiltinType::UShortAccum:
10463 case BuiltinType::SatUShortAccum:
10464 return Target.getUnsignedShortAccumScale();
10465 case BuiltinType::UAccum:
10466 case BuiltinType::SatUAccum:
10467 return Target.getUnsignedAccumScale();
10468 case BuiltinType::ULongAccum:
10469 case BuiltinType::SatULongAccum:
10470 return Target.getUnsignedLongAccumScale();
10471 case BuiltinType::ShortFract:
10472 case BuiltinType::SatShortFract:
10473 return Target.getShortFractScale();
10474 case BuiltinType::Fract:
10475 case BuiltinType::SatFract:
10476 return Target.getFractScale();
10477 case BuiltinType::LongFract:
10478 case BuiltinType::SatLongFract:
10479 return Target.getLongFractScale();
10480 case BuiltinType::UShortFract:
10481 case BuiltinType::SatUShortFract:
10482 return Target.getUnsignedShortFractScale();
10483 case BuiltinType::UFract:
10484 case BuiltinType::SatUFract:
10485 return Target.getUnsignedFractScale();
10486 case BuiltinType::ULongFract:
10487 case BuiltinType::SatULongFract:
10488 return Target.getUnsignedLongFractScale();
10489 }
10490}
10491
10492unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10493 assert(Ty->isFixedPointType());
10494
10495 const auto *BT = Ty->getAs<BuiltinType>();
10496 const TargetInfo &Target = getTargetInfo();
10497 switch (BT->getKind()) {
10498 default:
10499 llvm_unreachable("Not a fixed point type!");
10500 case BuiltinType::ShortAccum:
10501 case BuiltinType::SatShortAccum:
10502 return Target.getShortAccumIBits();
10503 case BuiltinType::Accum:
10504 case BuiltinType::SatAccum:
10505 return Target.getAccumIBits();
10506 case BuiltinType::LongAccum:
10507 case BuiltinType::SatLongAccum:
10508 return Target.getLongAccumIBits();
10509 case BuiltinType::UShortAccum:
10510 case BuiltinType::SatUShortAccum:
10511 return Target.getUnsignedShortAccumIBits();
10512 case BuiltinType::UAccum:
10513 case BuiltinType::SatUAccum:
10514 return Target.getUnsignedAccumIBits();
10515 case BuiltinType::ULongAccum:
10516 case BuiltinType::SatULongAccum:
10517 return Target.getUnsignedLongAccumIBits();
10518 case BuiltinType::ShortFract:
10519 case BuiltinType::SatShortFract:
10520 case BuiltinType::Fract:
10521 case BuiltinType::SatFract:
10522 case BuiltinType::LongFract:
10523 case BuiltinType::SatLongFract:
10524 case BuiltinType::UShortFract:
10525 case BuiltinType::SatUShortFract:
10526 case BuiltinType::UFract:
10527 case BuiltinType::SatUFract:
10528 case BuiltinType::ULongFract:
10529 case BuiltinType::SatULongFract:
10530 return 0;
10531 }
10532}
Leonard Chana6779422018-08-06 16:42:37 +000010533
10534FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
Erich Keane8e772162019-01-18 19:31:54 +000010535 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
10536 "Can only get the fixed point semantics for a "
10537 "fixed point or integer type.");
Leonard Chan2044ac82019-01-16 18:13:59 +000010538 if (Ty->isIntegerType())
10539 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
10540 Ty->isSignedIntegerType());
10541
Leonard Chana6779422018-08-06 16:42:37 +000010542 bool isSigned = Ty->isSignedFixedPointType();
10543 return FixedPointSemantics(
10544 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10545 Ty->isSaturatedFixedPointType(),
10546 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10547}
10548
10549APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10550 assert(Ty->isFixedPointType());
10551 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10552}
10553
10554APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10555 assert(Ty->isFixedPointType());
10556 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10557}
Leonard Chan2044ac82019-01-16 18:13:59 +000010558
10559QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
10560 assert(Ty->isUnsignedFixedPointType() &&
10561 "Expected unsigned fixed point type");
10562 const auto *BTy = Ty->getAs<BuiltinType>();
10563
10564 switch (BTy->getKind()) {
10565 case BuiltinType::UShortAccum:
10566 return ShortAccumTy;
10567 case BuiltinType::UAccum:
10568 return AccumTy;
10569 case BuiltinType::ULongAccum:
10570 return LongAccumTy;
10571 case BuiltinType::SatUShortAccum:
10572 return SatShortAccumTy;
10573 case BuiltinType::SatUAccum:
10574 return SatAccumTy;
10575 case BuiltinType::SatULongAccum:
10576 return SatLongAccumTy;
10577 case BuiltinType::UShortFract:
10578 return ShortFractTy;
10579 case BuiltinType::UFract:
10580 return FractTy;
10581 case BuiltinType::ULongFract:
10582 return LongFractTy;
10583 case BuiltinType::SatUShortFract:
10584 return SatShortFractTy;
10585 case BuiltinType::SatUFract:
10586 return SatFractTy;
10587 case BuiltinType::SatULongFract:
10588 return SatLongFractTy;
10589 default:
10590 llvm_unreachable("Unexpected unsigned fixed point type");
10591 }
10592}