blob: ea13dcb6506e0e30626d22f8361889dbb18be7f3 [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;
Fangrui Song7264a472019-07-03 08:13:17 +0000231 assert(Comment ==
232 llvm::lower_bound(RawComments, &CommentAtDeclLoc, Compare));
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000233 } else {
234 // Slow path.
Fangrui Song7264a472019-07-03 08:13:17 +0000235 Comment = llvm::lower_bound(RawComments, &CommentAtDeclLoc, Compare);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000236 }
237 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000238
239 // Decompose the location for the declaration and find the beginning of the
240 // file buffer.
241 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
242
243 // First check whether we have a trailing comment.
244 if (Comment != RawComments.end() &&
David L. Jones13d5a872018-03-02 00:07:45 +0000245 ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
246 && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000247 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000248 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000249 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000250 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000251 // Check that Doxygen trailing comment comes after the declaration, starts
252 // on the same line and in the same file as the declaration.
253 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
254 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
255 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
256 CommentBeginDecomp.second)) {
Jan Korous1652d812019-05-13 17:52:09 +0000257 (**Comment).setAttached();
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000258 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000259 }
260 }
261
262 // The comment just after the declaration was not a trailing comment.
263 // Let's look at the previous comment.
264 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000265 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000266 --Comment;
267
268 // Check that we actually have a non-member Doxygen comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000269 if (!((*Comment)->isDocumentation() ||
270 LangOpts.CommentOpts.ParseAllComments) ||
271 (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000272 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000273
274 // Decompose the end of the comment.
275 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000276 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000277
278 // If the comment and the declaration aren't in the same file, then they
279 // aren't related.
280 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000281 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000282
283 // Get the corresponding buffer.
284 bool Invalid = false;
285 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
286 &Invalid).data();
287 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000288 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000289
290 // Extract text between the comment and declaration.
291 StringRef Text(Buffer + CommentEndDecomp.second,
292 DeclLocDecomp.second - CommentEndDecomp.second);
293
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000294 // There should be no other declarations or preprocessor directives between
295 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000296 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000297 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000298
Jan Korous1652d812019-05-13 17:52:09 +0000299 (**Comment).setAttached();
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000300 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000301}
302
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000303/// If we have a 'templated' declaration for a template, adjust 'D' to
304/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000305/// If we have an implicit instantiation, adjust 'D' to refer to template.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000306static const Decl *adjustDeclToTemplate(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000307 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000308 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000309 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000310 return FTD;
311
312 // Nothing to do if function is not an implicit instantiation.
313 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
314 return D;
315
316 // Function is an implicit instantiation of a function template?
317 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
318 return FTD;
319
320 // Function is instantiated from a member definition of a class template?
321 if (const FunctionDecl *MemberDecl =
322 FD->getInstantiatedFromMemberFunction())
323 return MemberDecl;
324
325 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000326 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000327 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000328 // Static data member is instantiated from a member definition of a class
329 // template?
330 if (VD->isStaticDataMember())
331 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
332 return MemberDecl;
333
334 return D;
335 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000336 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000337 // Is this class declaration part of a class template?
338 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
339 return CTD;
340
341 // Class is an implicit instantiation of a class template or partial
342 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000343 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000344 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
345 return D;
346 llvm::PointerUnion<ClassTemplateDecl *,
347 ClassTemplatePartialSpecializationDecl *>
348 PU = CTSD->getSpecializedTemplateOrPartial();
349 return PU.is<ClassTemplateDecl*>() ?
350 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
351 static_cast<const Decl*>(
352 PU.get<ClassTemplatePartialSpecializationDecl *>());
353 }
354
355 // Class is instantiated from a member definition of a class template?
356 if (const MemberSpecializationInfo *Info =
357 CRD->getMemberSpecializationInfo())
358 return Info->getInstantiatedFrom();
359
360 return D;
361 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000362 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000363 // Enum is instantiated from a member definition of a class template?
364 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
365 return MemberDecl;
366
367 return D;
368 }
369 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000370 return D;
371}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000372
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000373const RawComment *ASTContext::getRawCommentForAnyRedecl(
374 const Decl *D,
375 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000376 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000377
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000378 // Check whether we have cached a comment for this declaration already.
379 {
380 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
381 RedeclComments.find(D);
382 if (Pos != RedeclComments.end()) {
383 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000384 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
385 if (OriginalDecl)
386 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000387 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000388 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000389 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000390 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000391
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000392 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000393 const RawComment *RC = nullptr;
394 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000395 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000396 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000397 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000398 if (Pos != RedeclComments.end()) {
399 const RawCommentAndCacheFlags &Raw = Pos->second;
400 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
401 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000402 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000403 break;
404 }
405 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000406 RC = getRawCommentForDeclNoCache(I);
407 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000408 RawCommentAndCacheFlags Raw;
409 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000410 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
411 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000412 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000413 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000414 } else
415 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000416 Raw.setOriginalDecl(I);
417 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000418 if (RC)
419 break;
420 }
421 }
422
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000423 // If we found a comment, it should be a documentation comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000424 assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000425
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000426 if (OriginalDecl)
427 *OriginalDecl = OriginalDeclForRC;
428
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000429 // Update cache for every declaration in the redeclaration chain.
430 RawCommentAndCacheFlags Raw;
431 Raw.setRaw(RC);
432 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000433 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000434
Aaron Ballman86c93902014-03-06 23:45:36 +0000435 for (auto I : D->redecls()) {
436 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000437 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
438 R = Raw;
439 }
440
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000441 return RC;
442}
443
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000444static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
445 SmallVectorImpl<const NamedDecl *> &Redeclared) {
446 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000447 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000448 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
449 if (!ID)
450 return;
451 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000452 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000453 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000454 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000455 ObjCMethod->isInstanceMethod()))
456 Redeclared.push_back(RedeclaredMethod);
457 }
458 }
459}
460
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000461comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
462 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000463 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000464 ThisDeclInfo->CommentDecl = D;
465 ThisDeclInfo->IsFilled = false;
466 ThisDeclInfo->fill();
467 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000468 if (!ThisDeclInfo->TemplateParameters)
469 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000470 comments::FullComment *CFC =
471 new (*this) comments::FullComment(FC->getBlocks(),
472 ThisDeclInfo);
473 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000474}
475
Richard Smithb39b9d52013-05-21 05:24:00 +0000476comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
477 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000478 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000479}
480
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000481comments::FullComment *ASTContext::getCommentForDecl(
482 const Decl *D,
483 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000484 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000485 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000486 D = adjustDeclToTemplate(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000487
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000488 const Decl *Canonical = D->getCanonicalDecl();
489 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
490 ParsedComments.find(Canonical);
Fangrui Song6907ce22018-07-30 19:24:48 +0000491
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000492 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000493 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000494 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000495 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000496 return CFC;
497 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000498 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000499 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000500
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000501 const Decl *OriginalDecl;
Fangrui Song6907ce22018-07-30 19:24:48 +0000502
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000503 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000504 if (!RC) {
505 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000506 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000507 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000508 if (OMD && OMD->isPropertyAccessor())
509 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
510 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
511 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000512 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000513 addRedeclaredMethods(OMD, Overridden);
514 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000515 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
516 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
517 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000518 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000519 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000520 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000521 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000522 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000523 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000524 if (const Decl *TD = TT->getDecl())
525 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000526 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000527 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000528 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000529 while (IC->getSuperClass()) {
530 IC = IC->getSuperClass();
531 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
532 return cloneFullComment(FC, D);
533 }
534 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000535 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000536 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
537 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
538 return cloneFullComment(FC, D);
539 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000540 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000541 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000542 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000543 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000544 for (const auto &I : RD->bases()) {
545 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000546 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000547 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000548 if (Ty.isNull())
549 continue;
550 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
551 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
552 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000553
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000554 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
555 return cloneFullComment(FC, D);
556 }
557 }
558 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000559 for (const auto &I : RD->vbases()) {
560 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000561 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000562 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000563 if (Ty.isNull())
564 continue;
565 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
566 if (!(VirtualBase= VirtualBase->getDefinition()))
567 continue;
568 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
569 return cloneFullComment(FC, D);
570 }
571 }
572 }
Craig Topper36250ad2014-05-12 05:36:57 +0000573 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000574 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000575
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000576 // If the RawComment was attached to other redeclaration of this Decl, we
577 // should parse the comment in context of that other Decl. This is important
578 // because comments can contain references to parameter names which can be
579 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000580 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000581 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000582
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000583 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000584 ParsedComments[Canonical] = FC;
585 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000586}
587
Fangrui Song6907ce22018-07-30 19:24:48 +0000588void
589ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000590 TemplateTemplateParmDecl *Parm) {
591 ID.AddInteger(Parm->getDepth());
592 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000593 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000594
595 TemplateParameterList *Params = Parm->getTemplateParameters();
596 ID.AddInteger(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000597 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000598 PEnd = Params->end();
599 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000600 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000601 ID.AddInteger(0);
602 ID.AddBoolean(TTP->isParameterPack());
603 continue;
604 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000605
Eugene Zelenko7855e772018-04-03 00:11:50 +0000606 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000607 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000608 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000609 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000610 if (NTTP->isExpandedParameterPack()) {
611 ID.AddBoolean(true);
612 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000613 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
614 QualType T = NTTP->getExpansionType(I);
615 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
616 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000617 } else
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000618 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000619 continue;
620 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000621
Eugene Zelenko7855e772018-04-03 00:11:50 +0000622 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000623 ID.AddInteger(2);
624 Profile(ID, TTP);
625 }
626}
627
628TemplateTemplateParmDecl *
629ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000630 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000631 // Check if we already have a canonical template template parameter.
632 llvm::FoldingSetNodeID ID;
633 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000634 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000635 CanonicalTemplateTemplateParm *Canonical
636 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
637 if (Canonical)
638 return Canonical->getParam();
Fangrui Song6907ce22018-07-30 19:24:48 +0000639
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000640 // Build a canonical template parameter list.
641 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000642 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000643 CanonParams.reserve(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000644 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000645 PEnd = Params->end();
646 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000647 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000648 CanonParams.push_back(
Fangrui Song6907ce22018-07-30 19:24:48 +0000649 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000650 SourceLocation(),
651 SourceLocation(),
652 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000653 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000654 TTP->isParameterPack()));
Eugene Zelenko7855e772018-04-03 00:11:50 +0000655 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000656 QualType T = getCanonicalType(NTTP->getType());
657 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
658 NonTypeTemplateParmDecl *Param;
659 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000660 SmallVector<QualType, 2> ExpandedTypes;
661 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000662 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
663 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
664 ExpandedTInfos.push_back(
665 getTrivialTypeSourceInfo(ExpandedTypes.back()));
666 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000667
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000668 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000669 SourceLocation(),
670 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000671 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000672 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000673 T,
674 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000675 ExpandedTypes,
676 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000677 } else {
678 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000679 SourceLocation(),
680 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000681 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000682 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000683 T,
684 NTTP->isParameterPack(),
685 TInfo);
686 }
687 CanonParams.push_back(Param);
688
689 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000690 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
691 cast<TemplateTemplateParmDecl>(*P)));
692 }
693
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000694 assert(!TTP->getRequiresClause() &&
695 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000696 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000697
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000698 TemplateTemplateParmDecl *CanonTTP
Fangrui Song6907ce22018-07-30 19:24:48 +0000699 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000700 SourceLocation(), TTP->getDepth(),
Fangrui Song6907ce22018-07-30 19:24:48 +0000701 TTP->getPosition(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000702 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000703 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000704 TemplateParameterList::Create(*this, SourceLocation(),
705 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000706 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000707 SourceLocation(),
708 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000709
710 // Get the new insert position for the node we care about.
711 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000712 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000713 (void)Canonical;
714
715 // Create the canonical template template parameter entry.
716 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
717 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
718 return CanonTTP;
719}
720
Charles Davis53c59df2010-08-16 03:33:14 +0000721CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000722 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000723
John McCall359b8852013-01-25 22:30:49 +0000724 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000725 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000726 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000727 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000728 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000729 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000730 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000731 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000732 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000733 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000734 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000735 return CreateMicrosoftCXXABI(*this);
736 }
David Blaikie8a40f702012-01-17 06:56:22 +0000737 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000738}
739
Alexander Richardson6d989432017-10-15 18:48:14 +0000740static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
741 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000742 if (LOpts.FakeAddressSpaceMap) {
743 // The fake address space map must have a distinct entry for each
744 // language-specific address space.
745 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000746 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000747 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000748 3, // opencl_local
749 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000750 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000751 4, // opencl_generic
752 5, // cuda_device
753 6, // cuda_constant
754 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000755 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000756 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000757 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000758 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000759 }
760}
761
David Tweed31d09b02013-09-13 12:04:22 +0000762static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
763 const LangOptions &LangOpts) {
764 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000765 case LangOptions::ASMM_Target:
766 return TI.useAddressSpaceMapMangling();
767 case LangOptions::ASMM_On:
768 return true;
769 case LangOptions::ASMM_Off:
770 return false;
771 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000772 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000773}
774
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000775ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000776 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000777 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000778 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
779 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000780 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000781 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000782 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000783 LangOpts.XRayNeverInstrumentFiles,
784 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000785 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000786 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000787 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
788 CompCategories(this_()), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000789 TUDecl = TranslationUnitDecl::Create(*this);
Sam McCall814e7972018-11-14 10:33:30 +0000790 TraversalScope = {TUDecl};
Daniel Dunbar221fa942008-08-11 04:54:23 +0000791}
792
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000793ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000794 // Release the DenseMaps associated with DeclContext objects.
795 // FIXME: Is this the ideal solution?
796 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000797
Manuel Klimeka7328992013-06-03 13:51:33 +0000798 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000799 for (auto &Pair : Deallocations)
800 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000801
Ted Kremenek076baeb2010-06-08 23:00:58 +0000802 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000803 // because they can contain DenseMaps.
804 for (llvm::DenseMap<const ObjCContainerDecl*,
805 const ASTRecordLayout*>::iterator
806 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
807 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000808 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000809 R->Destroy(*this);
810
Ted Kremenek076baeb2010-06-08 23:00:58 +0000811 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
812 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
813 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000814 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000815 R->Destroy(*this);
816 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000817
Douglas Gregor561eceb2010-08-30 16:49:28 +0000818 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
819 AEnd = DeclAttrs.end();
820 A != AEnd; ++A)
821 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000822
David Majnemere694f3e2015-08-14 14:43:50 +0000823 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
824 MaterializedTemporaryValues)
825 MTVPair.second->~APValue();
826
Richard Smith423f46f2016-07-20 21:38:26 +0000827 for (const auto &Value : ModuleInitializers)
828 Value.second->~PerModuleInitializers();
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000829
830 for (APValue *Value : APValueCleanups)
831 Value->~APValue();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000832}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000833
Sam McCall814e7972018-11-14 10:33:30 +0000834class ASTContext::ParentMap {
835 /// Contains parents of a node.
836 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
837
838 /// Maps from a node to its parents. This is used for nodes that have
839 /// pointer identity only, which are more common and we can save space by
840 /// only storing a unique pointer to them.
841 using ParentMapPointers = llvm::DenseMap<
842 const void *,
843 llvm::PointerUnion4<const Decl *, const Stmt *,
844 ast_type_traits::DynTypedNode *, ParentVector *>>;
845
846 /// Parent map for nodes without pointer identity. We store a full
847 /// DynTypedNode for all keys.
848 using ParentMapOtherNodes = llvm::DenseMap<
849 ast_type_traits::DynTypedNode,
850 llvm::PointerUnion4<const Decl *, const Stmt *,
851 ast_type_traits::DynTypedNode *, ParentVector *>>;
852
853 ParentMapPointers PointerParents;
854 ParentMapOtherNodes OtherParents;
855 class ASTVisitor;
856
857 static ast_type_traits::DynTypedNode
858 getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
859 if (const auto *D = U.dyn_cast<const Decl *>())
860 return ast_type_traits::DynTypedNode::create(*D);
861 if (const auto *S = U.dyn_cast<const Stmt *>())
862 return ast_type_traits::DynTypedNode::create(*S);
863 return *U.get<ast_type_traits::DynTypedNode *>();
864 }
865
866 template <typename NodeTy, typename MapTy>
867 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
868 const MapTy &Map) {
869 auto I = Map.find(Node);
870 if (I == Map.end()) {
871 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
872 }
873 if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
874 return llvm::makeArrayRef(*V);
875 }
876 return getSingleDynTypedNodeFromParentMap(I->second);
877 }
878
879public:
880 ParentMap(ASTContext &Ctx);
881 ~ParentMap() {
882 for (const auto &Entry : PointerParents) {
883 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
884 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
885 } else if (Entry.second.is<ParentVector *>()) {
886 delete Entry.second.get<ParentVector *>();
887 }
888 }
889 for (const auto &Entry : OtherParents) {
890 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
891 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
892 } else if (Entry.second.is<ParentVector *>()) {
893 delete Entry.second.get<ParentVector *>();
894 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000895 }
896 }
Sam McCall814e7972018-11-14 10:33:30 +0000897
898 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
899 if (Node.getNodeKind().hasPointerIdentity())
900 return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
901 return getDynNodeFromMap(Node, OtherParents);
Manuel Klimek95403e62014-05-21 13:28:59 +0000902 }
Sam McCall814e7972018-11-14 10:33:30 +0000903};
904
905void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
906 TraversalScope = TopLevelDecls;
907 Parents.reset();
Manuel Klimek95403e62014-05-21 13:28:59 +0000908}
909
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000910void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000911 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000912}
913
Mike Stump11289f42009-09-09 15:08:12 +0000914void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000915ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000916 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000917}
918
Chris Lattner4eb445d2007-01-26 01:27:23 +0000919void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000920 llvm::errs() << "\n*** AST Context Stats:\n";
921 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000922
Douglas Gregora30d0462009-05-26 14:40:08 +0000923 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000924#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000925#define ABSTRACT_TYPE(Name, Parent)
926#include "clang/AST/TypeNodes.def"
927 0 // Extra
928 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000929
Chris Lattner4eb445d2007-01-26 01:27:23 +0000930 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
931 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000932 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000933 }
934
Douglas Gregora30d0462009-05-26 14:40:08 +0000935 unsigned Idx = 0;
936 unsigned TotalBytes = 0;
937#define TYPE(Name, Parent) \
938 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000939 llvm::errs() << " " << counts[Idx] << " " << #Name \
Bruno Ricci58e03222018-08-06 15:17:32 +0000940 << " types, " << sizeof(Name##Type) << " each " \
941 << "(" << counts[Idx] * sizeof(Name##Type) \
942 << " bytes)\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000943 TotalBytes += counts[Idx] * sizeof(Name##Type); \
944 ++Idx;
945#define ABSTRACT_TYPE(Name, Parent)
946#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000947
Chandler Carruth3c147a72011-07-04 05:32:14 +0000948 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
949
Douglas Gregor7454c562010-07-02 20:37:36 +0000950 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000951 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
952 << NumImplicitDefaultConstructors
953 << " implicit default constructors created\n";
954 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
955 << NumImplicitCopyConstructors
956 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000957 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000958 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
959 << NumImplicitMoveConstructors
960 << " implicit move constructors created\n";
961 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
962 << NumImplicitCopyAssignmentOperators
963 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000964 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000965 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
966 << NumImplicitMoveAssignmentOperators
967 << " implicit move assignment operators created\n";
968 llvm::errs() << NumImplicitDestructorsDeclared << "/"
969 << NumImplicitDestructors
970 << " implicit destructors created\n";
971
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000972 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000973 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000974 ExternalSource->PrintStats();
975 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000976
Douglas Gregor5b11d492010-07-25 17:53:33 +0000977 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000978}
979
Richard Smith42413142015-05-15 20:05:43 +0000980void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
981 bool NotifyListeners) {
982 if (NotifyListeners)
983 if (auto *Listener = getASTMutationListener())
984 Listener->RedefinedHiddenDefinition(ND, M);
985
Richard Smith13897eb2018-09-12 23:37:00 +0000986 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
Richard Smith42413142015-05-15 20:05:43 +0000987}
988
989void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
Richard Smith20fbdb32018-09-12 02:13:46 +0000990 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
Richard Smith42413142015-05-15 20:05:43 +0000991 if (It == MergedDefModules.end())
992 return;
993
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000994 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000995 llvm::DenseSet<Module*> Found;
996 for (Module *&M : Merged)
997 if (!Found.insert(M).second)
998 M = nullptr;
999 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1000}
1001
Richard Smithdc1f0422016-07-20 19:10:16 +00001002void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1003 if (LazyInitializers.empty())
1004 return;
1005
1006 auto *Source = Ctx.getExternalSource();
1007 assert(Source && "lazy initializers but no external source");
1008
1009 auto LazyInits = std::move(LazyInitializers);
1010 LazyInitializers.clear();
1011
1012 for (auto ID : LazyInits)
1013 Initializers.push_back(Source->GetExternalDecl(ID));
1014
1015 assert(LazyInitializers.empty() &&
1016 "GetExternalDecl for lazy module initializer added more inits");
1017}
1018
1019void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1020 // One special case: if we add a module initializer that imports another
1021 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001022 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001023 auto It = ModuleInitializers.find(ID->getImportedModule());
1024
1025 // Maybe the ImportDecl does nothing at all. (Common case.)
1026 if (It == ModuleInitializers.end())
1027 return;
1028
1029 // Maybe the ImportDecl only imports another ImportDecl.
1030 auto &Imported = *It->second;
1031 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1032 Imported.resolve(*this);
1033 auto *OnlyDecl = Imported.Initializers.front();
1034 if (isa<ImportDecl>(OnlyDecl))
1035 D = OnlyDecl;
1036 }
1037 }
1038
1039 auto *&Inits = ModuleInitializers[M];
1040 if (!Inits)
1041 Inits = new (*this) PerModuleInitializers;
1042 Inits->Initializers.push_back(D);
1043}
1044
1045void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1046 auto *&Inits = ModuleInitializers[M];
1047 if (!Inits)
1048 Inits = new (*this) PerModuleInitializers;
1049 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1050 IDs.begin(), IDs.end());
1051}
1052
Eugene Zelenko7855e772018-04-03 00:11:50 +00001053ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001054 auto It = ModuleInitializers.find(M);
Fangrui Song6907ce22018-07-30 19:24:48 +00001055 if (It == ModuleInitializers.end())
Richard Smithdc1f0422016-07-20 19:10:16 +00001056 return None;
1057
1058 auto *Inits = It->second;
1059 Inits->resolve(*this);
1060 return Inits->Initializers;
1061}
1062
Richard Smithf19e1272015-03-07 00:04:49 +00001063ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1064 if (!ExternCContext)
1065 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1066
1067 return ExternCContext;
1068}
1069
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001070BuiltinTemplateDecl *
1071ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1072 const IdentifierInfo *II) const {
1073 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1074 BuiltinTemplate->setImplicit();
1075 TUDecl->addDecl(BuiltinTemplate);
1076
1077 return BuiltinTemplate;
1078}
1079
1080BuiltinTemplateDecl *
1081ASTContext::getMakeIntegerSeqDecl() const {
1082 if (!MakeIntegerSeqDecl)
1083 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1084 getMakeIntegerSeqName());
1085 return MakeIntegerSeqDecl;
1086}
1087
Eric Fiselier6ad68552016-07-01 01:24:09 +00001088BuiltinTemplateDecl *
1089ASTContext::getTypePackElementDecl() const {
1090 if (!TypePackElementDecl)
1091 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1092 getTypePackElementName());
1093 return TypePackElementDecl;
1094}
1095
Alp Toker2dea15b2013-12-17 01:22:38 +00001096RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1097 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001098 SourceLocation Loc;
1099 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001100 if (getLangOpts().CPlusPlus)
1101 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1102 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001103 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001104 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1105 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001106 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001107 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1108 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001109 return NewDecl;
1110}
1111
1112TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1113 StringRef Name) const {
1114 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1115 TypedefDecl *NewDecl = TypedefDecl::Create(
1116 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1117 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1118 NewDecl->setImplicit();
1119 return NewDecl;
1120}
1121
Douglas Gregor801c99d2011-08-12 06:49:56 +00001122TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001123 if (!Int128Decl)
1124 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001125 return Int128Decl;
1126}
1127
1128TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001129 if (!UInt128Decl)
1130 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001131 return UInt128Decl;
1132}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001133
John McCall48f2d582009-10-23 23:03:21 +00001134void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001135 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001136 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001137 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001138}
1139
Artem Belevichb5bc9232015-09-22 17:23:22 +00001140void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1141 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001142 assert((!this->Target || this->Target == &Target) &&
1143 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001144 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001145
Douglas Gregore8bbc122011-09-02 00:18:52 +00001146 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001147 this->AuxTarget = AuxTarget;
1148
Douglas Gregore8bbc122011-09-02 00:18:52 +00001149 ABI.reset(createCXXABI(Target));
1150 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001151 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001152
Chris Lattner970e54e2006-11-12 00:37:36 +00001153 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001154 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001155
Chris Lattner970e54e2006-11-12 00:37:36 +00001156 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001157 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001158 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001159 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001160 InitBuiltinType(CharTy, BuiltinType::Char_S);
1161 else
1162 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001163 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001164 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1165 InitBuiltinType(ShortTy, BuiltinType::Short);
1166 InitBuiltinType(IntTy, BuiltinType::Int);
1167 InitBuiltinType(LongTy, BuiltinType::Long);
1168 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001169
Chris Lattner970e54e2006-11-12 00:37:36 +00001170 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001171 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1172 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1173 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1174 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1175 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001176
Chris Lattner970e54e2006-11-12 00:37:36 +00001177 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001178 InitBuiltinType(FloatTy, BuiltinType::Float);
1179 InitBuiltinType(DoubleTy, BuiltinType::Double);
1180 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001181
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001182 // GNU extension, __float128 for IEEE quadruple precision
1183 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1184
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001185 // C11 extension ISO/IEC TS 18661-3
1186 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1187
Leonard Chanf921d852018-06-04 16:07:52 +00001188 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001189 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1190 InitBuiltinType(AccumTy, BuiltinType::Accum);
1191 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1192 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1193 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1194 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1195 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1196 InitBuiltinType(FractTy, BuiltinType::Fract);
1197 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1198 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1199 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1200 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1201 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1202 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1203 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1204 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1205 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1206 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1207 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1208 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1209 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1210 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1211 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1212 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001213
Chris Lattnerf122cef2009-04-30 02:43:43 +00001214 // GNU extension, 128-bit integers.
1215 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1216 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1217
Hans Wennborg0d81e012013-05-10 10:08:40 +00001218 // C++ 3.9.1p5
1219 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1220 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1221 else // -fshort-wchar makes wchar_t be unsigned.
1222 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1223 if (LangOpts.CPlusPlus && LangOpts.WChar)
1224 WideCharTy = WCharTy;
1225 else {
1226 // C99 (or C++ using -fno-wchar).
1227 WideCharTy = getFromTargetType(Target.getWCharType());
1228 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001229
James Molloy36365542012-05-04 10:55:22 +00001230 WIntTy = getFromTargetType(Target.getWIntType());
1231
Richard Smith3a8244d2018-05-01 05:02:45 +00001232 // C++20 (proposed)
1233 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1234
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001235 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1236 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1237 else // C99
1238 Char16Ty = getFromTargetType(Target.getChar16Type());
1239
1240 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1241 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1242 else // C99
1243 Char32Ty = getFromTargetType(Target.getChar32Type());
1244
Douglas Gregor4619e432008-12-05 23:32:09 +00001245 // Placeholder type for type-dependent expressions whose type is
1246 // completely unknown. No code should ever check a type against
1247 // DependentTy and users should never see it; however, it is here to
1248 // help diagnose failures to properly check for type-dependent
1249 // expressions.
1250 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001251
John McCall36e7fe32010-10-12 00:20:44 +00001252 // Placeholder type for functions.
1253 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1254
John McCall0009fcc2011-04-26 20:42:42 +00001255 // Placeholder type for bound members.
1256 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1257
John McCall526ab472011-10-25 17:37:35 +00001258 // Placeholder type for pseudo-objects.
1259 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1260
John McCall31996342011-04-07 08:22:57 +00001261 // "any" type; useful for debugger-like clients.
1262 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1263
John McCall8a6b59a2011-10-17 18:09:15 +00001264 // Placeholder type for unbridged ARC casts.
1265 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1266
Eli Friedman34866c72012-08-31 00:14:07 +00001267 // Placeholder type for builtin functions.
1268 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1269
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001270 // Placeholder type for OMP array sections.
1271 if (LangOpts.OpenMP)
1272 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1273
Chris Lattner970e54e2006-11-12 00:37:36 +00001274 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001275 FloatComplexTy = getComplexType(FloatTy);
1276 DoubleComplexTy = getComplexType(DoubleTy);
1277 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001278 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001279
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001280 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001281 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1282 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001283 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001284
Alexey Bader954ba212016-04-08 13:40:33 +00001285 if (LangOpts.OpenCL) {
1286#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1287 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001288#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001289
Guy Benyei61054192013-02-07 10:55:47 +00001290 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001291 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001292 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1293 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001294 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001295
1296#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1297 InitBuiltinType(Id##Ty, BuiltinType::Id);
1298#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001299 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001300
Ted Kremeneke65b0862012-03-06 20:05:56 +00001301 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001302 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1303 SignedCharTy : BoolTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001304
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001305 ObjCConstantStringType = QualType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001306
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001307 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001308
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001309 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001310 if (LangOpts.OpenCLVersion >= 200) {
1311 auto Q = VoidTy.getQualifiers();
1312 Q.setAddressSpace(LangAS::opencl_generic);
1313 VoidPtrTy = getPointerType(getCanonicalType(
1314 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1315 } else {
1316 VoidPtrTy = getPointerType(VoidTy);
1317 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001318
1319 // nullptr type (C++0x 2.14.7)
1320 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001321
1322 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1323 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001324
1325 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001326 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001327}
1328
David Blaikie9c902b52011-09-25 23:23:43 +00001329DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001330 return SourceMgr.getDiagnostics();
1331}
1332
Douglas Gregor561eceb2010-08-30 16:49:28 +00001333AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1334 AttrVec *&Result = DeclAttrs[D];
1335 if (!Result) {
1336 void *Mem = Allocate(sizeof(AttrVec));
1337 Result = new (Mem) AttrVec;
1338 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001339
Douglas Gregor561eceb2010-08-30 16:49:28 +00001340 return *Result;
1341}
1342
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001343/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001344void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001345 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1346 if (Pos != DeclAttrs.end()) {
1347 Pos->second->~AttrVec();
1348 DeclAttrs.erase(Pos);
1349 }
1350}
1351
Larisse Voufo39a1e502013-08-06 01:03:05 +00001352// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001353MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001354ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001355 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001356 return getTemplateOrSpecializationInfo(Var)
1357 .dyn_cast<MemberSpecializationInfo *>();
1358}
1359
1360ASTContext::TemplateOrSpecializationInfo
1361ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1362 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1363 TemplateOrInstantiation.find(Var);
1364 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001365 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001366
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001367 return Pos->second;
1368}
1369
Mike Stump11289f42009-09-09 15:08:12 +00001370void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001371ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001372 TemplateSpecializationKind TSK,
1373 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001374 assert(Inst->isStaticDataMember() && "Not a static data member");
1375 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001376 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1377 Tmpl, TSK, PointOfInstantiation));
1378}
1379
1380void
1381ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1382 TemplateOrSpecializationInfo TSI) {
1383 assert(!TemplateOrInstantiation[Inst] &&
1384 "Already noted what the variable was instantiated from");
1385 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001386}
1387
John McCalle61f2ba2009-11-18 02:36:19 +00001388NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001389ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1390 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001391 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001392 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001393
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001394 return Pos->second;
1395}
1396
1397void
Richard Smithd8a9e372016-12-18 21:39:37 +00001398ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001399 assert((isa<UsingDecl>(Pattern) ||
1400 isa<UnresolvedUsingValueDecl>(Pattern) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001401 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
John McCallb96ec562009-12-04 22:46:56 +00001402 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001403 assert((isa<UsingDecl>(Inst) ||
1404 isa<UnresolvedUsingValueDecl>(Inst) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001405 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
Richard Smithd8a9e372016-12-18 21:39:37 +00001406 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001407 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1408 InstantiatedFromUsingDecl[Inst] = Pattern;
1409}
1410
1411UsingShadowDecl *
1412ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1413 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1414 = InstantiatedFromUsingShadowDecl.find(Inst);
1415 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001416 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001417
1418 return Pos->second;
1419}
1420
1421void
1422ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1423 UsingShadowDecl *Pattern) {
1424 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1425 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001426}
1427
Anders Carlsson5da84842009-09-01 04:26:58 +00001428FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1429 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1430 = InstantiatedFromUnnamedFieldDecl.find(Field);
1431 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001432 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001433
Anders Carlsson5da84842009-09-01 04:26:58 +00001434 return Pos->second;
1435}
1436
1437void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1438 FieldDecl *Tmpl) {
1439 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1440 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1441 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1442 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001443
Anders Carlsson5da84842009-09-01 04:26:58 +00001444 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1445}
1446
Douglas Gregor832940b2010-03-02 23:58:15 +00001447ASTContext::overridden_cxx_method_iterator
1448ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001449 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001450}
1451
1452ASTContext::overridden_cxx_method_iterator
1453ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001454 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001455}
1456
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001457unsigned
1458ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001459 auto Range = overridden_methods(Method);
1460 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001461}
1462
Clement Courbet6ecaec82016-07-05 07:49:31 +00001463ASTContext::overridden_method_range
1464ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001465 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1466 OverriddenMethods.find(Method->getCanonicalDecl());
1467 if (Pos == OverriddenMethods.end())
1468 return overridden_method_range(nullptr, nullptr);
1469 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001470}
1471
Fangrui Song6907ce22018-07-30 19:24:48 +00001472void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
Douglas Gregor832940b2010-03-02 23:58:15 +00001473 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001474 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001475 OverriddenMethods[Method].push_back(Overridden);
1476}
1477
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001478void ASTContext::getOverriddenMethods(
1479 const NamedDecl *D,
1480 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001481 assert(D);
1482
Eugene Zelenko7855e772018-04-03 00:11:50 +00001483 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001484 Overridden.append(overridden_methods_begin(CXXMethod),
1485 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001486 return;
1487 }
1488
Eugene Zelenko7855e772018-04-03 00:11:50 +00001489 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001490 if (!Method)
1491 return;
1492
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001493 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1494 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001495 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001496}
1497
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001498void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1499 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1500 assert(!Import->isFromASTFile() && "Non-local import declaration");
1501 if (!FirstLocalImport) {
1502 FirstLocalImport = Import;
1503 LastLocalImport = Import;
1504 return;
1505 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001506
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001507 LastLocalImport->NextLocalImport = Import;
1508 LastLocalImport = Import;
1509}
1510
Chris Lattner53cfe802007-07-18 17:52:12 +00001511//===----------------------------------------------------------------------===//
1512// Type Sizing and Analysis
1513//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001514
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001515/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1516/// scalar floating point type.
1517const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001518 const auto *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001519 assert(BT && "Not a floating point type!");
1520 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001521 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001522 case BuiltinType::Float16:
1523 case BuiltinType::Half:
1524 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001525 case BuiltinType::Float: return Target->getFloatFormat();
1526 case BuiltinType::Double: return Target->getDoubleFormat();
Alexey Bataeve509af32019-07-09 14:09:53 +00001527 case BuiltinType::LongDouble:
1528 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1529 &Target->getLongDoubleFormat() != &AuxTarget->getLongDoubleFormat())
1530 return AuxTarget->getLongDoubleFormat();
1531 return Target->getLongDoubleFormat();
1532 case BuiltinType::Float128:
1533 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1534 &Target->getFloat128Format() != &AuxTarget->getFloat128Format())
1535 return AuxTarget->getFloat128Format();
1536 return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001537 }
1538}
1539
Rafael Espindola71eccb32013-08-08 19:53:46 +00001540CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001541 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001542
John McCall94268702010-10-08 18:24:19 +00001543 bool UseAlignAttrOnly = false;
1544 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1545 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001546
John McCall94268702010-10-08 18:24:19 +00001547 // __attribute__((aligned)) can increase or decrease alignment
1548 // *except* on a struct or struct member, where it only increases
1549 // alignment unless 'packed' is also specified.
1550 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001551 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001552 // ignore that possibility; Sema should diagnose it.
1553 if (isa<FieldDecl>(D)) {
1554 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1555 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1556 } else {
1557 UseAlignAttrOnly = true;
1558 }
1559 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001560 else if (isa<FieldDecl>(D))
Fangrui Song6907ce22018-07-30 19:24:48 +00001561 UseAlignAttrOnly =
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001562 D->hasAttr<PackedAttr>() ||
1563 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001564
John McCall4e819612011-01-20 07:57:12 +00001565 // If we're using the align attribute only, just ignore everything
1566 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001567 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001568 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001569 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001570 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001571 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001572 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001573 T = RT->getPointeeType();
1574 else
1575 T = getPointerType(RT->getPointeeType());
1576 }
Richard Smithf6d70302014-06-10 23:34:28 +00001577 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001578 if (T->isFunctionType())
1579 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1580 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001581 // Adjust alignments of declarations with array type by the
1582 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001583 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001584 unsigned MinWidth = Target->getLargeArrayMinWidth();
1585 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001586 if (isa<VariableArrayType>(arrayType))
1587 Align = std::max(Align, Target->getLargeArrayAlign());
1588 else if (isa<ConstantArrayType>(arrayType) &&
1589 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1590 Align = std::max(Align, Target->getLargeArrayAlign());
1591 }
John McCall33ddac02011-01-19 10:06:00 +00001592 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001593 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001594 if (BaseT.getQualifiers().hasUnaligned())
1595 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001596 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Tom Tanb7c6d952019-05-02 00:38:14 +00001597 if (VD->hasGlobalStorage() && !ForAlignof) {
1598 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1599 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1600 }
Ulrich Weigandfa806422013-05-06 16:23:57 +00001601 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001602 }
John McCall4e819612011-01-20 07:57:12 +00001603
1604 // Fields can be subject to extra alignment constraints, like if
1605 // the field is packed, the struct is packed, or the struct has a
1606 // a max-field-alignment constraint (#pragma pack). So calculate
1607 // the actual alignment of the field within the struct, and then
1608 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001609 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001610 const RecordDecl *Parent = Field->getParent();
1611 // We can only produce a sensible answer if the record is valid.
1612 if (!Parent->isInvalidDecl()) {
1613 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001614
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001615 // Start with the record's overall alignment.
1616 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001617
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001618 // Use the GCD of that and the offset within the record.
1619 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1620 if (Offset > 0) {
1621 // Alignment is always a power of 2, so the GCD will be a power of 2,
1622 // which means we get to do this crazy thing instead of Euclid's.
1623 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1624 if (LowBitOfOffset < FieldAlign)
1625 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1626 }
1627
1628 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001629 }
Charles Davis3fc51072010-02-23 04:52:00 +00001630 }
Chris Lattner68061312009-01-24 21:53:27 +00001631 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001632
Ken Dyckcc56c542011-01-15 18:38:59 +00001633 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001634}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001635
John McCallf1249922012-08-21 04:10:00 +00001636// getTypeInfoDataSizeInChars - Return the size of a type, in
1637// chars. If the type is a record, its data size is returned. This is
1638// the size of the memcpy that's performed when assigning this type
1639// using a trivial copy/move assignment operator.
1640std::pair<CharUnits, CharUnits>
1641ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1642 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1643
1644 // In C++, objects can sometimes be allocated into the tail padding
1645 // of a base-class subobject. We decide whether that's possible
1646 // during class layout, so here we can just trust the layout results.
1647 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001648 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001649 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1650 sizeAndAlign.first = layout.getDataSize();
1651 }
1652 }
1653
1654 return sizeAndAlign;
1655}
1656
Richard Trieu04d2d942013-05-14 21:59:17 +00001657/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1658/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1659std::pair<CharUnits, CharUnits>
1660static getConstantArrayInfoInChars(const ASTContext &Context,
1661 const ConstantArrayType *CAT) {
1662 std::pair<CharUnits, CharUnits> EltInfo =
1663 Context.getTypeInfoInChars(CAT->getElementType());
1664 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001665 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1666 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001667 "Overflow in array type char size evaluation");
1668 uint64_t Width = EltInfo.first.getQuantity() * Size;
1669 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001670 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1671 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001672 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001673 return std::make_pair(CharUnits::fromQuantity(Width),
1674 CharUnits::fromQuantity(Align));
1675}
1676
John McCall87fe5d52010-05-20 01:18:31 +00001677std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001678ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001679 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001680 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001681 TypeInfo Info = getTypeInfo(T);
1682 return std::make_pair(toCharUnitsFromBits(Info.Width),
1683 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001684}
1685
1686std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001687ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001688 return getTypeInfoInChars(T.getTypePtr());
1689}
1690
David Majnemer34b57492014-07-30 01:30:47 +00001691bool ASTContext::isAlignmentRequired(const Type *T) const {
1692 return getTypeInfo(T).AlignIsRequired;
1693}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001694
David Majnemer34b57492014-07-30 01:30:47 +00001695bool ASTContext::isAlignmentRequired(QualType T) const {
1696 return isAlignmentRequired(T.getTypePtr());
1697}
1698
Richard Smithb2f0f052016-10-10 18:54:32 +00001699unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1700 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001701 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001702 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1703 return Align;
1704
1705 // If we have an (array of) complete type, we're done.
1706 T = getBaseElementType(T);
1707 if (!T->isIncompleteType())
1708 return getTypeAlign(T);
1709
1710 // If we had an array type, its element type might be a typedef
1711 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001712 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001713 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1714 return Align;
1715
1716 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001717 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001718 return TT->getDecl()->getMaxAlignment();
1719
1720 return 0;
1721}
1722
David Majnemer34b57492014-07-30 01:30:47 +00001723TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001724 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1725 if (I != MemoizedTypeInfo.end())
1726 return I->second;
1727
1728 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1729 TypeInfo TI = getTypeInfoImpl(T);
1730 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001731 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001732}
1733
1734/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1735/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001736///
1737/// FIXME: Pointers into different addr spaces could have different sizes and
1738/// alignment requirements: getPointerInfo should take an AddrSpace, this
1739/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001740TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1741 uint64_t Width = 0;
1742 unsigned Align = 8;
1743 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001744 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001745 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001746#define TYPE(Class, Base)
1747#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001748#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001749#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001750#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1751 case Type::Class: \
1752 assert(!T->isDependentType() && "should not see dependent types here"); \
1753 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001754#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001755 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001756
Chris Lattner355332d2007-07-13 22:27:08 +00001757 case Type::FunctionNoProto:
1758 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001759 // GCC extension: alignof(function) = 32 bits
1760 Width = 0;
1761 Align = 32;
1762 break;
1763
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001764 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001765 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001766 Width = 0;
1767 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1768 break;
1769
Steve Naroff5c131802007-08-30 01:06:46 +00001770 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001771 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001772
David Majnemer34b57492014-07-30 01:30:47 +00001773 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001774 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001775 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001776 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001777 Width = EltInfo.Width * Size;
1778 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001779 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1780 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001781 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001782 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001783 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001784 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001785 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001786 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001787 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1788 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001789 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001790 // If the alignment is not a power of 2, round up to the next power of 2.
1791 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001792 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001793 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001794 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001795 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001796 // Adjust the alignment based on the target max.
1797 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1798 if (TargetVectorAlign && TargetVectorAlign < Align)
1799 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001800 break;
1801 }
Chris Lattner647fb222007-07-18 18:26:58 +00001802
Chris Lattner7570e9c2008-03-08 08:52:55 +00001803 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001804 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001805 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001806 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001807 // GCC extension: alignof(void) = 8 bits.
1808 Width = 0;
1809 Align = 8;
1810 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001811 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001812 Width = Target->getBoolWidth();
1813 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001814 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001815 case BuiltinType::Char_S:
1816 case BuiltinType::Char_U:
1817 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001818 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001819 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001820 Width = Target->getCharWidth();
1821 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001822 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001823 case BuiltinType::WChar_S:
1824 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001825 Width = Target->getWCharWidth();
1826 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001827 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001828 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001829 Width = Target->getChar16Width();
1830 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001831 break;
1832 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001833 Width = Target->getChar32Width();
1834 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001835 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001836 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001837 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001838 Width = Target->getShortWidth();
1839 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001840 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001841 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001842 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001843 Width = Target->getIntWidth();
1844 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001845 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001846 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001847 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001848 Width = Target->getLongWidth();
1849 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001850 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001851 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001852 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001853 Width = Target->getLongLongWidth();
1854 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001855 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001856 case BuiltinType::Int128:
1857 case BuiltinType::UInt128:
1858 Width = 128;
1859 Align = 128; // int128_t is 128-bit aligned on all targets.
1860 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001861 case BuiltinType::ShortAccum:
1862 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001863 case BuiltinType::SatShortAccum:
1864 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001865 Width = Target->getShortAccumWidth();
1866 Align = Target->getShortAccumAlign();
1867 break;
1868 case BuiltinType::Accum:
1869 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001870 case BuiltinType::SatAccum:
1871 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001872 Width = Target->getAccumWidth();
1873 Align = Target->getAccumAlign();
1874 break;
1875 case BuiltinType::LongAccum:
1876 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001877 case BuiltinType::SatLongAccum:
1878 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001879 Width = Target->getLongAccumWidth();
1880 Align = Target->getLongAccumAlign();
1881 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00001882 case BuiltinType::ShortFract:
1883 case BuiltinType::UShortFract:
1884 case BuiltinType::SatShortFract:
1885 case BuiltinType::SatUShortFract:
1886 Width = Target->getShortFractWidth();
1887 Align = Target->getShortFractAlign();
1888 break;
1889 case BuiltinType::Fract:
1890 case BuiltinType::UFract:
1891 case BuiltinType::SatFract:
1892 case BuiltinType::SatUFract:
1893 Width = Target->getFractWidth();
1894 Align = Target->getFractAlign();
1895 break;
1896 case BuiltinType::LongFract:
1897 case BuiltinType::ULongFract:
1898 case BuiltinType::SatLongFract:
1899 case BuiltinType::SatULongFract:
1900 Width = Target->getLongFractWidth();
1901 Align = Target->getLongFractAlign();
1902 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001903 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001904 case BuiltinType::Half:
Alexey Bataev123ad192019-02-27 20:29:45 +00001905 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
1906 !getLangOpts().OpenMPIsDevice) {
1907 Width = Target->getHalfWidth();
1908 Align = Target->getHalfAlign();
1909 } else {
1910 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1911 "Expected OpenMP device compilation.");
1912 Width = AuxTarget->getHalfWidth();
1913 Align = AuxTarget->getHalfAlign();
1914 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001915 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001916 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001917 Width = Target->getFloatWidth();
1918 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001919 break;
1920 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001921 Width = Target->getDoubleWidth();
1922 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001923 break;
1924 case BuiltinType::LongDouble:
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001925 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1926 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
1927 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
1928 Width = AuxTarget->getLongDoubleWidth();
1929 Align = AuxTarget->getLongDoubleAlign();
1930 } else {
1931 Width = Target->getLongDoubleWidth();
1932 Align = Target->getLongDoubleAlign();
1933 }
Chris Lattner6a4f7452007-12-19 19:23:28 +00001934 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001935 case BuiltinType::Float128:
Alexey Bataev123ad192019-02-27 20:29:45 +00001936 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
1937 !getLangOpts().OpenMPIsDevice) {
1938 Width = Target->getFloat128Width();
1939 Align = Target->getFloat128Align();
1940 } else {
1941 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1942 "Expected OpenMP device compilation.");
1943 Width = AuxTarget->getFloat128Width();
1944 Align = AuxTarget->getFloat128Align();
1945 }
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001946 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001947 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001948 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1949 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001950 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001951 case BuiltinType::ObjCId:
1952 case BuiltinType::ObjCClass:
1953 case BuiltinType::ObjCSel:
Fangrui Song6907ce22018-07-30 19:24:48 +00001954 Width = Target->getPointerWidth(0);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001955 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001956 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001957 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001958 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001959 case BuiltinType::OCLClkEvent:
1960 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001961 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001962#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1963 case BuiltinType::Id:
1964#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001965#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1966 case BuiltinType::Id:
1967#include "clang/Basic/OpenCLExtensionTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00001968 AS = getTargetAddressSpace(
1969 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001970 Width = Target->getPointerWidth(AS);
1971 Align = Target->getPointerAlign(AS);
1972 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001973 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001974 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001975 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001976 Width = Target->getPointerWidth(0);
1977 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001978 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001979 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001980 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001981 Width = Target->getPointerWidth(AS);
1982 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001983 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001984 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001985 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001986 // alignof and sizeof should never enter this code path here, so we go
1987 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001988 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001989 Width = Target->getPointerWidth(AS);
1990 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001991 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001992 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001993 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001994 Width = Target->getPointerWidth(AS);
1995 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001996 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001997 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001998 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00001999 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2000 Width = MPI.Width;
2001 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00002002 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002003 }
Chris Lattner647fb222007-07-18 18:26:58 +00002004 case Type::Complex: {
2005 // Complex types have the same alignment as their elements, but twice the
2006 // size.
David Majnemer34b57492014-07-30 01:30:47 +00002007 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2008 Width = EltInfo.Width * 2;
2009 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00002010 break;
2011 }
John McCall8b07ec22010-05-15 11:32:37 +00002012 case Type::ObjCObject:
2013 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00002014 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002015 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002016 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00002017 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002018 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00002019 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00002020 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002021 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00002022 break;
2023 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002024 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002025 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002026 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00002027
2028 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00002029 Width = 8;
2030 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00002031 break;
2032 }
Mike Stump11289f42009-09-09 15:08:12 +00002033
Eugene Zelenko7855e772018-04-03 00:11:50 +00002034 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00002035 const EnumDecl *ED = ET->getDecl();
2036 TypeInfo Info =
2037 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2038 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2039 Info.Align = AttrAlign;
2040 Info.AlignIsRequired = true;
2041 }
2042 return Info;
2043 }
Chris Lattner8b23c252008-04-06 22:05:18 +00002044
Eugene Zelenko7855e772018-04-03 00:11:50 +00002045 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00002046 const RecordDecl *RD = RT->getDecl();
2047 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00002048 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002049 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00002050 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00002051 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00002052 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002053
Chris Lattner63d2b362009-10-22 05:17:15 +00002054 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00002055 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2056 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00002057
Richard Smith600b5262017-01-26 20:40:47 +00002058 case Type::Auto:
2059 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002060 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00002061 assert(!A->getDeducedType().isNull() &&
2062 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00002063 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00002064 }
2065
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002066 case Type::Paren:
2067 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2068
Leonard Chanc72aaf62019-05-07 03:20:17 +00002069 case Type::MacroQualified:
2070 return getTypeInfo(
2071 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2072
Manman Rene6be26c2016-09-13 17:25:08 +00002073 case Type::ObjCTypeParam:
2074 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2075
Douglas Gregoref462e62009-04-30 17:32:17 +00002076 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002077 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002078 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002079 // If the typedef has an aligned attribute on it, it overrides any computed
2080 // alignment we have. This violates the GCC documentation (which says that
2081 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002082 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002083 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002084 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002085 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002086 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002087 AlignIsRequired = Info.AlignIsRequired;
2088 }
David Majnemer34b57492014-07-30 01:30:47 +00002089 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002090 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002091 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002092
Abramo Bagnara6150c882010-05-11 21:36:43 +00002093 case Type::Elaborated:
2094 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002095
John McCall81904512011-01-06 01:58:22 +00002096 case Type::Attributed:
2097 return getTypeInfo(
2098 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2099
Eli Friedman0dfb8892011-10-06 23:00:33 +00002100 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002101 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002102 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2103 Width = Info.Width;
2104 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002105
JF Bastien801fca22018-05-09 03:51:12 +00002106 if (!Width) {
2107 // An otherwise zero-sized type should still generate an
2108 // atomic operation.
2109 Width = Target->getCharWidth();
2110 assert(Align);
2111 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2112 // If the size of the type doesn't exceed the platform's max
2113 // atomic promotion width, make the size and alignment more
2114 // favorable to atomic operations:
2115
John McCalla8ec7eb2013-03-07 21:37:17 +00002116 // Round the size up to a power of 2.
2117 if (!llvm::isPowerOf2_64(Width))
2118 Width = llvm::NextPowerOf2(Width);
2119
2120 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002121 Align = static_cast<unsigned>(Width);
2122 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002123 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002124 break;
2125
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002126 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002127 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2128 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002129 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002130 }
Mike Stump11289f42009-09-09 15:08:12 +00002131
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002132 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002133 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002134}
2135
Momchil Velikov20208cc2018-07-30 17:48:23 +00002136unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2137 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2138 if (I != MemoizedUnadjustedAlign.end())
2139 return I->second;
2140
2141 unsigned UnadjustedAlign;
2142 if (const auto *RT = T->getAs<RecordType>()) {
2143 const RecordDecl *RD = RT->getDecl();
2144 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2145 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2146 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2147 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2148 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2149 } else {
John Brawn6c49f582019-05-22 11:42:54 +00002150 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
Momchil Velikov20208cc2018-07-30 17:48:23 +00002151 }
2152
2153 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2154 return UnadjustedAlign;
2155}
2156
Alexey Bataev00396512015-07-02 03:40:19 +00002157unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2158 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2159 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2160 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2161 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2162 getTargetInfo().getABI() == "elfv1-qpx" &&
2163 T->isSpecificBuiltinType(BuiltinType::Double))
2164 SimdAlign = 256;
2165 return SimdAlign;
2166}
2167
Ken Dyckcc56c542011-01-15 18:38:59 +00002168/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2169CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2170 return CharUnits::fromQuantity(BitSize / getCharWidth());
2171}
2172
Ken Dyckb0fcc592011-02-11 01:54:29 +00002173/// toBits - Convert a size in characters to a size in characters.
2174int64_t ASTContext::toBits(CharUnits CharSize) const {
2175 return CharSize.getQuantity() * getCharWidth();
2176}
2177
Ken Dyck8c89d592009-12-22 14:23:30 +00002178/// getTypeSizeInChars - Return the size of the specified type, in characters.
2179/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002180CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002181 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002182}
Jay Foad39c79802011-01-12 09:06:06 +00002183CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002184 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002185}
2186
Fangrui Song6907ce22018-07-30 19:24:48 +00002187/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002188/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002189CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002190 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002191}
Jay Foad39c79802011-01-12 09:06:06 +00002192CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002193 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002194}
2195
Momchil Velikov20208cc2018-07-30 17:48:23 +00002196/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2197/// type, in characters, before alignment adustments. This method does
2198/// not work on incomplete types.
2199CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2200 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2201}
2202CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2203 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2204}
2205
Chris Lattnera3402cd2009-01-27 18:08:34 +00002206/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2207/// type for the current target in bits. This can be different than the ABI
2208/// alignment in cases where it is beneficial for performance to overalign
2209/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002210unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002211 TypeInfo TI = getTypeInfo(T);
2212 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002213
David Majnemere1544562015-04-24 01:25:05 +00002214 T = T->getBaseElementTypeUnsafe();
2215
2216 // The preferred alignment of member pointers is that of a pointer.
2217 if (T->isMemberPointerType())
2218 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2219
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002220 if (!Target->allowsLargerPreferedTypeAlignment())
2221 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002222
Eli Friedman7ab09572009-05-25 21:27:19 +00002223 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002224 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002225 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002226 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002227 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002228 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002229 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2230 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002231 // Don't increase the alignment if an alignment attribute was specified on a
2232 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002233 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002234 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002235
Chris Lattnera3402cd2009-01-27 18:08:34 +00002236 return ABIAlign;
2237}
2238
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002239/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2240/// for __attribute__((aligned)) on this target, to be used if no alignment
2241/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002242unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002243 return getTargetInfo().getDefaultAlignForAttributeAligned();
2244}
2245
Ulrich Weigandfa806422013-05-06 16:23:57 +00002246/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2247/// to a global variable of the specified type.
2248unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
Tom Tanb7c6d952019-05-02 00:38:14 +00002249 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2250 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
Ulrich Weigandfa806422013-05-06 16:23:57 +00002251}
2252
2253/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2254/// should be given to a global variable of the specified type.
2255CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2256 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2257}
2258
David Majnemer08ef2ba2015-06-23 20:34:18 +00002259CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2260 CharUnits Offset = CharUnits::Zero();
2261 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2262 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2263 Offset += Layout->getBaseClassOffset(Base);
2264 Layout = &getASTRecordLayout(Base);
2265 }
2266 return Offset;
2267}
2268
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002269/// DeepCollectObjCIvars -
2270/// This routine first collects all declared, but not synthesized, ivars in
2271/// super class and then collects all ivars, including those synthesized for
2272/// current class. This routine is used for implementation of current class
2273/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002274void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2275 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002276 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002277 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2278 DeepCollectObjCIvars(SuperClass, false, Ivars);
2279 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002280 for (const auto *I : OI->ivars())
2281 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002282 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002283 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Fangrui Song6907ce22018-07-30 19:24:48 +00002284 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002285 Iv= Iv->getNextIvar())
2286 Ivars.push_back(Iv);
2287 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002288}
2289
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002290/// CollectInheritedProtocols - Collect all protocols in current class and
2291/// those inherited by it.
2292void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002293 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002294 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002295 // We can use protocol_iterator here instead of
Fangrui Song6907ce22018-07-30 19:24:48 +00002296 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002297 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002298 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002299 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002300
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002301 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002302 for (const auto *Cat : OI->visible_categories())
2303 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002304
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002305 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2306 while (SD) {
2307 CollectInheritedProtocols(SD, Protocols);
2308 SD = SD->getSuperClass();
2309 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002310 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002311 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002312 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002313 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002314 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002315 // Insert the protocol.
2316 if (!Protocols.insert(
2317 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2318 return;
2319
2320 for (auto *Proto : OP->protocols())
2321 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002322 }
2323}
2324
Erich Keane8a6b7402017-11-30 16:37:02 +00002325static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2326 const RecordDecl *RD) {
2327 assert(RD->isUnion() && "Must be union type");
2328 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2329
2330 for (const auto *Field : RD->fields()) {
2331 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2332 return false;
2333 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2334 if (FieldSize != UnionSize)
2335 return false;
2336 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002337 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002338}
2339
Benjamin Kramer802e6252017-12-24 12:46:22 +00002340static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002341 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2342
2343 if (!RD->field_empty())
2344 return false;
2345
2346 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2347 return ClassDecl->isEmpty();
2348
2349 return true;
2350}
2351
2352static llvm::Optional<int64_t>
2353structHasUniqueObjectRepresentations(const ASTContext &Context,
2354 const RecordDecl *RD) {
2355 assert(!RD->isUnion() && "Must be struct/class type");
2356 const auto &Layout = Context.getASTRecordLayout(RD);
2357
2358 int64_t CurOffsetInBits = 0;
2359 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2360 if (ClassDecl->isDynamicClass())
2361 return llvm::None;
2362
2363 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2364 for (const auto Base : ClassDecl->bases()) {
2365 // Empty types can be inherited from, and non-empty types can potentially
2366 // have tail padding, so just make sure there isn't an error.
2367 if (!isStructEmpty(Base.getType())) {
2368 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2369 Context, Base.getType()->getAs<RecordType>()->getDecl());
2370 if (!Size)
2371 return llvm::None;
2372 Bases.emplace_back(Base.getType(), Size.getValue());
2373 }
2374 }
2375
Fangrui Song1d38c132018-09-30 21:41:11 +00002376 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2377 const std::pair<QualType, int64_t> &R) {
2378 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2379 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2380 });
Erich Keane8a6b7402017-11-30 16:37:02 +00002381
2382 for (const auto Base : Bases) {
2383 int64_t BaseOffset = Context.toBits(
2384 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2385 int64_t BaseSize = Base.second;
2386 if (BaseOffset != CurOffsetInBits)
2387 return llvm::None;
2388 CurOffsetInBits = BaseOffset + BaseSize;
2389 }
2390 }
2391
2392 for (const auto *Field : RD->fields()) {
2393 if (!Field->getType()->isReferenceType() &&
2394 !Context.hasUniqueObjectRepresentations(Field->getType()))
2395 return llvm::None;
2396
2397 int64_t FieldSizeInBits =
2398 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2399 if (Field->isBitField()) {
2400 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2401
2402 if (BitfieldSize > FieldSizeInBits)
2403 return llvm::None;
2404 FieldSizeInBits = BitfieldSize;
2405 }
2406
2407 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2408
2409 if (FieldOffsetInBits != CurOffsetInBits)
2410 return llvm::None;
2411
2412 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2413 }
2414
2415 return CurOffsetInBits;
2416}
2417
2418bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2419 // C++17 [meta.unary.prop]:
2420 // The predicate condition for a template specialization
2421 // has_unique_object_representations<T> shall be
2422 // satisfied if and only if:
2423 // (9.1) - T is trivially copyable, and
2424 // (9.2) - any two objects of type T with the same value have the same
2425 // object representation, where two objects
2426 // of array or non-union class type are considered to have the same value
2427 // if their respective sequences of
2428 // direct subobjects have the same values, and two objects of union type
2429 // are considered to have the same
2430 // value if they have the same active member and the corresponding members
2431 // have the same value.
2432 // The set of scalar types for which this condition holds is
2433 // implementation-defined. [ Note: If a type has padding
2434 // bits, the condition does not hold; otherwise, the condition holds true
2435 // for unsigned integral types. -- end note ]
2436 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2437
2438 // Arrays are unique only if their element type is unique.
2439 if (Ty->isArrayType())
2440 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2441
2442 // (9.1) - T is trivially copyable...
2443 if (!Ty.isTriviallyCopyableType(*this))
2444 return false;
2445
2446 // All integrals and enums are unique.
2447 if (Ty->isIntegralOrEnumerationType())
2448 return true;
2449
2450 // All other pointers are unique.
2451 if (Ty->isPointerType())
2452 return true;
2453
2454 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002455 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002456 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2457 }
2458
2459 if (Ty->isRecordType()) {
2460 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2461
Erich Keanebd2197c2017-12-12 16:02:06 +00002462 if (Record->isInvalidDecl())
2463 return false;
2464
Erich Keane8a6b7402017-11-30 16:37:02 +00002465 if (Record->isUnion())
2466 return unionHasUniqueObjectRepresentations(*this, Record);
2467
2468 Optional<int64_t> StructSize =
2469 structHasUniqueObjectRepresentations(*this, Record);
2470
2471 return StructSize &&
2472 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2473 }
2474
2475 // FIXME: More cases to handle here (list by rsmith):
2476 // vectors (careful about, eg, vector of 3 foo)
2477 // _Complex int and friends
2478 // _Atomic T
2479 // Obj-C block pointers
2480 // Obj-C object pointers
2481 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2482 // clk_event_t, queue_t, reserve_id_t)
2483 // There're also Obj-C class types and the Obj-C selector type, but I think it
2484 // makes sense for those to return false here.
2485
2486 return false;
2487}
2488
Jay Foad39c79802011-01-12 09:06:06 +00002489unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002490 unsigned count = 0;
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002491 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002492 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002493 count += Ext->ivar_size();
Fangrui Song6907ce22018-07-30 19:24:48 +00002494
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002495 // Count ivar defined in this class's implementation. This
2496 // includes synthesized ivars.
2497 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002498 count += ImplDecl->ivar_size();
2499
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002500 return count;
2501}
2502
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002503bool ASTContext::isSentinelNullExpr(const Expr *E) {
2504 if (!E)
2505 return false;
2506
2507 // nullptr_t is always treated as null.
2508 if (E->getType()->isNullPtrType()) return true;
2509
2510 if (E->getType()->isAnyPointerType() &&
2511 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2512 Expr::NPC_ValueDependentIsNull))
2513 return true;
2514
2515 // Unfortunately, __null has type 'int'.
2516 if (isa<GNUNullExpr>(E)) return true;
2517
2518 return false;
2519}
2520
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002521/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002522/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002523ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2524 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2525 I = ObjCImpls.find(D);
2526 if (I != ObjCImpls.end())
2527 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002528 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002529}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002530
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002531/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002532/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002533ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2534 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2535 I = ObjCImpls.find(D);
2536 if (I != ObjCImpls.end())
2537 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002538 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002539}
2540
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002541/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002542void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2543 ObjCImplementationDecl *ImplD) {
2544 assert(IFaceD && ImplD && "Passed null params");
2545 ObjCImpls[IFaceD] = ImplD;
2546}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002547
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002548/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002549void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2550 ObjCCategoryImplDecl *ImplD) {
2551 assert(CatD && ImplD && "Passed null params");
2552 ObjCImpls[CatD] = ImplD;
2553}
2554
Chandler Carruth21c90602015-12-30 03:24:14 +00002555const ObjCMethodDecl *
2556ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2557 return ObjCMethodRedecls.lookup(MD);
2558}
2559
2560void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2561 const ObjCMethodDecl *Redecl) {
2562 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2563 ObjCMethodRedecls[MD] = Redecl;
2564}
2565
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002566const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2567 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002568 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002569 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002570 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002571 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002572 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002573 return IMD->getClassInterface();
2574
Craig Topper36250ad2014-05-12 05:36:57 +00002575 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002576}
2577
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002578/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002579/// none exists.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002580ASTContext::BlockVarCopyInit
2581ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002582 assert(VD && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002583 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002584 "getBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002585 auto I = BlockVarCopyInits.find(VD);
2586 if (I != BlockVarCopyInits.end())
2587 return I->second;
2588 return {nullptr, false};
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002589}
2590
JF Bastien0d702a72019-04-30 00:11:53 +00002591/// Set the copy initialization expression of a block var decl.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002592void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2593 bool CanThrow) {
2594 assert(VD && CopyExpr && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002595 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002596 "setBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002597 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002598}
2599
John McCallbcd03502009-12-07 02:54:59 +00002600TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002601 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002602 if (!DataSize)
2603 DataSize = TypeLoc::getFullDataSizeForType(T);
2604 else
2605 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002606 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002607
Eugene Zelenko7855e772018-04-03 00:11:50 +00002608 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002609 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2610 new (TInfo) TypeSourceInfo(T);
2611 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002612}
2613
John McCallbcd03502009-12-07 02:54:59 +00002614TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002615 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002616 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002617 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002618 return DI;
2619}
2620
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002621const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002622ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002623 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002624}
2625
2626const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002627ASTContext::getASTObjCImplementationLayout(
2628 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002629 return getObjCLayout(D->getClassInterface(), D);
2630}
2631
Chris Lattner983a8bb2007-07-13 22:13:22 +00002632//===----------------------------------------------------------------------===//
2633// Type creation/memoization methods
2634//===----------------------------------------------------------------------===//
2635
Jay Foad39c79802011-01-12 09:06:06 +00002636QualType
John McCall33ddac02011-01-19 10:06:00 +00002637ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2638 unsigned fastQuals = quals.getFastQualifiers();
2639 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002640
2641 // Check if we've already instantiated this type.
2642 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002643 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002644 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002645 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2646 assert(eq->getQualifiers() == quals);
2647 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002648 }
2649
John McCall33ddac02011-01-19 10:06:00 +00002650 // If the base type is not canonical, make the appropriate canonical type.
2651 QualType canon;
2652 if (!baseType->isCanonicalUnqualified()) {
2653 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002654 canonSplit.Quals.addConsistentQualifiers(quals);
2655 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002656
2657 // Re-find the insert position.
2658 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2659 }
2660
Eugene Zelenko7855e772018-04-03 00:11:50 +00002661 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002662 ExtQualNodes.InsertNode(eq, insertPos);
2663 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002664}
2665
Alexander Richardson6d989432017-10-15 18:48:14 +00002666QualType ASTContext::getAddrSpaceQualType(QualType T,
2667 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002668 QualType CanT = getCanonicalType(T);
2669 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002670 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002671
John McCall8ccfcb52009-09-24 19:53:00 +00002672 // If we are composing extended qualifiers together, merge together
2673 // into one ExtQuals node.
2674 QualifierCollector Quals;
2675 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002676
John McCall8ccfcb52009-09-24 19:53:00 +00002677 // If this type already has an address space specified, it cannot get
2678 // another one.
2679 assert(!Quals.hasAddressSpace() &&
2680 "Type cannot be in multiple addr spaces!");
2681 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002682
John McCall8ccfcb52009-09-24 19:53:00 +00002683 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002684}
2685
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002686QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2687 // If we are composing extended qualifiers together, merge together
2688 // into one ExtQuals node.
2689 QualifierCollector Quals;
2690 const Type *TypeNode = Quals.strip(T);
2691
2692 // If the qualifier doesn't have an address space just return it.
2693 if (!Quals.hasAddressSpace())
2694 return T;
2695
2696 Quals.removeAddressSpace();
2697
2698 // Removal of the address space can mean there are no longer any
2699 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2700 // or required.
2701 if (Quals.hasNonFastQualifiers())
2702 return getExtQualType(TypeNode, Quals);
2703 else
2704 return QualType(TypeNode, Quals.getFastQualifiers());
2705}
2706
Chris Lattnerd60183d2009-02-18 22:53:11 +00002707QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002708 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002709 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002710 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002711 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002712
Eugene Zelenko7855e772018-04-03 00:11:50 +00002713 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002714 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002715 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002716 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2717 return getPointerType(ResultType);
2718 }
2719 }
Mike Stump11289f42009-09-09 15:08:12 +00002720
John McCall8ccfcb52009-09-24 19:53:00 +00002721 // If we are composing extended qualifiers together, merge together
2722 // into one ExtQuals node.
2723 QualifierCollector Quals;
2724 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002725
John McCall8ccfcb52009-09-24 19:53:00 +00002726 // If this type already has an ObjCGC specified, it cannot get
2727 // another one.
2728 assert(!Quals.hasObjCGCAttr() &&
2729 "Type cannot have multiple ObjCGCs!");
2730 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002731
John McCall8ccfcb52009-09-24 19:53:00 +00002732 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002733}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002734
John McCall4f5019e2010-12-19 02:44:49 +00002735const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2736 FunctionType::ExtInfo Info) {
2737 if (T->getExtInfo() == Info)
2738 return T;
2739
2740 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002741 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002742 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002743 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002744 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002745 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2746 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002747 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002748 }
2749
2750 return cast<FunctionType>(Result.getTypePtr());
2751}
2752
Richard Smith2a7d4812013-05-04 07:00:32 +00002753void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2754 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002755 FD = FD->getMostRecentDecl();
2756 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002757 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002758 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002759 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002760 if (FunctionDecl *Next = FD->getPreviousDecl())
2761 FD = Next;
2762 else
2763 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002764 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002765 if (ASTMutationListener *L = getASTMutationListener())
2766 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002767}
2768
Richard Smith0b3a4622014-11-13 20:01:57 +00002769/// Get a function type and produce the equivalent function type with the
2770/// specified exception specification. Type sugar that can be present on a
2771/// declaration of a function with an exception specification is permitted
2772/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002773QualType ASTContext::getFunctionTypeWithExceptionSpec(
2774 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002775 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002776 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002777 return getParenType(
2778 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002779
Leonard Chandc5d9752019-05-10 18:05:15 +00002780 // Might be wrapped in a macro qualified type.
2781 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2782 return getMacroQualifiedType(
2783 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2784 MQT->getMacroIdentifier());
2785
Richard Smith0b3a4622014-11-13 20:01:57 +00002786 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002787 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002788 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002789 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002790 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2791 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002792
2793 // Anything else must be a function type. Rebuild it with the new exception
2794 // specification.
Stephan Bergmann84dcc8f2019-02-13 09:39:17 +00002795 const auto *Proto = Orig->getAs<FunctionProtoType>();
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002796 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002797 Proto->getReturnType(), Proto->getParamTypes(),
2798 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2799}
2800
Richard Smithdfe85e22016-12-15 02:35:39 +00002801bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2802 QualType U) {
2803 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002804 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002805 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2806 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002807}
2808
Richard Smith0b3a4622014-11-13 20:01:57 +00002809void ASTContext::adjustExceptionSpec(
2810 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2811 bool AsWritten) {
2812 // Update the type.
2813 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002814 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002815 FD->setType(Updated);
2816
2817 if (!AsWritten)
2818 return;
2819
2820 // Update the type in the type source information too.
2821 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2822 // If the type and the type-as-written differ, we may need to update
2823 // the type-as-written too.
2824 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002825 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002826
2827 // FIXME: When we get proper type location information for exceptions,
2828 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2829 // up the TypeSourceInfo;
2830 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2831 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2832 "TypeLoc size mismatch from updating exception specification");
2833 TSInfo->overrideType(Updated);
2834 }
2835}
2836
Chris Lattnerc6395932007-06-22 20:56:16 +00002837/// getComplexType - Return the uniqued reference to the type for a complex
2838/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002839QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002840 // Unique pointers, to guarantee there is only one pointer of a particular
2841 // structure.
2842 llvm::FoldingSetNodeID ID;
2843 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002844
Craig Topper36250ad2014-05-12 05:36:57 +00002845 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002846 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2847 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002848
Chris Lattnerc6395932007-06-22 20:56:16 +00002849 // If the pointee type isn't canonical, this won't be a canonical type either,
2850 // so fill in the canonical type field.
2851 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002852 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002853 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002854
Chris Lattnerc6395932007-06-22 20:56:16 +00002855 // Get the new insert position for the node we care about.
2856 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002857 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002858 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002859 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002860 Types.push_back(New);
2861 ComplexTypes.InsertNode(New, InsertPos);
2862 return QualType(New, 0);
2863}
2864
Chris Lattner970e54e2006-11-12 00:37:36 +00002865/// getPointerType - Return the uniqued reference to the type for a pointer to
2866/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002867QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002868 // Unique pointers, to guarantee there is only one pointer of a particular
2869 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002870 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002871 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002872
Craig Topper36250ad2014-05-12 05:36:57 +00002873 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002874 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002875 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002876
Chris Lattner7ccecb92006-11-12 08:50:50 +00002877 // If the pointee type isn't canonical, this won't be a canonical type either,
2878 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002879 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002880 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002881 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002882
Bob Wilsonc8541f22013-03-15 17:12:43 +00002883 // Get the new insert position for the node we care about.
2884 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002885 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002886 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002887 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002888 Types.push_back(New);
2889 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002890 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002891}
2892
Reid Kleckner0503a872013-12-05 01:23:43 +00002893QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2894 llvm::FoldingSetNodeID ID;
2895 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002896 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002897 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2898 if (AT)
2899 return QualType(AT, 0);
2900
2901 QualType Canonical = getCanonicalType(New);
2902
2903 // Get the new insert position for the node we care about.
2904 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002905 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002906
2907 AT = new (*this, TypeAlignment)
2908 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2909 Types.push_back(AT);
2910 AdjustedTypes.InsertNode(AT, InsertPos);
2911 return QualType(AT, 0);
2912}
2913
Reid Kleckner8a365022013-06-24 17:51:48 +00002914QualType ASTContext::getDecayedType(QualType T) const {
2915 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2916
Reid Kleckner8a365022013-06-24 17:51:48 +00002917 QualType Decayed;
2918
2919 // C99 6.7.5.3p7:
2920 // A declaration of a parameter as "array of type" shall be
2921 // adjusted to "qualified pointer to type", where the type
2922 // qualifiers (if any) are those specified within the [ and ] of
2923 // the array type derivation.
2924 if (T->isArrayType())
2925 Decayed = getArrayDecayedType(T);
2926
2927 // C99 6.7.5.3p8:
2928 // A declaration of a parameter as "function returning type"
2929 // shall be adjusted to "pointer to function returning type", as
2930 // in 6.3.2.1.
2931 if (T->isFunctionType())
2932 Decayed = getPointerType(T);
2933
Reid Kleckner0503a872013-12-05 01:23:43 +00002934 llvm::FoldingSetNodeID ID;
2935 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002936 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002937 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2938 if (AT)
2939 return QualType(AT, 0);
2940
Reid Kleckner8a365022013-06-24 17:51:48 +00002941 QualType Canonical = getCanonicalType(Decayed);
2942
2943 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002944 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002945 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002946
Reid Kleckner0503a872013-12-05 01:23:43 +00002947 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2948 Types.push_back(AT);
2949 AdjustedTypes.InsertNode(AT, InsertPos);
2950 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002951}
2952
Mike Stump11289f42009-09-09 15:08:12 +00002953/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002954/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002955QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002956 assert(T->isFunctionType() && "block of function types only");
2957 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002958 // structure.
2959 llvm::FoldingSetNodeID ID;
2960 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002961
Craig Topper36250ad2014-05-12 05:36:57 +00002962 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002963 if (BlockPointerType *PT =
2964 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2965 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002966
2967 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002968 // type either so fill in the canonical type field.
2969 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002970 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002971 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002972
Steve Naroffec33ed92008-08-27 16:04:49 +00002973 // Get the new insert position for the node we care about.
2974 BlockPointerType *NewIP =
2975 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002976 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002977 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002978 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002979 Types.push_back(New);
2980 BlockPointerTypes.InsertNode(New, InsertPos);
2981 return QualType(New, 0);
2982}
2983
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002984/// getLValueReferenceType - Return the uniqued reference to the type for an
2985/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002986QualType
2987ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002988 assert(getCanonicalType(T) != OverloadTy &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002989 "Unresolved overloaded function type");
Fangrui Song6907ce22018-07-30 19:24:48 +00002990
Bill Wendling3708c182007-05-27 10:15:43 +00002991 // Unique pointers, to guarantee there is only one pointer of a particular
2992 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002993 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002994 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002995
Craig Topper36250ad2014-05-12 05:36:57 +00002996 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002997 if (LValueReferenceType *RT =
2998 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002999 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003000
Eugene Zelenko7855e772018-04-03 00:11:50 +00003001 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003002
Bill Wendling3708c182007-05-27 10:15:43 +00003003 // If the referencee type isn't canonical, this won't be a canonical type
3004 // either, so fill in the canonical type field.
3005 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003006 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3007 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3008 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003009
Bill Wendling3708c182007-05-27 10:15:43 +00003010 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003011 LValueReferenceType *NewIP =
3012 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003013 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00003014 }
3015
Eugene Zelenko7855e772018-04-03 00:11:50 +00003016 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3017 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00003018 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003019 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00003020
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003021 return QualType(New, 0);
3022}
3023
3024/// getRValueReferenceType - Return the uniqued reference to the type for an
3025/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003026QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003027 // Unique pointers, to guarantee there is only one pointer of a particular
3028 // structure.
3029 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003030 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003031
Craig Topper36250ad2014-05-12 05:36:57 +00003032 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003033 if (RValueReferenceType *RT =
3034 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3035 return QualType(RT, 0);
3036
Eugene Zelenko7855e772018-04-03 00:11:50 +00003037 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003038
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003039 // If the referencee type isn't canonical, this won't be a canonical type
3040 // either, so fill in the canonical type field.
3041 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003042 if (InnerRef || !T.isCanonical()) {
3043 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3044 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003045
3046 // Get the new insert position for the node we care about.
3047 RValueReferenceType *NewIP =
3048 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003049 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003050 }
3051
Eugene Zelenko7855e772018-04-03 00:11:50 +00003052 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003053 Types.push_back(New);
3054 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00003055 return QualType(New, 0);
3056}
3057
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003058/// getMemberPointerType - Return the uniqued reference to the type for a
3059/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00003060QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003061 // Unique pointers, to guarantee there is only one pointer of a particular
3062 // structure.
3063 llvm::FoldingSetNodeID ID;
3064 MemberPointerType::Profile(ID, T, Cls);
3065
Craig Topper36250ad2014-05-12 05:36:57 +00003066 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003067 if (MemberPointerType *PT =
3068 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3069 return QualType(PT, 0);
3070
3071 // If the pointee or class type isn't canonical, this won't be a canonical
3072 // type either, so fill in the canonical type field.
3073 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00003074 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003075 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3076
3077 // Get the new insert position for the node we care about.
3078 MemberPointerType *NewIP =
3079 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003080 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003081 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003082 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003083 Types.push_back(New);
3084 MemberPointerTypes.InsertNode(New, InsertPos);
3085 return QualType(New, 0);
3086}
3087
Mike Stump11289f42009-09-09 15:08:12 +00003088/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00003089/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00003090QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00003091 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003092 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003093 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00003094 assert((EltTy->isDependentType() ||
3095 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00003096 "Constant array of VLAs is illegal!");
3097
Chris Lattnere2df3f92009-05-13 04:12:56 +00003098 // Convert the array size into a canonical width matching the pointer size for
3099 // the target.
3100 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00003101 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00003102
Chris Lattner23b7eb62007-06-15 23:05:46 +00003103 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00003104 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00003105
Craig Topper36250ad2014-05-12 05:36:57 +00003106 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003107 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003108 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003109 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003110
John McCall33ddac02011-01-19 10:06:00 +00003111 // If the element type isn't canonical or has qualifiers, this won't
3112 // be a canonical type either, so fill in the canonical type field.
3113 QualType Canon;
3114 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3115 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003116 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003117 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003118 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003119
Chris Lattner36f8e652007-01-27 08:31:04 +00003120 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003121 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003122 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003123 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003124 }
Mike Stump11289f42009-09-09 15:08:12 +00003125
Eugene Zelenko7855e772018-04-03 00:11:50 +00003126 auto *New = new (*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003127 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003128 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003129 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003130 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003131}
3132
John McCall06549462011-01-18 08:40:38 +00003133/// getVariableArrayDecayedType - Turns the given type, which may be
3134/// variably-modified, into the corresponding type with all the known
3135/// sizes replaced with [*].
3136QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3137 // Vastly most common case.
3138 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003139
John McCall06549462011-01-18 08:40:38 +00003140 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003141
John McCall06549462011-01-18 08:40:38 +00003142 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003143 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003144 switch (ty->getTypeClass()) {
3145#define TYPE(Class, Base)
3146#define ABSTRACT_TYPE(Class, Base)
3147#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3148#include "clang/AST/TypeNodes.def"
3149 llvm_unreachable("didn't desugar past all non-canonical types?");
3150
3151 // These types should never be variably-modified.
3152 case Type::Builtin:
3153 case Type::Complex:
3154 case Type::Vector:
Erich Keanef702b022018-07-13 19:46:04 +00003155 case Type::DependentVector:
John McCall06549462011-01-18 08:40:38 +00003156 case Type::ExtVector:
3157 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003158 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003159 case Type::ObjCObject:
3160 case Type::ObjCInterface:
3161 case Type::ObjCObjectPointer:
3162 case Type::Record:
3163 case Type::Enum:
3164 case Type::UnresolvedUsing:
3165 case Type::TypeOfExpr:
3166 case Type::TypeOf:
3167 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003168 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003169 case Type::DependentName:
3170 case Type::InjectedClassName:
3171 case Type::TemplateSpecialization:
3172 case Type::DependentTemplateSpecialization:
3173 case Type::TemplateTypeParm:
3174 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003175 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003176 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003177 case Type::PackExpansion:
3178 llvm_unreachable("type should never be variably-modified");
3179
3180 // These types can be variably-modified but should never need to
3181 // further decay.
3182 case Type::FunctionNoProto:
3183 case Type::FunctionProto:
3184 case Type::BlockPointer:
3185 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003186 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003187 return type;
3188
3189 // These types can be variably-modified. All these modifications
3190 // preserve structure except as noted by comments.
3191 // TODO: if we ever care about optimizing VLAs, there are no-op
3192 // optimizations available here.
3193 case Type::Pointer:
3194 result = getPointerType(getVariableArrayDecayedType(
3195 cast<PointerType>(ty)->getPointeeType()));
3196 break;
3197
3198 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003199 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003200 result = getLValueReferenceType(
3201 getVariableArrayDecayedType(lv->getPointeeType()),
3202 lv->isSpelledAsLValue());
3203 break;
3204 }
3205
3206 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003207 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003208 result = getRValueReferenceType(
3209 getVariableArrayDecayedType(lv->getPointeeType()));
3210 break;
3211 }
3212
Eli Friedman0dfb8892011-10-06 23:00:33 +00003213 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003214 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003215 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3216 break;
3217 }
3218
John McCall06549462011-01-18 08:40:38 +00003219 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003220 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003221 result = getConstantArrayType(
3222 getVariableArrayDecayedType(cat->getElementType()),
3223 cat->getSize(),
3224 cat->getSizeModifier(),
3225 cat->getIndexTypeCVRQualifiers());
3226 break;
3227 }
3228
3229 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003230 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003231 result = getDependentSizedArrayType(
3232 getVariableArrayDecayedType(dat->getElementType()),
3233 dat->getSizeExpr(),
3234 dat->getSizeModifier(),
3235 dat->getIndexTypeCVRQualifiers(),
3236 dat->getBracketsRange());
3237 break;
3238 }
3239
3240 // Turn incomplete types into [*] types.
3241 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003242 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003243 result = getVariableArrayType(
3244 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003245 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003246 ArrayType::Normal,
3247 iat->getIndexTypeCVRQualifiers(),
3248 SourceRange());
3249 break;
3250 }
3251
3252 // Turn VLA types into [*] types.
3253 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003254 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003255 result = getVariableArrayType(
3256 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003257 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003258 ArrayType::Star,
3259 vat->getIndexTypeCVRQualifiers(),
3260 vat->getBracketsRange());
3261 break;
3262 }
3263 }
3264
3265 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003266 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003267}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003268
Steve Naroffcadebd02007-08-30 18:14:25 +00003269/// getVariableArrayType - Returns a non-unique reference to the type for a
3270/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003271QualType ASTContext::getVariableArrayType(QualType EltTy,
3272 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003273 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003274 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003275 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003276 // Since we don't unique expressions, it isn't possible to unique VLA's
3277 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003278 QualType Canon;
Fangrui Song6907ce22018-07-30 19:24:48 +00003279
John McCall33ddac02011-01-19 10:06:00 +00003280 // Be sure to pull qualifiers off the element type.
3281 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3282 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003283 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003284 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003285 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003286 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003287
Eugene Zelenko7855e772018-04-03 00:11:50 +00003288 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003289 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003290
3291 VariableArrayTypes.push_back(New);
3292 Types.push_back(New);
3293 return QualType(New, 0);
3294}
3295
Douglas Gregor4619e432008-12-05 23:32:09 +00003296/// getDependentSizedArrayType - Returns a non-unique reference to
3297/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003298/// type.
John McCall33ddac02011-01-19 10:06:00 +00003299QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3300 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003301 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003302 unsigned elementTypeQuals,
3303 SourceRange brackets) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003304 assert((!numElements || numElements->isTypeDependent() ||
John McCall33ddac02011-01-19 10:06:00 +00003305 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003306 "Size must be type- or value-dependent!");
3307
John McCall33ddac02011-01-19 10:06:00 +00003308 // Dependently-sized array types that do not have a specified number
3309 // of elements will have their sizes deduced from a dependent
3310 // initializer. We do no canonicalization here at all, which is okay
3311 // because they can't be used in most locations.
3312 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003313 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003314 = new (*this, TypeAlignment)
3315 DependentSizedArrayType(*this, elementType, QualType(),
3316 numElements, ASM, elementTypeQuals,
3317 brackets);
3318 Types.push_back(newType);
3319 return QualType(newType, 0);
3320 }
3321
3322 // Otherwise, we actually build a new type every time, but we
3323 // also build a canonical type.
3324
3325 SplitQualType canonElementType = getCanonicalType(elementType).split();
3326
Craig Topper36250ad2014-05-12 05:36:57 +00003327 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003328 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003329 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003330 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003331 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003332
John McCall33ddac02011-01-19 10:06:00 +00003333 // Look for an existing type with these properties.
3334 DependentSizedArrayType *canonTy =
3335 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003336
John McCall33ddac02011-01-19 10:06:00 +00003337 // If we don't have one, build one.
3338 if (!canonTy) {
3339 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003340 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003341 QualType(), numElements, ASM, elementTypeQuals,
3342 brackets);
3343 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3344 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003345 }
3346
John McCall33ddac02011-01-19 10:06:00 +00003347 // Apply qualifiers from the element type to the array.
3348 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003349 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003350
David Majnemer16a74702015-07-24 05:54:19 +00003351 // If we didn't need extra canonicalization for the element type or the size
3352 // expression, then just use that as our result.
3353 if (QualType(canonElementType.Ty, 0) == elementType &&
3354 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003355 return canon;
3356
3357 // Otherwise, we need to build a type which follows the spelling
3358 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003359 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003360 = new (*this, TypeAlignment)
3361 DependentSizedArrayType(*this, elementType, canon, numElements,
3362 ASM, elementTypeQuals, brackets);
3363 Types.push_back(sugaredType);
3364 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003365}
3366
John McCall33ddac02011-01-19 10:06:00 +00003367QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003368 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003369 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003370 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003371 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003372
Craig Topper36250ad2014-05-12 05:36:57 +00003373 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003374 if (IncompleteArrayType *iat =
3375 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3376 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003377
3378 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003379 // either, so fill in the canonical type field. We also have to pull
3380 // qualifiers off the element type.
3381 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003382
John McCall33ddac02011-01-19 10:06:00 +00003383 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3384 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003385 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003386 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003387 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003388
3389 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003390 IncompleteArrayType *existing =
3391 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3392 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003393 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003394
Eugene Zelenko7855e772018-04-03 00:11:50 +00003395 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003396 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003397
John McCall33ddac02011-01-19 10:06:00 +00003398 IncompleteArrayTypes.InsertNode(newType, insertPos);
3399 Types.push_back(newType);
3400 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003401}
3402
Steve Naroff91fcddb2007-07-18 18:00:27 +00003403/// getVectorType - Return the unique reference to a vector type of
3404/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003405QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003406 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003407 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003408
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003409 // Check if we've already instantiated a vector of this type.
3410 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003411 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003412
Craig Topper36250ad2014-05-12 05:36:57 +00003413 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003414 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3415 return QualType(VTP, 0);
3416
3417 // If the element type isn't canonical, this won't be a canonical type either,
3418 // so fill in the canonical type field.
3419 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003420 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003421 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003422
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003423 // Get the new insert position for the node we care about.
3424 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003425 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003426 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003427 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003428 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003429 VectorTypes.InsertNode(New, InsertPos);
3430 Types.push_back(New);
3431 return QualType(New, 0);
3432}
3433
Erich Keanef702b022018-07-13 19:46:04 +00003434QualType
3435ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3436 SourceLocation AttrLoc,
3437 VectorType::VectorKind VecKind) const {
3438 llvm::FoldingSetNodeID ID;
3439 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3440 VecKind);
3441 void *InsertPos = nullptr;
3442 DependentVectorType *Canon =
3443 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3444 DependentVectorType *New;
3445
3446 if (Canon) {
3447 New = new (*this, TypeAlignment) DependentVectorType(
3448 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3449 } else {
3450 QualType CanonVecTy = getCanonicalType(VecType);
3451 if (CanonVecTy == VecType) {
3452 New = new (*this, TypeAlignment) DependentVectorType(
3453 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3454
3455 DependentVectorType *CanonCheck =
3456 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3457 assert(!CanonCheck &&
3458 "Dependent-sized vector_size canonical type broken");
3459 (void)CanonCheck;
3460 DependentVectorTypes.InsertNode(New, InsertPos);
3461 } else {
3462 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3463 SourceLocation());
3464 New = new (*this, TypeAlignment) DependentVectorType(
3465 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3466 }
3467 }
3468
3469 Types.push_back(New);
3470 return QualType(New, 0);
3471}
3472
Nate Begemance4d7fc2008-04-18 23:10:10 +00003473/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003474/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003475QualType
3476ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003477 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003478
Steve Naroff91fcddb2007-07-18 18:00:27 +00003479 // Check if we've already instantiated a vector of this type.
3480 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003481 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003482 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003483 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003484 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3485 return QualType(VTP, 0);
3486
3487 // If the element type isn't canonical, this won't be a canonical type either,
3488 // so fill in the canonical type field.
3489 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003490 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003491 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003492
Steve Naroff91fcddb2007-07-18 18:00:27 +00003493 // Get the new insert position for the node we care about.
3494 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003495 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003496 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003497 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003498 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003499 VectorTypes.InsertNode(New, InsertPos);
3500 Types.push_back(New);
3501 return QualType(New, 0);
3502}
3503
Jay Foad39c79802011-01-12 09:06:06 +00003504QualType
3505ASTContext::getDependentSizedExtVectorType(QualType vecType,
3506 Expr *SizeExpr,
3507 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003508 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003509 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003510 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003511
Craig Topper36250ad2014-05-12 05:36:57 +00003512 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003513 DependentSizedExtVectorType *Canon
3514 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3515 DependentSizedExtVectorType *New;
3516 if (Canon) {
3517 // We already have a canonical version of this array type; use it as
3518 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003519 New = new (*this, TypeAlignment)
3520 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3521 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003522 } else {
3523 QualType CanonVecTy = getCanonicalType(vecType);
3524 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003525 New = new (*this, TypeAlignment)
3526 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3527 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003528
3529 DependentSizedExtVectorType *CanonCheck
3530 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3531 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3532 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003533 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3534 } else {
3535 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3536 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003537 New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003538 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003539 }
3540 }
Mike Stump11289f42009-09-09 15:08:12 +00003541
Douglas Gregor758a8692009-06-17 21:51:59 +00003542 Types.push_back(New);
3543 return QualType(New, 0);
3544}
3545
Fangrui Song6907ce22018-07-30 19:24:48 +00003546QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3547 Expr *AddrSpaceExpr,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003548 SourceLocation AttrLoc) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003549 assert(AddrSpaceExpr->isInstantiationDependent());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003550
3551 QualType canonPointeeType = getCanonicalType(PointeeType);
3552
3553 void *insertPos = nullptr;
3554 llvm::FoldingSetNodeID ID;
3555 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3556 AddrSpaceExpr);
3557
3558 DependentAddressSpaceType *canonTy =
3559 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3560
3561 if (!canonTy) {
3562 canonTy = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003563 DependentAddressSpaceType(*this, canonPointeeType,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003564 QualType(), AddrSpaceExpr, AttrLoc);
3565 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3566 Types.push_back(canonTy);
3567 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003568
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003569 if (canonPointeeType == PointeeType &&
3570 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
Fangrui Song6907ce22018-07-30 19:24:48 +00003571 return QualType(canonTy, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003572
Eugene Zelenko7855e772018-04-03 00:11:50 +00003573 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003574 = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003575 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003576 AddrSpaceExpr, AttrLoc);
3577 Types.push_back(sugaredType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003578 return QualType(sugaredType, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003579}
3580
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003581/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003582static bool isCanonicalResultType(QualType T) {
3583 return T.isCanonical() &&
3584 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3585 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3586}
3587
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003588/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003589QualType
3590ASTContext::getFunctionNoProtoType(QualType ResultTy,
3591 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003592 // Unique functions, to guarantee there is only one function of a particular
3593 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003594 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003595 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003596
Craig Topper36250ad2014-05-12 05:36:57 +00003597 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003598 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003599 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003600 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003601
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003602 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003603 if (!isCanonicalResultType(ResultTy)) {
3604 Canonical =
3605 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003606
Chris Lattner47955de2007-01-27 08:37:20 +00003607 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003608 FunctionNoProtoType *NewIP =
3609 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003610 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003611 }
Mike Stump11289f42009-09-09 15:08:12 +00003612
Eugene Zelenko7855e772018-04-03 00:11:50 +00003613 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003614 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003615 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003616 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003617 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003618}
3619
Douglas Gregora602a152015-10-01 20:20:47 +00003620CanQualType
3621ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3622 CanQualType CanResultType = getCanonicalType(ResultType);
3623
3624 // Canonical result types do not have ARC lifetime qualifiers.
3625 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3626 Qualifiers Qs = CanResultType.getQualifiers();
3627 Qs.removeObjCLifetime();
3628 return CanQualType::CreateUnsafe(
3629 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3630 }
3631
3632 return CanResultType;
3633}
3634
Richard Smith3c4f8d22016-10-16 17:54:23 +00003635static bool isCanonicalExceptionSpecification(
3636 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3637 if (ESI.Type == EST_None)
3638 return true;
3639 if (!NoexceptInType)
3640 return false;
3641
3642 // C++17 onwards: exception specification is part of the type, as a simple
3643 // boolean "can this function type throw".
3644 if (ESI.Type == EST_BasicNoexcept)
3645 return true;
3646
Richard Smitheaf11ad2018-05-03 03:58:32 +00003647 // A noexcept(expr) specification is (possibly) canonical if expr is
3648 // value-dependent.
3649 if (ESI.Type == EST_DependentNoexcept)
3650 return true;
3651
Richard Smith3c4f8d22016-10-16 17:54:23 +00003652 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003653 // expansions (so we can't tell whether it's non-throwing) and all its
3654 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003655 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003656 bool AnyPackExpansions = false;
3657 for (QualType ET : ESI.Exceptions) {
3658 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003659 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003660 if (ET->getAs<PackExpansionType>())
3661 AnyPackExpansions = true;
3662 }
3663 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003664 }
3665
Richard Smith3c4f8d22016-10-16 17:54:23 +00003666 return false;
3667}
3668
Richard Smith304b1242016-10-18 20:13:25 +00003669QualType ASTContext::getFunctionTypeInternal(
3670 QualType ResultTy, ArrayRef<QualType> ArgArray,
3671 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003672 size_t NumArgs = ArgArray.size();
3673
Richard Smith2a2cda52016-10-18 19:29:18 +00003674 // Unique functions, to guarantee there is only one function of a particular
3675 // structure.
3676 llvm::FoldingSetNodeID ID;
3677 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3678 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003679
Richard Smith2a2cda52016-10-18 19:29:18 +00003680 QualType Canonical;
3681 bool Unique = false;
3682
3683 void *InsertPos = nullptr;
3684 if (FunctionProtoType *FPT =
3685 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3686 QualType Existing = QualType(FPT, 0);
3687
3688 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3689 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003690 // noexcept expression, or we're just looking for a canonical type.
3691 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003692 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003693 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003694 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3695 return Existing;
3696
3697 // We need a new type sugar node for this one, to hold the new noexcept
3698 // expression. We do no canonicalization here, but that's OK since we don't
3699 // expect to see the same noexcept expression much more than once.
3700 Canonical = getCanonicalType(Existing);
3701 Unique = true;
3702 }
3703
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003704 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003705 bool IsCanonicalExceptionSpec =
3706 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3707
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003708 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003709 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003710 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003711 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003712 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003713 isCanonical = false;
3714
Richard Smith304b1242016-10-18 20:13:25 +00003715 if (OnlyWantCanonical)
3716 assert(isCanonical &&
3717 "given non-canonical parameters constructing canonical type");
3718
Richard Smith2a2cda52016-10-18 19:29:18 +00003719 // If this type isn't canonical, get the canonical version of it if we don't
3720 // already have it. The exception spec is only partially part of the
3721 // canonical type, and only in C++17 onwards.
3722 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003723 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003724 CanonicalArgs.reserve(NumArgs);
3725 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003726 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003727
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003728 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003729 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003730 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003731
3732 if (IsCanonicalExceptionSpec) {
3733 // Exception spec is already OK.
3734 } else if (NoexceptInType) {
3735 switch (EPI.ExceptionSpec.Type) {
3736 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3737 // We don't know yet. It shouldn't matter what we pick here; no-one
3738 // should ever look at this.
3739 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003740 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003741 CanonicalEPI.ExceptionSpec.Type = EST_None;
3742 break;
3743
Richard Smith2a2cda52016-10-18 19:29:18 +00003744 // A dynamic exception specification is almost always "not noexcept",
3745 // with the exception that a pack expansion might expand to no types.
3746 case EST_Dynamic: {
3747 bool AnyPacks = false;
3748 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3749 if (ET->getAs<PackExpansionType>())
3750 AnyPacks = true;
3751 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3752 }
3753 if (!AnyPacks)
3754 CanonicalEPI.ExceptionSpec.Type = EST_None;
3755 else {
3756 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3757 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3758 }
3759 break;
3760 }
3761
Erich Keaned02f4a12019-05-30 17:31:54 +00003762 case EST_DynamicNone:
3763 case EST_BasicNoexcept:
3764 case EST_NoexceptTrue:
3765 case EST_NoThrow:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003766 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3767 break;
3768
Richard Smitheaf11ad2018-05-03 03:58:32 +00003769 case EST_DependentNoexcept:
3770 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003771 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003772 } else {
3773 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3774 }
John McCalldb40c7f2010-12-14 08:05:40 +00003775
Douglas Gregora602a152015-10-01 20:20:47 +00003776 // Adjust the canonical function result type.
3777 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003778 Canonical =
3779 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003780
Chris Lattnerfd4de792007-01-27 01:15:32 +00003781 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003782 FunctionProtoType *NewIP =
3783 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003784 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003785 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003786
Bruno Ricci26a25362018-10-02 11:46:38 +00003787 // Compute the needed size to hold this FunctionProtoType and the
3788 // various trailing objects.
3789 auto ESH = FunctionProtoType::getExceptionSpecSize(
3790 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3791 size_t Size = FunctionProtoType::totalSizeToAlloc<
3792 QualType, FunctionType::FunctionTypeExtraBitfields,
3793 FunctionType::ExceptionType, Expr *, FunctionDecl *,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003794 FunctionProtoType::ExtParameterInfo, Qualifiers>(
Bruno Ricci26a25362018-10-02 11:46:38 +00003795 NumArgs, FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
3796 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003797 EPI.ExtParameterInfos ? NumArgs : 0,
3798 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
John McCall18afab72016-03-01 00:49:02 +00003799
Bruno Ricci26a25362018-10-02 11:46:38 +00003800 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003801 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003802 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003803 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003804 if (!Unique)
3805 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003806 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003807}
Chris Lattneref51c202006-11-10 07:17:23 +00003808
Joey Goulye3c85de2016-12-01 11:30:49 +00003809QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003810 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003811 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003812
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003813 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003814 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003815 return QualType(PT, 0);
3816
3817 // If the pipe element type isn't canonical, this won't be a canonical type
3818 // either, so fill in the canonical type field.
3819 QualType Canonical;
3820 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003821 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003822
3823 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003824 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003825 assert(!NewIP && "Shouldn't be in the map!");
3826 (void)NewIP;
3827 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003828 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003829 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003830 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003831 return QualType(New, 0);
3832}
3833
Anastasia Stulova59055b92018-05-09 13:23:26 +00003834QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3835 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3836 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3837 : Ty;
3838}
3839
Joey Goulye3c85de2016-12-01 11:30:49 +00003840QualType ASTContext::getReadPipeType(QualType T) const {
3841 return getPipeType(T, true);
3842}
3843
Joey Gouly5788b782016-11-18 14:10:54 +00003844QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003845 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003846}
3847
John McCalle78aac42010-03-10 03:28:59 +00003848#ifndef NDEBUG
3849static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3850 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003851 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003852 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3853 return true;
3854 if (RD->getDescribedClassTemplate() &&
3855 !isa<ClassTemplateSpecializationDecl>(RD))
3856 return true;
3857 return false;
3858}
3859#endif
3860
3861/// getInjectedClassNameType - Return the unique reference to the
3862/// injected class name type for the specified templated declaration.
3863QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003864 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003865 assert(NeedsInjectedClassNameType(Decl));
3866 if (Decl->TypeForDecl) {
3867 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003868 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003869 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3870 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3871 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3872 } else {
John McCall424cec92011-01-19 06:33:43 +00003873 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003874 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003875 Decl->TypeForDecl = newType;
3876 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003877 }
3878 return QualType(Decl->TypeForDecl, 0);
3879}
3880
Douglas Gregor83a586e2008-04-13 21:07:44 +00003881/// getTypeDeclType - Return the unique reference to the type for the
3882/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003883QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003884 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003885 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003886
Eugene Zelenko7855e772018-04-03 00:11:50 +00003887 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003888 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003889
John McCall96f0b5f2010-03-10 06:48:02 +00003890 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3891 "Template type parameter types are always available.");
3892
Eugene Zelenko7855e772018-04-03 00:11:50 +00003893 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003894 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003895 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003896 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003897 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003898 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003899 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003900 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003901 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3902 Decl->TypeForDecl = newType;
3903 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003904 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003905 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003906
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003907 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003908}
3909
Chris Lattner32d920b2007-01-26 02:01:53 +00003910/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003911/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003912QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003913ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3914 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003915 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003916
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003917 if (Canonical.isNull())
3918 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00003919 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003920 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003921 Decl->TypeForDecl = newType;
3922 Types.push_back(newType);
3923 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003924}
3925
Jay Foad39c79802011-01-12 09:06:06 +00003926QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003927 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3928
Douglas Gregorec9fd132012-01-14 16:38:05 +00003929 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003930 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003931 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003932
Eugene Zelenko7855e772018-04-03 00:11:50 +00003933 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003934 Decl->TypeForDecl = newType;
3935 Types.push_back(newType);
3936 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003937}
3938
Jay Foad39c79802011-01-12 09:06:06 +00003939QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003940 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3941
Douglas Gregorec9fd132012-01-14 16:38:05 +00003942 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003943 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003944 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003945
Eugene Zelenko7855e772018-04-03 00:11:50 +00003946 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003947 Decl->TypeForDecl = newType;
3948 Types.push_back(newType);
3949 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003950}
3951
Richard Smithe43e2b32018-08-20 21:47:29 +00003952QualType ASTContext::getAttributedType(attr::Kind attrKind,
John McCall81904512011-01-06 01:58:22 +00003953 QualType modifiedType,
3954 QualType equivalentType) {
3955 llvm::FoldingSetNodeID id;
3956 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3957
Craig Topper36250ad2014-05-12 05:36:57 +00003958 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003959 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3960 if (type) return QualType(type, 0);
3961
3962 QualType canon = getCanonicalType(equivalentType);
3963 type = new (*this, TypeAlignment)
Leonard Chanc72aaf62019-05-07 03:20:17 +00003964 AttributedType(canon, attrKind, modifiedType, equivalentType);
John McCall81904512011-01-06 01:58:22 +00003965
3966 Types.push_back(type);
3967 AttributedTypes.InsertNode(type, insertPos);
3968
3969 return QualType(type, 0);
3970}
3971
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003972/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00003973QualType
3974ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003975 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003976 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003977 && "replacement types must always be canonical");
3978
3979 llvm::FoldingSetNodeID ID;
3980 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003981 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003982 SubstTemplateTypeParmType *SubstParm
3983 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3984
3985 if (!SubstParm) {
3986 SubstParm = new (*this, TypeAlignment)
3987 SubstTemplateTypeParmType(Parm, Replacement);
3988 Types.push_back(SubstParm);
3989 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3990 }
3991
3992 return QualType(SubstParm, 0);
3993}
3994
Fangrui Song6907ce22018-07-30 19:24:48 +00003995/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00003996QualType ASTContext::getSubstTemplateTypeParmPackType(
3997 const TemplateTypeParmType *Parm,
3998 const TemplateArgument &ArgPack) {
3999#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00004000 for (const auto &P : ArgPack.pack_elements()) {
4001 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4002 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00004003 }
4004#endif
Fangrui Song6907ce22018-07-30 19:24:48 +00004005
Douglas Gregorada4b792011-01-14 02:55:32 +00004006 llvm::FoldingSetNodeID ID;
4007 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00004008 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00004009 if (SubstTemplateTypeParmPackType *SubstParm
4010 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4011 return QualType(SubstParm, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00004012
Douglas Gregorada4b792011-01-14 02:55:32 +00004013 QualType Canon;
4014 if (!Parm->isCanonicalUnqualified()) {
4015 Canon = getCanonicalType(QualType(Parm, 0));
4016 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4017 ArgPack);
4018 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4019 }
4020
Eugene Zelenko7855e772018-04-03 00:11:50 +00004021 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00004022 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4023 ArgPack);
4024 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00004025 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00004026 return QualType(SubstParm, 0);
Douglas Gregorada4b792011-01-14 02:55:32 +00004027}
4028
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004029/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00004030/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00004031/// name.
Mike Stump11289f42009-09-09 15:08:12 +00004032QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00004033 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00004034 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00004035 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00004036 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00004037 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004038 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00004039 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4040
4041 if (TypeParm)
4042 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004043
Chandler Carruth08836322011-05-01 00:51:33 +00004044 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00004045 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00004046 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004047
Fangrui Song6907ce22018-07-30 19:24:48 +00004048 TemplateTypeParmType *TypeCheck
Douglas Gregorc42075a2010-02-04 18:10:26 +00004049 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4050 assert(!TypeCheck && "Template type parameter canonical type broken");
4051 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00004052 } else
John McCall90d1c2d2009-09-24 23:30:46 +00004053 TypeParm = new (*this, TypeAlignment)
4054 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00004055
4056 Types.push_back(TypeParm);
4057 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4058
4059 return QualType(TypeParm, 0);
4060}
4061
John McCalle78aac42010-03-10 03:28:59 +00004062TypeSourceInfo *
4063ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4064 SourceLocation NameLoc,
4065 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004066 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004067 assert(!Name.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004068 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004069 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00004070
4071 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00004072 TemplateSpecializationTypeLoc TL =
4073 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00004074 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00004075 TL.setTemplateNameLoc(NameLoc);
4076 TL.setLAngleLoc(Args.getLAngleLoc());
4077 TL.setRAngleLoc(Args.getRAngleLoc());
4078 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4079 TL.setArgLocInfo(i, Args[i].getLocInfo());
4080 return DI;
4081}
4082
Mike Stump11289f42009-09-09 15:08:12 +00004083QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00004084ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00004085 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004086 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004087 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004088 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00004089
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004090 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004091 ArgVec.reserve(Args.size());
4092 for (const TemplateArgumentLoc &Arg : Args.arguments())
4093 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00004094
David Majnemer6fbeee32016-07-07 04:43:07 +00004095 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00004096}
4097
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004098#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00004099static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4100 for (const TemplateArgument &Arg : Args)
4101 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004102 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004103
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004104 return true;
4105}
4106#endif
4107
John McCall0ad16662009-10-29 08:12:44 +00004108QualType
4109ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00004110 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004111 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004112 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004113 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00004114 // Look through qualified template names.
4115 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4116 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004117
4118 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00004119 Template.getAsTemplateDecl() &&
4120 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004121 QualType CanonType;
4122 if (!Underlying.isNull())
4123 CanonType = getCanonicalType(Underlying);
4124 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004125 // We can get here with an alias template when the specialization contains
4126 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00004127 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004128 "Caller must compute aliased type");
4129 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004130 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00004131 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00004132
Douglas Gregora8e02e72009-07-28 23:00:59 +00004133 // Allocate the (non-canonical) template specialization type, but don't
4134 // try to unique it: these types typically have location information that
4135 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004136 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00004137 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004138 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00004139 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004140 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00004141 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004142 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00004143
Douglas Gregor8bf42052009-02-09 18:46:07 +00004144 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00004145 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00004146}
4147
David Majnemer6fbeee32016-07-07 04:43:07 +00004148QualType ASTContext::getCanonicalTemplateSpecializationType(
4149 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004150 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004151 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004152
Douglas Gregore29139c2011-03-03 17:04:51 +00004153 // Look through qualified template names.
4154 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4155 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004156
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004157 // Build the canonical template specialization type.
4158 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004159 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004160 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004161 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004162 for (const TemplateArgument &Arg : Args)
4163 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004164
4165 // Determine whether this canonical template specialization type already
4166 // exists.
4167 llvm::FoldingSetNodeID ID;
4168 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004169 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004170
Craig Topper36250ad2014-05-12 05:36:57 +00004171 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004172 TemplateSpecializationType *Spec
4173 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4174
4175 if (!Spec) {
4176 // Allocate a new canonical template specialization type.
4177 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4178 sizeof(TemplateArgument) * NumArgs),
4179 TypeAlignment);
4180 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004181 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004182 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004183 Types.push_back(Spec);
4184 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4185 }
4186
4187 assert(Spec->isDependentType() &&
4188 "Non-dependent template-id type must have a canonical type");
4189 return QualType(Spec, 0);
4190}
4191
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004192QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4193 NestedNameSpecifier *NNS,
4194 QualType NamedType,
4195 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004196 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004197 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004198
Craig Topper36250ad2014-05-12 05:36:57 +00004199 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004200 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004201 if (T)
4202 return QualType(T, 0);
4203
Douglas Gregorc42075a2010-02-04 18:10:26 +00004204 QualType Canon = NamedType;
4205 if (!Canon.isCanonical()) {
4206 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004207 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4208 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004209 (void)CheckT;
4210 }
4211
Bruno Riccid6bd5982018-08-16 10:48:16 +00004212 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4213 TypeAlignment);
4214 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4215
Douglas Gregor52537682009-03-19 00:18:19 +00004216 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004217 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004218 return QualType(T, 0);
4219}
4220
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004221QualType
Jay Foad39c79802011-01-12 09:06:06 +00004222ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004223 llvm::FoldingSetNodeID ID;
4224 ParenType::Profile(ID, InnerType);
4225
Craig Topper36250ad2014-05-12 05:36:57 +00004226 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004227 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4228 if (T)
4229 return QualType(T, 0);
4230
4231 QualType Canon = InnerType;
4232 if (!Canon.isCanonical()) {
4233 Canon = getCanonicalType(InnerType);
4234 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4235 assert(!CheckT && "Paren canonical type broken");
4236 (void)CheckT;
4237 }
4238
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004239 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004240 Types.push_back(T);
4241 ParenTypes.InsertNode(T, InsertPos);
4242 return QualType(T, 0);
4243}
4244
Leonard Chanc72aaf62019-05-07 03:20:17 +00004245QualType
4246ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4247 const IdentifierInfo *MacroII) const {
4248 QualType Canon = UnderlyingTy;
4249 if (!Canon.isCanonical())
4250 Canon = getCanonicalType(UnderlyingTy);
4251
4252 auto *newType = new (*this, TypeAlignment)
4253 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4254 Types.push_back(newType);
4255 return QualType(newType, 0);
4256}
4257
Douglas Gregor02085352010-03-31 20:19:30 +00004258QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4259 NestedNameSpecifier *NNS,
4260 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004261 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004262 if (Canon.isNull()) {
4263 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004264 if (CanonNNS != NNS)
4265 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004266 }
4267
4268 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004269 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004270
Craig Topper36250ad2014-05-12 05:36:57 +00004271 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004272 DependentNameType *T
4273 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004274 if (T)
4275 return QualType(T, 0);
4276
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004277 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004278 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004279 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004280 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004281}
4282
Mike Stump11289f42009-09-09 15:08:12 +00004283QualType
John McCallc392f372010-06-11 00:33:02 +00004284ASTContext::getDependentTemplateSpecializationType(
4285 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004286 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004287 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004288 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004289 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004290 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004291 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4292 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004293 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004294}
4295
4296QualType
4297ASTContext::getDependentTemplateSpecializationType(
4298 ElaboratedTypeKeyword Keyword,
4299 NestedNameSpecifier *NNS,
4300 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004301 ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004302 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor6e068012011-02-28 00:04:36 +00004303 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004304
Douglas Gregorc42075a2010-02-04 18:10:26 +00004305 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004306 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004307 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004308
Craig Topper36250ad2014-05-12 05:36:57 +00004309 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004310 DependentTemplateSpecializationType *T
4311 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004312 if (T)
4313 return QualType(T, 0);
4314
John McCallc392f372010-06-11 00:33:02 +00004315 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004316
John McCallc392f372010-06-11 00:33:02 +00004317 ElaboratedTypeKeyword CanonKeyword = Keyword;
4318 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4319
4320 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004321 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004322 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004323 for (unsigned I = 0; I != NumArgs; ++I) {
4324 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4325 if (!CanonArgs[I].structurallyEquals(Args[I]))
4326 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004327 }
4328
John McCallc392f372010-06-11 00:33:02 +00004329 QualType Canon;
4330 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4331 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004332 Name,
4333 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004334
4335 // Find the insert position again.
4336 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4337 }
4338
4339 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4340 sizeof(TemplateArgument) * NumArgs),
4341 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004342 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004343 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004344 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004345 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004346 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004347}
4348
Richard Smith32918772017-02-14 00:25:28 +00004349TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4350 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004351 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004352 QualType ArgType = getTypeDeclType(TTP);
4353 if (TTP->isParameterPack())
4354 ArgType = getPackExpansionType(ArgType, None);
4355
4356 Arg = TemplateArgument(ArgType);
4357 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4358 Expr *E = new (*this) DeclRefExpr(
Bruno Ricci5fc4db72018-12-21 14:10:18 +00004359 *this, NTTP, /*enclosing*/ false,
Richard Smith32918772017-02-14 00:25:28 +00004360 NTTP->getType().getNonLValueExprType(*this),
4361 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4362
4363 if (NTTP->isParameterPack())
4364 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4365 None);
4366 Arg = TemplateArgument(E);
4367 } else {
4368 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4369 if (TTP->isParameterPack())
4370 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4371 else
4372 Arg = TemplateArgument(TemplateName(TTP));
4373 }
4374
4375 if (Param->isTemplateParameterPack())
4376 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4377
4378 return Arg;
4379}
4380
Richard Smith43e14d22016-12-23 02:10:11 +00004381void
4382ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4383 SmallVectorImpl<TemplateArgument> &Args) {
4384 Args.reserve(Args.size() + Params->size());
4385
Richard Smith32918772017-02-14 00:25:28 +00004386 for (NamedDecl *Param : *Params)
4387 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004388}
4389
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004390QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004391 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004392 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004393 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004394
Richard Smithb2997f52019-05-21 20:10:50 +00004395 // A deduced type can deduce to a pack, eg
4396 // auto ...x = some_pack;
4397 // That declaration isn't (yet) valid, but is created as part of building an
4398 // init-capture pack:
4399 // [...x = some_pack] {}
4400 assert((Pattern->containsUnexpandedParameterPack() ||
4401 Pattern->getContainedDeducedType()) &&
Douglas Gregord2fa7662010-12-20 02:24:11 +00004402 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004403 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004404 PackExpansionType *T
4405 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4406 if (T)
4407 return QualType(T, 0);
4408
4409 QualType Canon;
4410 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004411 Canon = getCanonicalType(Pattern);
4412 // The canonical type might not contain an unexpanded parameter pack, if it
4413 // contains an alias template specialization which ignores one of its
4414 // parameters.
4415 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004416 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004417
Richard Smith68eea502012-07-16 00:20:35 +00004418 // Find the insert position again, in case we inserted an element into
4419 // PackExpansionTypes and invalidated our insert position.
4420 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4421 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004422 }
4423
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004424 T = new (*this, TypeAlignment)
4425 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004426 Types.push_back(T);
4427 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004428 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004429}
4430
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004431/// CmpProtocolNames - Comparison predicate for sorting protocols
4432/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004433static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4434 ObjCProtocolDecl *const *RHS) {
4435 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004436}
4437
Craig Topper1f26d5b2016-01-03 19:43:23 +00004438static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4439 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004440
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004441 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4442 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004443
Craig Topper1f26d5b2016-01-03 19:43:23 +00004444 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004445 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004446 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004447 return false;
4448 return true;
4449}
4450
Craig Topper6a8c1512015-10-22 01:56:18 +00004451static void
4452SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004453 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004454 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004455
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004456 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004457 for (ObjCProtocolDecl *&P : Protocols)
4458 P = P->getCanonicalDecl();
4459
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004460 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004461 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4462 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004463}
4464
John McCall8b07ec22010-05-15 11:32:37 +00004465QualType ASTContext::getObjCObjectType(QualType BaseType,
4466 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004467 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004468 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004469 llvm::makeArrayRef(Protocols, NumProtocols),
4470 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004471}
4472
4473QualType ASTContext::getObjCObjectType(
4474 QualType baseType,
4475 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004476 ArrayRef<ObjCProtocolDecl *> protocols,
4477 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004478 // If the base type is an interface and there aren't any protocols or
4479 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004480 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4481 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004482 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004483
4484 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004485 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004486 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004487 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004488 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4489 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004490
Douglas Gregore9d95f12015-07-07 03:57:35 +00004491 // Determine the type arguments to be used for canonicalization,
4492 // which may be explicitly specified here or written on the base
4493 // type.
4494 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4495 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004496 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004497 effectiveTypeArgs = baseObject->getTypeArgs();
4498 }
John McCallfc93cf92009-10-22 22:37:11 +00004499
Douglas Gregore9d95f12015-07-07 03:57:35 +00004500 // Build the canonical type, which has the canonical base type and a
4501 // sorted-and-uniqued list of protocols and the type arguments
4502 // canonicalized.
4503 QualType canonical;
4504 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4505 effectiveTypeArgs.end(),
4506 [&](QualType type) {
4507 return type.isCanonical();
4508 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004509 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004510 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4511 // Determine the canonical type arguments.
4512 ArrayRef<QualType> canonTypeArgs;
4513 SmallVector<QualType, 4> canonTypeArgsVec;
4514 if (!typeArgsAreCanonical) {
4515 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4516 for (auto typeArg : effectiveTypeArgs)
4517 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4518 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004519 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004520 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004521 }
4522
Douglas Gregore9d95f12015-07-07 03:57:35 +00004523 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4524 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4525 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004526 canonProtocolsVec.append(protocols.begin(), protocols.end());
4527 SortAndUniqueProtocols(canonProtocolsVec);
4528 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004529 } else {
4530 canonProtocols = protocols;
4531 }
4532
4533 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004534 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004535
John McCallfc93cf92009-10-22 22:37:11 +00004536 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004537 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4538 }
4539
Douglas Gregore9d95f12015-07-07 03:57:35 +00004540 unsigned size = sizeof(ObjCObjectTypeImpl);
4541 size += typeArgs.size() * sizeof(QualType);
4542 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4543 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004544 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004545 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4546 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004547
4548 Types.push_back(T);
4549 ObjCObjectTypes.InsertNode(T, InsertPos);
4550 return QualType(T, 0);
4551}
4552
Manman Ren3569eb52016-09-13 17:03:12 +00004553/// Apply Objective-C protocol qualifiers to the given type.
4554/// If this is for the canonical type of a type parameter, we can apply
4555/// protocol qualifiers on the ObjCObjectPointerType.
4556QualType
4557ASTContext::applyObjCProtocolQualifiers(QualType type,
4558 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4559 bool allowOnPointerType) const {
4560 hasError = false;
4561
Eugene Zelenko7855e772018-04-03 00:11:50 +00004562 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004563 return getObjCTypeParamType(objT->getDecl(), protocols);
4564 }
4565
Manman Ren3569eb52016-09-13 17:03:12 +00004566 // Apply protocol qualifiers to ObjCObjectPointerType.
4567 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004568 if (const auto *objPtr =
4569 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004570 const ObjCObjectType *objT = objPtr->getObjectType();
4571 // Merge protocol lists and construct ObjCObjectType.
4572 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4573 protocolsVec.append(objT->qual_begin(),
4574 objT->qual_end());
4575 protocolsVec.append(protocols.begin(), protocols.end());
4576 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4577 type = getObjCObjectType(
4578 objT->getBaseType(),
4579 objT->getTypeArgsAsWritten(),
4580 protocols,
4581 objT->isKindOfTypeAsWritten());
4582 return getObjCObjectPointerType(type);
4583 }
4584 }
4585
4586 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004587 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004588 // FIXME: Check for protocols to which the class type is already
4589 // known to conform.
4590
4591 return getObjCObjectType(objT->getBaseType(),
4592 objT->getTypeArgsAsWritten(),
4593 protocols,
4594 objT->isKindOfTypeAsWritten());
4595 }
4596
4597 // If the canonical type is ObjCObjectType, ...
4598 if (type->isObjCObjectType()) {
4599 // Silently overwrite any existing protocol qualifiers.
4600 // TODO: determine whether that's the right thing to do.
4601
4602 // FIXME: Check for protocols to which the class type is already
4603 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004604 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004605 }
4606
4607 // id<protocol-list>
4608 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004609 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004610 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004611 objPtr->isKindOfType());
4612 return getObjCObjectPointerType(type);
4613 }
4614
4615 // Class<protocol-list>
4616 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004617 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004618 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004619 objPtr->isKindOfType());
4620 return getObjCObjectPointerType(type);
4621 }
4622
4623 hasError = true;
4624 return type;
4625}
4626
Manman Rene6be26c2016-09-13 17:25:08 +00004627QualType
4628ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4629 ArrayRef<ObjCProtocolDecl *> protocols,
4630 QualType Canonical) const {
4631 // Look in the folding set for an existing type.
4632 llvm::FoldingSetNodeID ID;
4633 ObjCTypeParamType::Profile(ID, Decl, protocols);
4634 void *InsertPos = nullptr;
4635 if (ObjCTypeParamType *TypeParam =
4636 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4637 return QualType(TypeParam, 0);
4638
4639 if (Canonical.isNull()) {
4640 // We canonicalize to the underlying type.
4641 Canonical = getCanonicalType(Decl->getUnderlyingType());
4642 if (!protocols.empty()) {
4643 // Apply the protocol qualifers.
4644 bool hasError;
Richard Trieua986a312018-08-30 01:57:52 +00004645 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4646 Canonical, protocols, hasError, true /*allowOnPointerType*/));
Manman Rene6be26c2016-09-13 17:25:08 +00004647 assert(!hasError && "Error when apply protocol qualifier to bound type");
4648 }
4649 }
4650
4651 unsigned size = sizeof(ObjCTypeParamType);
4652 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4653 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004654 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004655
4656 Types.push_back(newType);
4657 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4658 return QualType(newType, 0);
4659}
4660
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004661/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4662/// protocol list adopt all protocols in QT's qualified-id protocol
4663/// list.
4664bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4665 ObjCInterfaceDecl *IC) {
4666 if (!QT->isObjCQualifiedIdType())
4667 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004668
Eugene Zelenko7855e772018-04-03 00:11:50 +00004669 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004670 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004671 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004672 if (!IC->ClassImplementsProtocol(Proto, false))
4673 return false;
4674 }
4675 return true;
4676 }
4677 return false;
4678}
4679
4680/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4681/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4682/// of protocols.
4683bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4684 ObjCInterfaceDecl *IDecl) {
4685 if (!QT->isObjCQualifiedIdType())
4686 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004687 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004688 if (!OPT)
4689 return false;
4690 if (!IDecl->hasDefinition())
4691 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004692 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4693 CollectInheritedProtocols(IDecl, InheritedProtocols);
4694 if (InheritedProtocols.empty())
4695 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004696 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004697 // of IDecl's, then bridge casting is ok.
4698 bool Conforms = false;
4699 for (auto *Proto : OPT->quals()) {
4700 Conforms = false;
4701 for (auto *PI : InheritedProtocols) {
4702 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4703 Conforms = true;
4704 break;
4705 }
4706 }
4707 if (!Conforms)
4708 break;
4709 }
4710 if (Conforms)
4711 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004712
Aaron Ballman83731462014-03-17 16:14:00 +00004713 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004714 // If both the right and left sides have qualifiers.
4715 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004716 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004717 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004718 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004719 break;
4720 }
4721 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004722 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004723 }
4724 return true;
4725}
4726
John McCall8b07ec22010-05-15 11:32:37 +00004727/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4728/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004729QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004730 llvm::FoldingSetNodeID ID;
4731 ObjCObjectPointerType::Profile(ID, ObjectT);
4732
Craig Topper36250ad2014-05-12 05:36:57 +00004733 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004734 if (ObjCObjectPointerType *QT =
4735 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4736 return QualType(QT, 0);
4737
4738 // Find the canonical object type.
4739 QualType Canonical;
4740 if (!ObjectT.isCanonical()) {
4741 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4742
4743 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004744 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4745 }
4746
Douglas Gregorf85bee62010-02-08 22:59:26 +00004747 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004748 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004749 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004750 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004751
Steve Narofffb4330f2009-06-17 22:40:22 +00004752 Types.push_back(QType);
4753 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004754 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004755}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004756
Douglas Gregor1c283312010-08-11 12:19:30 +00004757/// getObjCInterfaceType - Return the unique reference to the type for the
4758/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004759QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4760 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004761 if (Decl->TypeForDecl)
4762 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004763
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004764 if (PrevDecl) {
4765 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4766 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4767 return QualType(PrevDecl->TypeForDecl, 0);
4768 }
4769
Douglas Gregor7671e532011-12-16 16:34:57 +00004770 // Prefer the definition, if there is one.
4771 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4772 Decl = Def;
Fangrui Song6907ce22018-07-30 19:24:48 +00004773
Douglas Gregor1c283312010-08-11 12:19:30 +00004774 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004775 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004776 Decl->TypeForDecl = T;
4777 Types.push_back(T);
4778 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004779}
4780
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004781/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4782/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004783/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004784/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004785/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004786QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004787 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004788 if (tofExpr->isTypeDependent()) {
4789 llvm::FoldingSetNodeID ID;
4790 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004791
Craig Topper36250ad2014-05-12 05:36:57 +00004792 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004793 DependentTypeOfExprType *Canon
4794 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4795 if (Canon) {
4796 // We already have a "canonical" version of an identical, dependent
4797 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004798 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004799 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004800 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004801 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004802 Canon
4803 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004804 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4805 toe = Canon;
4806 }
4807 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004808 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004809 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004810 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004811 Types.push_back(toe);
4812 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004813}
4814
Steve Naroffa773cd52007-08-01 18:02:17 +00004815/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004816/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004817/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004818/// an issue. This doesn't affect the type checker, since it operates
4819/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004820QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004821 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004822 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004823 Types.push_back(tot);
4824 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004825}
4826
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004827/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004828/// nodes. This would never be helpful, since each such type has its own
4829/// expression, and would not give a significant memory saving, since there
4830/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004831QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004832 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004833
4834 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004835 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004836 // unique dependent type. Two such decltype-specifiers refer to the same
4837 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004838 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004839 llvm::FoldingSetNodeID ID;
4840 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004841
Craig Topper36250ad2014-05-12 05:36:57 +00004842 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004843 DependentDecltypeType *Canon
4844 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004845 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004846 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004847 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004848 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004849 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004850 dt = new (*this, TypeAlignment)
4851 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004852 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004853 dt = new (*this, TypeAlignment)
4854 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004855 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004856 Types.push_back(dt);
4857 return QualType(dt, 0);
4858}
4859
Alexis Hunte852b102011-05-24 22:41:36 +00004860/// getUnaryTransformationType - We don't unique these, since the memory
4861/// savings are minimal and these are rare.
4862QualType ASTContext::getUnaryTransformType(QualType BaseType,
4863 QualType UnderlyingType,
4864 UnaryTransformType::UTTKind Kind)
4865 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004866 UnaryTransformType *ut = nullptr;
4867
4868 if (BaseType->isDependentType()) {
4869 // Look in the folding set for an existing type.
4870 llvm::FoldingSetNodeID ID;
4871 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4872
4873 void *InsertPos = nullptr;
4874 DependentUnaryTransformType *Canon
4875 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4876
4877 if (!Canon) {
4878 // Build a new, canonical __underlying_type(type) type.
4879 Canon = new (*this, TypeAlignment)
4880 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4881 Kind);
4882 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4883 }
4884 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4885 QualType(), Kind,
4886 QualType(Canon, 0));
4887 } else {
4888 QualType CanonType = getCanonicalType(UnderlyingType);
4889 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4890 UnderlyingType, Kind,
4891 CanonType);
4892 }
4893 Types.push_back(ut);
4894 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004895}
4896
Richard Smith2a7d4812013-05-04 07:00:32 +00004897/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4898/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4899/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004900QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Richard Smithb2997f52019-05-21 20:10:50 +00004901 bool IsDependent, bool IsPack) const {
4902 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
Richard Smithe301ba22015-11-11 02:02:15 +00004903 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004904 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004905
Richard Smith2a7d4812013-05-04 07:00:32 +00004906 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004907 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004908 llvm::FoldingSetNodeID ID;
Richard Smithb2997f52019-05-21 20:10:50 +00004909 AutoType::Profile(ID, DeducedType, Keyword, IsDependent, IsPack);
Richard Smith2a7d4812013-05-04 07:00:32 +00004910 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4911 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004912
Eugene Zelenko7855e772018-04-03 00:11:50 +00004913 auto *AT = new (*this, TypeAlignment)
Richard Smithb2997f52019-05-21 20:10:50 +00004914 AutoType(DeducedType, Keyword, IsDependent, IsPack);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004915 Types.push_back(AT);
4916 if (InsertPos)
4917 AutoTypes.InsertNode(AT, InsertPos);
4918 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004919}
4920
Richard Smith600b5262017-01-26 20:40:47 +00004921/// Return the uniqued reference to the deduced template specialization type
4922/// which has been deduced to the given type, or to the canonical undeduced
4923/// such type, or the canonical deduced-but-dependent such type.
4924QualType ASTContext::getDeducedTemplateSpecializationType(
4925 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4926 // Look in the folding set for an existing type.
4927 void *InsertPos = nullptr;
4928 llvm::FoldingSetNodeID ID;
4929 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4930 IsDependent);
4931 if (DeducedTemplateSpecializationType *DTST =
4932 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4933 return QualType(DTST, 0);
4934
Eugene Zelenko7855e772018-04-03 00:11:50 +00004935 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00004936 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4937 Types.push_back(DTST);
4938 if (InsertPos)
4939 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4940 return QualType(DTST, 0);
4941}
4942
Eli Friedman0dfb8892011-10-06 23:00:33 +00004943/// getAtomicType - Return the uniqued reference to the atomic type for
4944/// the given value type.
4945QualType ASTContext::getAtomicType(QualType T) const {
4946 // Unique pointers, to guarantee there is only one pointer of a particular
4947 // structure.
4948 llvm::FoldingSetNodeID ID;
4949 AtomicType::Profile(ID, T);
4950
Craig Topper36250ad2014-05-12 05:36:57 +00004951 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004952 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4953 return QualType(AT, 0);
4954
4955 // If the atomic value type isn't canonical, this won't be a canonical type
4956 // either, so fill in the canonical type field.
4957 QualType Canonical;
4958 if (!T.isCanonical()) {
4959 Canonical = getAtomicType(getCanonicalType(T));
4960
4961 // Get the new insert position for the node we care about.
4962 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004963 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004964 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00004965 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00004966 Types.push_back(New);
4967 AtomicTypes.InsertNode(New, InsertPos);
4968 return QualType(New, 0);
4969}
4970
Richard Smith02e85f32011-04-14 22:09:26 +00004971/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4972QualType ASTContext::getAutoDeductType() const {
4973 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004974 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004975 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Richard Smithb2997f52019-05-21 20:10:50 +00004976 /*dependent*/false, /*pack*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004977 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004978 return AutoDeductTy;
4979}
4980
4981/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4982QualType ASTContext::getAutoRRefDeductType() const {
4983 if (AutoRRefDeductTy.isNull())
4984 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4985 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4986 return AutoRRefDeductTy;
4987}
4988
Chris Lattnerfb072462007-01-23 05:45:31 +00004989/// getTagDeclType - Return the unique reference to the type for the
4990/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004991QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004992 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004993 // FIXME: What is the design on getTagDeclType when it requires casting
4994 // away const? mutable?
4995 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004996}
4997
Mike Stump11289f42009-09-09 15:08:12 +00004998/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4999/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5000/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00005001CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005002 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00005003}
Chris Lattnerfb072462007-01-23 05:45:31 +00005004
Fangrui Song6907ce22018-07-30 19:24:48 +00005005/// Return the unique signed counterpart of the integer type
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00005006/// corresponding to size_t.
5007CanQualType ASTContext::getSignedSizeType() const {
5008 return getFromTargetType(Target->getSignedSizeType());
5009}
5010
Hans Wennborg27541db2011-10-27 08:29:09 +00005011/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5012CanQualType ASTContext::getIntMaxType() const {
5013 return getFromTargetType(Target->getIntMaxType());
5014}
5015
5016/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5017CanQualType ASTContext::getUIntMaxType() const {
5018 return getFromTargetType(Target->getUIntMaxType());
5019}
5020
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00005021/// getSignedWCharType - Return the type of "signed wchar_t".
5022/// Used when in C++, as a GCC extension.
5023QualType ASTContext::getSignedWCharType() const {
5024 // FIXME: derive from "Target" ?
5025 return WCharTy;
5026}
5027
5028/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5029/// Used when in C++, as a GCC extension.
5030QualType ASTContext::getUnsignedWCharType() const {
5031 // FIXME: derive from "Target" ?
5032 return UnsignedIntTy;
5033}
5034
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00005035QualType ASTContext::getIntPtrType() const {
5036 return getFromTargetType(Target->getIntPtrType());
5037}
5038
5039QualType ASTContext::getUIntPtrType() const {
5040 return getCorrespondingUnsignedType(getIntPtrType());
5041}
5042
Hans Wennborg27541db2011-10-27 08:29:09 +00005043/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005044/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5045QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005046 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005047}
5048
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005049/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00005050/// integer type. The standard (C11 7.21.6.1p7) refers to this type
5051/// in the definition of %tu format specifier.
5052QualType ASTContext::getUnsignedPointerDiffType() const {
5053 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5054}
5055
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005056/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00005057/// <sys/types.h>. We need this to compute the correct type for vfork().
5058QualType ASTContext::getProcessIDType() const {
5059 return getFromTargetType(Target->getProcessIDType());
5060}
5061
Chris Lattnera21ad802008-04-02 05:18:44 +00005062//===----------------------------------------------------------------------===//
5063// Type Operators
5064//===----------------------------------------------------------------------===//
5065
Jay Foad39c79802011-01-12 09:06:06 +00005066CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00005067 // Push qualifiers into arrays, and then discard any remaining
5068 // qualifiers.
5069 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00005070 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00005071 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00005072 QualType Result;
5073 if (isa<ArrayType>(Ty)) {
5074 Result = getArrayDecayedType(QualType(Ty,0));
5075 } else if (isa<FunctionType>(Ty)) {
5076 Result = getPointerType(QualType(Ty, 0));
5077 } else {
5078 Result = QualType(Ty, 0);
5079 }
5080
5081 return CanQualType::CreateUnsafe(Result);
5082}
5083
John McCall6c9dd522011-01-18 07:41:22 +00005084QualType ASTContext::getUnqualifiedArrayType(QualType type,
5085 Qualifiers &quals) {
5086 SplitQualType splitType = type.getSplitUnqualifiedType();
5087
5088 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5089 // the unqualified desugared type and then drops it on the floor.
5090 // We then have to strip that sugar back off with
5091 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005092 const auto *AT =
5093 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00005094
5095 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005096 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00005097 quals = splitType.Quals;
5098 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005099 }
5100
John McCall6c9dd522011-01-18 07:41:22 +00005101 // Otherwise, recurse on the array's element type.
5102 QualType elementType = AT->getElementType();
5103 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5104
5105 // If that didn't change the element type, AT has no qualifiers, so we
5106 // can just use the results in splitType.
5107 if (elementType == unqualElementType) {
5108 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00005109 quals = splitType.Quals;
5110 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00005111 }
5112
5113 // Otherwise, add in the qualifiers from the outermost type, then
5114 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00005115 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005116
Eugene Zelenko7855e772018-04-03 00:11:50 +00005117 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005118 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005119 CAT->getSizeModifier(), 0);
5120 }
5121
Eugene Zelenko7855e772018-04-03 00:11:50 +00005122 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005123 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005124 }
5125
Eugene Zelenko7855e772018-04-03 00:11:50 +00005126 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005127 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00005128 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005129 VAT->getSizeModifier(),
5130 VAT->getIndexTypeCVRQualifiers(),
5131 VAT->getBracketsRange());
5132 }
5133
Eugene Zelenko7855e772018-04-03 00:11:50 +00005134 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00005135 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005136 DSAT->getSizeModifier(), 0,
5137 SourceRange());
5138}
5139
Richard Smitha3405ff2018-07-11 00:19:19 +00005140/// Attempt to unwrap two types that may both be array types with the same bound
5141/// (or both be array types of unknown bound) for the purpose of comparing the
5142/// cv-decomposition of two types per C++ [conv.qual].
Richard Smith5407d4f2018-07-18 20:13:36 +00005143bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5144 bool UnwrappedAny = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00005145 while (true) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005146 auto *AT1 = getAsArrayType(T1);
5147 if (!AT1) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005148
Richard Smith5407d4f2018-07-18 20:13:36 +00005149 auto *AT2 = getAsArrayType(T2);
5150 if (!AT2) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005151
5152 // If we don't have two array types with the same constant bound nor two
5153 // incomplete array types, we've unwrapped everything we can.
5154 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5155 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5156 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
Richard Smith5407d4f2018-07-18 20:13:36 +00005157 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005158 } else if (!isa<IncompleteArrayType>(AT1) ||
5159 !isa<IncompleteArrayType>(AT2)) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005160 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005161 }
5162
5163 T1 = AT1->getElementType();
5164 T2 = AT2->getElementType();
Richard Smith5407d4f2018-07-18 20:13:36 +00005165 UnwrappedAny = true;
Richard Smitha3405ff2018-07-11 00:19:19 +00005166 }
5167}
5168
5169/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5170///
5171/// If T1 and T2 are both pointer types of the same kind, or both array types
5172/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5173/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5174///
5175/// This function will typically be called in a loop that successively
5176/// "unwraps" pointer and pointer-to-member types to compare them at each
5177/// level.
5178///
5179/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5180/// pair of types that can't be unwrapped further.
5181bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005182 UnwrapSimilarArrayTypes(T1, T2);
Richard Smitha3405ff2018-07-11 00:19:19 +00005183
Eugene Zelenko7855e772018-04-03 00:11:50 +00005184 const auto *T1PtrType = T1->getAs<PointerType>();
5185 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005186 if (T1PtrType && T2PtrType) {
5187 T1 = T1PtrType->getPointeeType();
5188 T2 = T2PtrType->getPointeeType();
5189 return true;
5190 }
Richard Smith5407d4f2018-07-18 20:13:36 +00005191
Eugene Zelenko7855e772018-04-03 00:11:50 +00005192 const auto *T1MPType = T1->getAs<MemberPointerType>();
5193 const auto *T2MPType = T2->getAs<MemberPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00005194 if (T1MPType && T2MPType &&
5195 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005196 QualType(T2MPType->getClass(), 0))) {
5197 T1 = T1MPType->getPointeeType();
5198 T2 = T2MPType->getPointeeType();
5199 return true;
5200 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005201
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005202 if (getLangOpts().ObjC) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005203 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5204 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005205 if (T1OPType && T2OPType) {
5206 T1 = T1OPType->getPointeeType();
5207 T2 = T2OPType->getPointeeType();
5208 return true;
5209 }
5210 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005211
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005212 // FIXME: Block pointers, too?
Fangrui Song6907ce22018-07-30 19:24:48 +00005213
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005214 return false;
5215}
5216
Richard Smitha3405ff2018-07-11 00:19:19 +00005217bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5218 while (true) {
5219 Qualifiers Quals;
5220 T1 = getUnqualifiedArrayType(T1, Quals);
5221 T2 = getUnqualifiedArrayType(T2, Quals);
5222 if (hasSameType(T1, T2))
5223 return true;
5224 if (!UnwrapSimilarTypes(T1, T2))
5225 return false;
5226 }
5227}
5228
5229bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5230 while (true) {
5231 Qualifiers Quals1, Quals2;
5232 T1 = getUnqualifiedArrayType(T1, Quals1);
5233 T2 = getUnqualifiedArrayType(T2, Quals2);
5234
5235 Quals1.removeCVRQualifiers();
5236 Quals2.removeCVRQualifiers();
5237 if (Quals1 != Quals2)
5238 return false;
5239
5240 if (hasSameType(T1, T2))
5241 return true;
5242
5243 if (!UnwrapSimilarTypes(T1, T2))
5244 return false;
5245 }
5246}
5247
Jay Foad39c79802011-01-12 09:06:06 +00005248DeclarationNameInfo
5249ASTContext::getNameForTemplate(TemplateName Name,
5250 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005251 switch (Name.getKind()) {
5252 case TemplateName::QualifiedTemplate:
5253 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005254 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005255 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5256 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005257
John McCalld9dfe3a2011-06-30 08:33:18 +00005258 case TemplateName::OverloadedTemplate: {
5259 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5260 // DNInfo work in progress: CHECKME: what about DNLoc?
5261 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5262 }
5263
Richard Smithb23c5e82019-05-09 03:31:27 +00005264 case TemplateName::AssumedTemplate: {
5265 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5266 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5267 }
5268
John McCalld9dfe3a2011-06-30 08:33:18 +00005269 case TemplateName::DependentTemplate: {
5270 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005271 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005272 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005273 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5274 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005275 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005276 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5277 // DNInfo work in progress: FIXME: source locations?
5278 DeclarationNameLoc DNLoc;
5279 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5280 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5281 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005282 }
5283 }
5284
John McCalld9dfe3a2011-06-30 08:33:18 +00005285 case TemplateName::SubstTemplateTemplateParm: {
5286 SubstTemplateTemplateParmStorage *subst
5287 = Name.getAsSubstTemplateTemplateParm();
5288 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5289 NameLoc);
5290 }
5291
5292 case TemplateName::SubstTemplateTemplateParmPack: {
5293 SubstTemplateTemplateParmPackStorage *subst
5294 = Name.getAsSubstTemplateTemplateParmPack();
5295 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5296 NameLoc);
5297 }
5298 }
5299
5300 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005301}
5302
Jay Foad39c79802011-01-12 09:06:06 +00005303TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005304 switch (Name.getKind()) {
5305 case TemplateName::QualifiedTemplate:
5306 case TemplateName::Template: {
5307 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005308 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005309 Template = getCanonicalTemplateTemplateParmDecl(TTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00005310
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005311 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005312 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005313 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005314
John McCalld9dfe3a2011-06-30 08:33:18 +00005315 case TemplateName::OverloadedTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00005316 case TemplateName::AssumedTemplate:
5317 llvm_unreachable("cannot canonicalize unresolved template");
Mike Stump11289f42009-09-09 15:08:12 +00005318
John McCalld9dfe3a2011-06-30 08:33:18 +00005319 case TemplateName::DependentTemplate: {
5320 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5321 assert(DTN && "Non-dependent template names must refer to template decls.");
5322 return DTN->CanonicalTemplateName;
5323 }
5324
5325 case TemplateName::SubstTemplateTemplateParm: {
5326 SubstTemplateTemplateParmStorage *subst
5327 = Name.getAsSubstTemplateTemplateParm();
5328 return getCanonicalTemplateName(subst->getReplacement());
5329 }
5330
5331 case TemplateName::SubstTemplateTemplateParmPack: {
5332 SubstTemplateTemplateParmPackStorage *subst
5333 = Name.getAsSubstTemplateTemplateParmPack();
5334 TemplateTemplateParmDecl *canonParameter
5335 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5336 TemplateArgument canonArgPack
5337 = getCanonicalTemplateArgument(subst->getArgumentPack());
5338 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5339 }
5340 }
5341
5342 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005343}
5344
Douglas Gregoradee3e32009-11-11 23:06:43 +00005345bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5346 X = getCanonicalTemplateName(X);
5347 Y = getCanonicalTemplateName(Y);
5348 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5349}
5350
Mike Stump11289f42009-09-09 15:08:12 +00005351TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005352ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005353 switch (Arg.getKind()) {
5354 case TemplateArgument::Null:
5355 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005356
Douglas Gregora8e02e72009-07-28 23:00:59 +00005357 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005358 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005359
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005360 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005361 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005362 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005363 }
Mike Stump11289f42009-09-09 15:08:12 +00005364
Eli Friedmanb826a002012-09-26 02:36:12 +00005365 case TemplateArgument::NullPtr:
5366 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5367 /*isNullPtr*/true);
5368
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005369 case TemplateArgument::Template:
5370 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005371
5372 case TemplateArgument::TemplateExpansion:
5373 return TemplateArgument(getCanonicalTemplateName(
5374 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005375 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005376
Douglas Gregora8e02e72009-07-28 23:00:59 +00005377 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005378 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005379
Douglas Gregora8e02e72009-07-28 23:00:59 +00005380 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005381 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005382
Douglas Gregora8e02e72009-07-28 23:00:59 +00005383 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005384 if (Arg.pack_size() == 0)
5385 return Arg;
Fangrui Song6907ce22018-07-30 19:24:48 +00005386
Eugene Zelenko7855e772018-04-03 00:11:50 +00005387 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005388 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005389 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005390 AEnd = Arg.pack_end();
5391 A != AEnd; (void)++A, ++Idx)
5392 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005393
Benjamin Kramercce63472015-08-05 09:40:22 +00005394 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005395 }
5396 }
5397
5398 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005399 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005400}
5401
Douglas Gregor333489b2009-03-27 23:10:48 +00005402NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005403ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005404 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005405 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005406
5407 switch (NNS->getKind()) {
5408 case NestedNameSpecifier::Identifier:
5409 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005410 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005411 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5412 NNS->getAsIdentifier());
5413
5414 case NestedNameSpecifier::Namespace:
5415 // A namespace is canonical; build a nested-name-specifier with
5416 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005417 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005418 NNS->getAsNamespace()->getOriginalNamespace());
5419
5420 case NestedNameSpecifier::NamespaceAlias:
5421 // A namespace is canonical; build a nested-name-specifier with
5422 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005423 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005424 NNS->getAsNamespaceAlias()->getNamespace()
5425 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005426
5427 case NestedNameSpecifier::TypeSpec:
5428 case NestedNameSpecifier::TypeSpecWithTemplate: {
5429 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Fangrui Song6907ce22018-07-30 19:24:48 +00005430
Douglas Gregor3ade5702010-11-04 00:09:33 +00005431 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5432 // break it apart into its prefix and identifier, then reconsititute those
5433 // as the canonical nested-name-specifier. This is required to canonicalize
5434 // a dependent nested-name-specifier involving typedefs of dependent-name
5435 // types, e.g.,
5436 // typedef typename T::type T1;
5437 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005438 if (const auto *DNT = T->getAs<DependentNameType>())
Fangrui Song6907ce22018-07-30 19:24:48 +00005439 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005440 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005441
Eli Friedman5358a0a2012-03-03 04:09:56 +00005442 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5443 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5444 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005445 return NestedNameSpecifier::Create(*this, nullptr, false,
5446 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005447 }
5448
5449 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005450 case NestedNameSpecifier::Super:
5451 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005452 return NNS;
5453 }
5454
David Blaikie8a40f702012-01-17 06:56:22 +00005455 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005456}
5457
Jay Foad39c79802011-01-12 09:06:06 +00005458const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005459 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005460 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005461 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005462 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005463 return AT;
5464 }
Mike Stump11289f42009-09-09 15:08:12 +00005465
John McCall8ccfcb52009-09-24 19:53:00 +00005466 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005467 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005468 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005469
John McCall8ccfcb52009-09-24 19:53:00 +00005470 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005471 // implements C99 6.7.3p8: "If the specification of an array type includes
5472 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005473
Chris Lattner7adf0762008-08-04 07:31:14 +00005474 // If we get here, we either have type qualifiers on the type, or we have
5475 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005476 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005477
John McCall33ddac02011-01-19 10:06:00 +00005478 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005479 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005480
Chris Lattner7adf0762008-08-04 07:31:14 +00005481 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005482 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005483 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005484 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005485
Chris Lattner7adf0762008-08-04 07:31:14 +00005486 // Otherwise, we have an array and we have qualifiers on it. Push the
5487 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005488 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005489
Eugene Zelenko7855e772018-04-03 00:11:50 +00005490 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005491 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5492 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005493 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005494 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005495 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5496 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005497 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005498
Eugene Zelenko7855e772018-04-03 00:11:50 +00005499 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005500 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005501 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005502 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005503 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005504 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005505 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005506
Eugene Zelenko7855e772018-04-03 00:11:50 +00005507 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005508 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005509 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005510 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005511 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005512 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005513}
5514
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005515QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005516 if (T->isArrayType() || T->isFunctionType())
5517 return getDecayedType(T);
5518 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005519}
5520
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005521QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005522 T = getVariableArrayDecayedType(T);
5523 T = getAdjustedParameterType(T);
5524 return T.getUnqualifiedType();
5525}
5526
David Majnemerd09a51c2015-03-03 01:50:05 +00005527QualType ASTContext::getExceptionObjectType(QualType T) const {
5528 // C++ [except.throw]p3:
5529 // A throw-expression initializes a temporary object, called the exception
5530 // object, the type of which is determined by removing any top-level
5531 // cv-qualifiers from the static type of the operand of throw and adjusting
5532 // the type from "array of T" or "function returning T" to "pointer to T"
5533 // or "pointer to function returning T", [...]
5534 T = getVariableArrayDecayedType(T);
5535 if (T->isArrayType() || T->isFunctionType())
5536 T = getDecayedType(T);
5537 return T.getUnqualifiedType();
5538}
5539
Chris Lattnera21ad802008-04-02 05:18:44 +00005540/// getArrayDecayedType - Return the properly qualified result of decaying the
5541/// specified array type to a pointer. This operation is non-trivial when
5542/// handling typedefs etc. The canonical type of "T" must be an array type,
5543/// this returns a pointer to a properly qualified element of the array.
5544///
5545/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005546QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005547 // Get the element type with 'getAsArrayType' so that we don't lose any
5548 // typedefs in the element type of the array. This also handles propagation
5549 // of type qualifiers from the array type into the element type if present
5550 // (C99 6.7.3p8).
5551 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5552 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005553
Chris Lattner7adf0762008-08-04 07:31:14 +00005554 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005555
5556 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005557 QualType Result = getQualifiedType(PtrTy,
5558 PrettyArrayType->getIndexTypeQualifiers());
5559
5560 // int x[_Nullable] -> int * _Nullable
5561 if (auto Nullability = Ty->getNullability(*this)) {
5562 Result = const_cast<ASTContext *>(this)->getAttributedType(
5563 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5564 }
5565 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005566}
5567
John McCall33ddac02011-01-19 10:06:00 +00005568QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5569 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005570}
5571
John McCall33ddac02011-01-19 10:06:00 +00005572QualType ASTContext::getBaseElementType(QualType type) const {
5573 Qualifiers qs;
5574 while (true) {
5575 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005576 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005577 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005578
John McCall33ddac02011-01-19 10:06:00 +00005579 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005580 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005581 }
Mike Stump11289f42009-09-09 15:08:12 +00005582
John McCall33ddac02011-01-19 10:06:00 +00005583 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005584}
5585
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005586/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005587uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005588ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5589 uint64_t ElementCount = 1;
5590 do {
5591 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005592 CA = dyn_cast_or_null<ConstantArrayType>(
5593 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005594 } while (CA);
5595 return ElementCount;
5596}
5597
Steve Naroff0af91202007-04-27 21:51:21 +00005598/// getFloatingRank - Return a relative rank for floating point types.
5599/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005600static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005601 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005602 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005603
John McCall9dd450b2009-09-21 23:43:11 +00005604 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5605 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005606 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005607 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005608 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005609 case BuiltinType::Float: return FloatRank;
5610 case BuiltinType::Double: return DoubleRank;
5611 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005612 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005613 }
5614}
5615
Mike Stump11289f42009-09-09 15:08:12 +00005616/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5617/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005618/// 'typeDomain' is a real floating point or complex type.
5619/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005620QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5621 QualType Domain) const {
5622 FloatingRank EltRank = getFloatingRank(Size);
5623 if (Domain->isComplexType()) {
5624 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005625 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005626 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005627 case FloatRank: return FloatComplexTy;
5628 case DoubleRank: return DoubleComplexTy;
5629 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005630 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005631 }
Steve Naroff0af91202007-04-27 21:51:21 +00005632 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005633
5634 assert(Domain->isRealFloatingType() && "Unknown domain!");
5635 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005636 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005637 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005638 case FloatRank: return FloatTy;
5639 case DoubleRank: return DoubleTy;
5640 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005641 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005642 }
David Blaikief47fa302012-01-17 02:30:50 +00005643 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005644}
5645
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005646/// getFloatingTypeOrder - Compare the rank of the two specified floating
5647/// point types, ignoring the domain of the type (i.e. 'double' ==
5648/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005649/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005650int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005651 FloatingRank LHSR = getFloatingRank(LHS);
5652 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005653
Chris Lattnerb90739d2008-04-06 23:38:49 +00005654 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005655 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005656 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005657 return 1;
5658 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005659}
5660
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +00005661int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
5662 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
5663 return 0;
5664 return getFloatingTypeOrder(LHS, RHS);
5665}
5666
Chris Lattner76a00cf2008-04-06 22:59:24 +00005667/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5668/// routine will assert if passed a built-in type that isn't an integer or enum,
5669/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005670unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005671 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005672
Chris Lattner76a00cf2008-04-06 22:59:24 +00005673 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005674 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005675 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005676 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005677 case BuiltinType::Char_S:
5678 case BuiltinType::Char_U:
5679 case BuiltinType::SChar:
5680 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005681 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005682 case BuiltinType::Short:
5683 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005684 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005685 case BuiltinType::Int:
5686 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005687 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005688 case BuiltinType::Long:
5689 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005690 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005691 case BuiltinType::LongLong:
5692 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005693 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005694 case BuiltinType::Int128:
5695 case BuiltinType::UInt128:
5696 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005697 }
5698}
5699
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005700/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005701/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5702///
5703/// \returns the type this bit-field will promote to, or NULL if no
5704/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005705QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005706 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005707 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005708
Richard Smithaadb2542018-06-28 21:17:55 +00005709 // C++ [conv.prom]p5:
5710 // If the bit-field has an enumerated type, it is treated as any other
5711 // value of that type for promotion purposes.
5712 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5713 return {};
5714
Richard Smith5b571672014-09-24 23:55:00 +00005715 // FIXME: We should not do this unless E->refersToBitField() is true. This
5716 // matters in C where getSourceBitField() will find bit-fields for various
5717 // cases where the source expression is not a bit-field designator.
5718
John McCalld25db7e2013-05-06 21:39:12 +00005719 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005720 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005721 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005722
5723 QualType FT = Field->getType();
5724
Richard Smithcaf33902011-10-10 18:28:20 +00005725 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005726 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005727 // C++ [conv.prom]p5:
5728 // A prvalue for an integral bit-field can be converted to a prvalue of type
5729 // int if int can represent all the values of the bit-field; otherwise, it
5730 // can be converted to unsigned int if unsigned int can represent all the
5731 // values of the bit-field. If the bit-field is larger yet, no integral
5732 // promotion applies to it.
5733 // C11 6.3.1.1/2:
5734 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5735 // If an int can represent all values of the original type (as restricted by
5736 // the width, for a bit-field), the value is converted to an int; otherwise,
5737 // it is converted to an unsigned int.
5738 //
5739 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5740 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005741 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5742 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005743 if (BitWidth < IntSize)
5744 return IntTy;
5745
5746 if (BitWidth == IntSize)
5747 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5748
Richard Smithaadb2542018-06-28 21:17:55 +00005749 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005750 // like the base type. GCC has some weird bugs in this area that we
5751 // deliberately do not follow (GCC follows a pre-standard resolution to
5752 // C's DR315 which treats bit-width as being part of the type, and this leaks
5753 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005754 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005755}
5756
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005757/// getPromotedIntegerType - Returns the type that Promotable will
5758/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5759/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005760QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005761 assert(!Promotable.isNull());
5762 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005763 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005764 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005765
Eugene Zelenko7855e772018-04-03 00:11:50 +00005766 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005767 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5768 // (3.9.1) can be converted to a prvalue of the first of the following
5769 // types that can represent all the values of its underlying type:
5770 // int, unsigned int, long int, unsigned long int, long long int, or
5771 // unsigned long long int [...]
5772 // FIXME: Is there some better way to compute this?
5773 if (BT->getKind() == BuiltinType::WChar_S ||
5774 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005775 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005776 BT->getKind() == BuiltinType::Char16 ||
5777 BT->getKind() == BuiltinType::Char32) {
5778 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5779 uint64_t FromSize = getTypeSize(BT);
5780 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5781 LongLongTy, UnsignedLongLongTy };
5782 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5783 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5784 if (FromSize < ToSize ||
5785 (FromSize == ToSize &&
5786 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5787 return PromoteTypes[Idx];
5788 }
5789 llvm_unreachable("char type should fit into long long");
5790 }
5791 }
5792
5793 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005794 if (Promotable->isSignedIntegerType())
5795 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005796 uint64_t PromotableSize = getIntWidth(Promotable);
5797 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005798 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5799 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5800}
5801
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005802/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005803/// type and returns its ownership.
5804Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5805 while (!T.isNull()) {
5806 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5807 return T.getObjCLifetime();
5808 if (T->isArrayType())
5809 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005810 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005811 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005812 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005813 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005814 else
5815 break;
5816 }
5817
5818 return Qualifiers::OCL_None;
5819}
5820
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005821static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5822 // Incomplete enum types are not treated as integer types.
5823 // FIXME: In C++, enum types are never integer types.
5824 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5825 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005826 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005827}
5828
Mike Stump11289f42009-09-09 15:08:12 +00005829/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005830/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005831/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005832int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005833 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5834 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005835
5836 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005837 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005838 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005839 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005840 RHSC = getIntegerTypeForEnum(ET);
5841
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005842 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005843
Chris Lattner76a00cf2008-04-06 22:59:24 +00005844 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5845 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005846
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005847 unsigned LHSRank = getIntegerRank(LHSC);
5848 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005849
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005850 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5851 if (LHSRank == RHSRank) return 0;
5852 return LHSRank > RHSRank ? 1 : -1;
5853 }
Mike Stump11289f42009-09-09 15:08:12 +00005854
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005855 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5856 if (LHSUnsigned) {
5857 // If the unsigned [LHS] type is larger, return it.
5858 if (LHSRank >= RHSRank)
5859 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005860
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005861 // If the signed type can represent all values of the unsigned type, it
5862 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005863 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005864 return -1;
5865 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005866
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005867 // If the unsigned [RHS] type is larger, return it.
5868 if (RHSRank >= LHSRank)
5869 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005870
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005871 // If the signed type can represent all values of the unsigned type, it
5872 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005873 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005874 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005875}
Anders Carlsson98f07902007-08-17 05:31:46 +00005876
Ben Langmuirf5416742016-02-04 00:55:24 +00005877TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005878 if (CFConstantStringTypeDecl)
5879 return CFConstantStringTypeDecl;
Anders Carlsson6d417272009-11-14 21:45:58 +00005880
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005881 assert(!CFConstantStringTagDecl &&
5882 "tag and typedef should be initialized together");
5883 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5884 CFConstantStringTagDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00005885
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005886 struct {
5887 QualType Type;
5888 const char *Name;
5889 } Fields[5];
5890 unsigned Count = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005891
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005892 /// Objective-C ABI
5893 ///
5894 /// typedef struct __NSConstantString_tag {
Saleem Abdulrasool1f6c41f2018-10-27 06:12:52 +00005895 /// const int *isa;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005896 /// int flags;
5897 /// const char *str;
5898 /// long length;
5899 /// } __NSConstantString;
5900 ///
5901 /// Swift ABI (4.1, 4.2)
5902 ///
5903 /// typedef struct __NSConstantString_tag {
5904 /// uintptr_t _cfisa;
5905 /// uintptr_t _swift_rc;
5906 /// _Atomic(uint64_t) _cfinfoa;
5907 /// const char *_ptr;
5908 /// uint32_t _length;
5909 /// } __NSConstantString;
5910 ///
5911 /// Swift ABI (5.0)
5912 ///
5913 /// typedef struct __NSConstantString_tag {
5914 /// uintptr_t _cfisa;
5915 /// uintptr_t _swift_rc;
5916 /// _Atomic(uint64_t) _cfinfoa;
5917 /// const char *_ptr;
5918 /// uintptr_t _length;
5919 /// } __NSConstantString;
5920
5921 const auto CFRuntime = getLangOpts().CFRuntime;
5922 if (static_cast<unsigned>(CFRuntime) <
5923 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
5924 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
5925 Fields[Count++] = { IntTy, "flags" };
5926 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
5927 Fields[Count++] = { LongTy, "length" };
5928 } else {
5929 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
5930 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
5931 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
5932 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
5933 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5934 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5935 Fields[Count++] = { IntTy, "_ptr" };
5936 else
5937 Fields[Count++] = { getUIntPtrType(), "_ptr" };
5938 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005939
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005940 // Create fields
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005941 for (unsigned i = 0; i < Count; ++i) {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005942 FieldDecl *Field =
5943 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005944 SourceLocation(), &Idents.get(Fields[i].Name),
5945 Fields[i].Type, /*TInfo=*/nullptr,
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005946 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5947 Field->setAccess(AS_public);
5948 CFConstantStringTagDecl->addDecl(Field);
Anders Carlsson98f07902007-08-17 05:31:46 +00005949 }
Mike Stump11289f42009-09-09 15:08:12 +00005950
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005951 CFConstantStringTagDecl->completeDefinition();
5952 // This type is designed to be compatible with NSConstantString, but cannot
5953 // use the same name, since NSConstantString is an interface.
5954 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5955 CFConstantStringTypeDecl =
5956 buildImplicitTypedef(tagType, "__NSConstantString");
5957
Quentin Colombet043406b2016-02-03 22:41:00 +00005958 return CFConstantStringTypeDecl;
5959}
5960
Ben Langmuirf5416742016-02-04 00:55:24 +00005961RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5962 if (!CFConstantStringTagDecl)
5963 getCFConstantStringDecl(); // Build the tag and the typedef.
5964 return CFConstantStringTagDecl;
5965}
5966
Quentin Colombet043406b2016-02-03 22:41:00 +00005967// getCFConstantStringType - Return the type used for constant CFStrings.
5968QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005969 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005970}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005971
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005972QualType ASTContext::getObjCSuperType() const {
5973 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005974 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005975 TUDecl->addDecl(ObjCSuperTypeDecl);
5976 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5977 }
5978 return ObjCSuperType;
5979}
5980
Douglas Gregor512b0772009-04-23 22:29:11 +00005981void ASTContext::setCFConstantStringType(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005982 const auto *TD = T->getAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00005983 assert(TD && "Invalid CFConstantStringType");
5984 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005985 const auto *TagType =
Ben Langmuirf5416742016-02-04 00:55:24 +00005986 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5987 assert(TagType && "Invalid CFConstantStringType");
5988 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005989}
5990
Jay Foad39c79802011-01-12 09:06:06 +00005991QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005992 if (BlockDescriptorType)
5993 return getTagDeclType(BlockDescriptorType);
5994
Alp Toker2dea15b2013-12-17 01:22:38 +00005995 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005996 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005997 RD = buildImplicitRecord("__block_descriptor");
5998 RD->startDefinition();
5999
Mike Stumpd0153282009-10-20 02:12:22 +00006000 QualType FieldTypes[] = {
6001 UnsignedLongTy,
6002 UnsignedLongTy,
6003 };
6004
Craig Topperd6d31ac2013-07-15 08:24:27 +00006005 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00006006 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006007 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00006008 };
6009
6010 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006011 FieldDecl *Field = FieldDecl::Create(
6012 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006013 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6014 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006015 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006016 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00006017 }
6018
Alp Toker2dea15b2013-12-17 01:22:38 +00006019 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00006020
Alp Toker2dea15b2013-12-17 01:22:38 +00006021 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00006022
6023 return getTagDeclType(BlockDescriptorType);
6024}
6025
Jay Foad39c79802011-01-12 09:06:06 +00006026QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006027 if (BlockDescriptorExtendedType)
6028 return getTagDeclType(BlockDescriptorExtendedType);
6029
Alp Toker2dea15b2013-12-17 01:22:38 +00006030 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006031 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00006032 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6033 RD->startDefinition();
6034
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006035 QualType FieldTypes[] = {
6036 UnsignedLongTy,
6037 UnsignedLongTy,
6038 getPointerType(VoidPtrTy),
6039 getPointerType(VoidPtrTy)
6040 };
6041
Craig Topperd6d31ac2013-07-15 08:24:27 +00006042 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006043 "reserved",
6044 "Size",
6045 "CopyFuncPtr",
6046 "DestroyFuncPtr"
6047 };
6048
6049 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006050 FieldDecl *Field = FieldDecl::Create(
6051 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006052 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6053 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00006054 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006055 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006056 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006057 }
6058
Alp Toker2dea15b2013-12-17 01:22:38 +00006059 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006060
Alp Toker2dea15b2013-12-17 01:22:38 +00006061 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006062 return getTagDeclType(BlockDescriptorExtendedType);
6063}
6064
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006065TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006066 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006067
6068 if (!BT) {
6069 if (isa<PipeType>(T))
6070 return TargetInfo::OCLTK_Pipe;
6071
6072 return TargetInfo::OCLTK_Default;
6073 }
6074
6075 switch (BT->getKind()) {
6076#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6077 case BuiltinType::Id: \
6078 return TargetInfo::OCLTK_Image;
6079#include "clang/Basic/OpenCLImageTypes.def"
6080
6081 case BuiltinType::OCLClkEvent:
6082 return TargetInfo::OCLTK_ClkEvent;
6083
6084 case BuiltinType::OCLEvent:
6085 return TargetInfo::OCLTK_Event;
6086
6087 case BuiltinType::OCLQueue:
6088 return TargetInfo::OCLTK_Queue;
6089
6090 case BuiltinType::OCLReserveID:
6091 return TargetInfo::OCLTK_ReserveID;
6092
6093 case BuiltinType::OCLSampler:
6094 return TargetInfo::OCLTK_Sampler;
6095
6096 default:
6097 return TargetInfo::OCLTK_Default;
6098 }
6099}
6100
6101LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6102 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6103}
6104
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006105/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6106/// requires copy/dispose. Note that this must match the logic
6107/// in buildByrefHelpers.
6108bool ASTContext::BlockRequiresCopying(QualType Ty,
6109 const VarDecl *D) {
6110 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00006111 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006112 if (!copyExpr && record->hasTrivialDestructor()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006113
Mike Stump94967902009-10-21 18:16:27 +00006114 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00006115 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006116
Akira Hatanaka7275da02018-02-28 07:15:55 +00006117 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6118 // move or destroy.
6119 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6120 return true;
6121
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006122 if (!Ty->isObjCRetainableType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006123
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006124 Qualifiers qs = Ty.getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00006125
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006126 // If we have lifetime, that dominates.
6127 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006128 switch (lifetime) {
6129 case Qualifiers::OCL_None: llvm_unreachable("impossible");
Fangrui Song6907ce22018-07-30 19:24:48 +00006130
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006131 // These are just bits as far as the runtime is concerned.
6132 case Qualifiers::OCL_ExplicitNone:
6133 case Qualifiers::OCL_Autoreleasing:
6134 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00006135
6136 // These cases should have been taken care of when checking the type's
6137 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006138 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006139 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00006140 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006141 }
6142 llvm_unreachable("fell out of lifetime switch!");
6143 }
6144 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6145 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00006146}
6147
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006148bool ASTContext::getByrefLifetime(QualType Ty,
6149 Qualifiers::ObjCLifetime &LifeTime,
6150 bool &HasByrefExtendedLayout) const {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00006151 if (!getLangOpts().ObjC ||
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006152 getLangOpts().getGC() != LangOptions::NonGC)
6153 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006154
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006155 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00006156 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006157 HasByrefExtendedLayout = true;
6158 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006159 } else if ((LifeTime = Ty.getObjCLifetime())) {
6160 // Honor the ARC qualifiers.
6161 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6162 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006163 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00006164 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006165 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006166 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006167 return true;
6168}
6169
Douglas Gregorbab8a962011-09-08 01:46:34 +00006170TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6171 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00006172 ObjCInstanceTypeDecl =
6173 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00006174 return ObjCInstanceTypeDecl;
6175}
6176
Anders Carlsson18acd442007-10-29 06:33:42 +00006177// This returns true if a type has been typedefed to BOOL:
6178// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00006179static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006180 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00006181 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6182 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00006183
Anders Carlssond8499822007-10-29 05:01:08 +00006184 return false;
6185}
6186
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006187/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006188/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00006189CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00006190 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6191 return CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00006192
Ken Dyck40775002010-01-11 17:06:35 +00006193 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00006194
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006195 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00006196 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00006197 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006198 // Treat arrays as pointers, since that's how they're passed in.
6199 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00006200 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00006201 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00006202}
6203
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006204bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00006205 return getTargetInfo().getCXXABI().isMicrosoft() &&
6206 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00006207 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00006208 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006209}
6210
Richard Smithd9b90092016-07-02 01:32:16 +00006211ASTContext::InlineVariableDefinitionKind
6212ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6213 if (!VD->isInline())
6214 return InlineVariableDefinitionKind::None;
6215
6216 // In almost all cases, it's a weak definition.
6217 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00006218 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00006219 return InlineVariableDefinitionKind::Weak;
6220
6221 // If there's a file-context declaration in this translation unit, it's a
6222 // non-discardable definition.
6223 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00006224 if (D->getLexicalDeclContext()->isFileContext() &&
6225 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00006226 return InlineVariableDefinitionKind::Strong;
6227
6228 // If we've not seen one yet, we don't know.
6229 return InlineVariableDefinitionKind::WeakUnknown;
6230}
6231
Eugene Zelenko7855e772018-04-03 00:11:50 +00006232static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00006233 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006234}
6235
John McCall351762c2011-02-07 10:33:21 +00006236/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00006237/// declaration.
John McCall351762c2011-02-07 10:33:21 +00006238std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6239 std::string S;
6240
David Chisnall950a9512009-11-17 19:33:30 +00006241 const BlockDecl *Decl = Expr->getBlockDecl();
6242 QualType BlockTy =
6243 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
6244 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006245 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00006246 getObjCEncodingForMethodParameter(
6247 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
6248 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006249 else
Alp Toker314cc812014-01-25 16:55:45 +00006250 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00006251 // Compute size of all parameters.
6252 // Start with computing size of a pointer in number of bytes.
6253 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006254 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6255 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006256 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00006257 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006258 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00006259 if (sz.isZero())
6260 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006261 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00006262 ParmOffset += sz;
6263 }
6264 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00006265 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00006266 // Block pointer and offset.
6267 S += "@?0";
Fangrui Song6907ce22018-07-30 19:24:48 +00006268
David Chisnall950a9512009-11-17 19:33:30 +00006269 // Argument types.
6270 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006271 for (auto PVDecl : Decl->parameters()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006272 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006273 if (const auto *AT =
6274 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00006275 // Use array's original type only if it has known number of
6276 // elements.
6277 if (!isa<ConstantArrayType>(AT))
6278 PType = PVDecl->getType();
6279 } else if (PType->isFunctionType())
6280 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006281 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006282 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6283 S, true /*Extended*/);
6284 else
6285 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006286 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006287 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006288 }
John McCall351762c2011-02-07 10:33:21 +00006289
6290 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006291}
6292
John McCall843dfcc2016-11-29 21:57:00 +00006293std::string
6294ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6295 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006296 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006297 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006298 CharUnits ParmOffset;
6299 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006300 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006301 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006302 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006303 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006304 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006305
6306 assert(sz.isPositive() &&
John McCall843dfcc2016-11-29 21:57:00 +00006307 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006308 ParmOffset += sz;
6309 }
6310 S += charUnitsToString(ParmOffset);
6311 ParmOffset = CharUnits::Zero();
6312
6313 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006314 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006315 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006316 if (const auto *AT =
6317 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006318 // Use array's original type only if it has known number of
6319 // elements.
6320 if (!isa<ConstantArrayType>(AT))
6321 PType = PVDecl->getType();
6322 } else if (PType->isFunctionType())
6323 PType = PVDecl->getType();
6324 getObjCEncodingForType(PType, S);
6325 S += charUnitsToString(ParmOffset);
6326 ParmOffset += getObjCEncodingTypeSize(PType);
6327 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006328
John McCall843dfcc2016-11-29 21:57:00 +00006329 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006330}
6331
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006332/// getObjCEncodingForMethodParameter - Return the encoded type for a single
Fangrui Song6907ce22018-07-30 19:24:48 +00006333/// method parameter or return type. If Extended, include class names and
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006334/// block object types.
6335void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6336 QualType T, std::string& S,
6337 bool Extended) const {
6338 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6339 getObjCEncodingForTypeQualifier(QT, S);
6340 // Encode parameter type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006341 ObjCEncOptions Options = ObjCEncOptions()
6342 .setExpandPointedToStructures()
6343 .setExpandStructures()
6344 .setIsOutermostType();
6345 if (Extended)
6346 Options.setEncodeBlockParameters().setEncodeClassNames();
6347 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006348}
6349
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006350/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006351/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006352std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6353 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006354 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006355 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006356 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006357 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6358 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006359 // Compute size of all parameters.
6360 // Start with computing size of a pointer in number of bytes.
6361 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006362 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006363 // The first two arguments (self and _cmd) are pointers; account for
6364 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006365 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006366 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006367 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006368 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006369 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006370 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006371 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006372
6373 assert(sz.isPositive() &&
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006374 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006375 ParmOffset += sz;
6376 }
Ken Dyck40775002010-01-11 17:06:35 +00006377 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006378 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006379 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006380
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006381 // Argument types.
6382 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006383 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006384 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006385 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006386 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006387 if (const auto *AT =
6388 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006389 // Use array's original type only if it has known number of
6390 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006391 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006392 PType = PVDecl->getType();
6393 } else if (PType->isFunctionType())
6394 PType = PVDecl->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00006395 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006396 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006397 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006398 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006399 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006400
John McCall843dfcc2016-11-29 21:57:00 +00006401 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006402}
6403
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006404ObjCPropertyImplDecl *
6405ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6406 const ObjCPropertyDecl *PD,
6407 const Decl *Container) const {
6408 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006409 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006410 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006411 for (auto *PID : CID->property_impls())
6412 if (PID->getPropertyDecl() == PD)
6413 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006414 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006415 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006416 for (auto *PID : OID->property_impls())
6417 if (PID->getPropertyDecl() == PD)
6418 return PID;
6419 }
6420 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006421}
6422
Daniel Dunbar4932b362008-08-28 04:38:10 +00006423/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006424/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006425/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6426/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006427/// Property attributes are stored as a comma-delimited C string. The simple
6428/// attributes readonly and bycopy are encoded as single characters. The
6429/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6430/// encoded as single characters, followed by an identifier. Property types
6431/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006432/// these attributes are defined by the following enumeration:
6433/// @code
6434/// enum PropertyAttributes {
6435/// kPropertyReadOnly = 'R', // property is read-only.
6436/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6437/// kPropertyByref = '&', // property is a reference to the value last assigned
6438/// kPropertyDynamic = 'D', // property is dynamic
6439/// kPropertyGetter = 'G', // followed by getter selector name
6440/// kPropertySetter = 'S', // followed by setter selector name
6441/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006442/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006443/// kPropertyWeak = 'W' // 'weak' property
6444/// kPropertyStrong = 'P' // property GC'able
6445/// kPropertyNonAtomic = 'N' // property non-atomic
6446/// };
6447/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006448std::string
6449ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6450 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006451 // Collect information from the property implementation decl(s).
6452 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006453 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006454
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006455 if (ObjCPropertyImplDecl *PropertyImpDecl =
6456 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6457 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6458 Dynamic = true;
6459 else
6460 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006461 }
6462
6463 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006464 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006465
6466 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006467 // GCC has some special rules regarding encoding of properties which
6468 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006469 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006470
6471 if (PD->isReadOnly()) {
6472 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006473 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6474 S += ",C";
6475 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6476 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006477 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6478 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006479 } else {
6480 switch (PD->getSetterKind()) {
6481 case ObjCPropertyDecl::Assign: break;
6482 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006483 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006484 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006485 }
6486 }
6487
6488 // It really isn't clear at all what this means, since properties
6489 // are "dynamic by default".
6490 if (Dynamic)
6491 S += ",D";
6492
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006493 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6494 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006495
Daniel Dunbar4932b362008-08-28 04:38:10 +00006496 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6497 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006498 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006499 }
6500
6501 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6502 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006503 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006504 }
6505
6506 if (SynthesizePID) {
6507 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6508 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006509 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006510 }
6511
6512 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006513 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006514}
6515
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006516/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006517/// Another legacy compatibility encoding: 32-bit longs are encoded as
6518/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006519/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006520void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006521 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006522 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006523 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006524 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006525 else
Jay Foad39c79802011-01-12 09:06:06 +00006526 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006527 PointeeTy = IntTy;
6528 }
6529 }
6530}
6531
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006532void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006533 const FieldDecl *Field,
6534 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006535 // We follow the behavior of gcc, expanding structures which are
6536 // directly pointed to, and expanding embedded structures. Note that
6537 // these rules are sufficient to prevent recursive encoding of the
6538 // same type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006539 getObjCEncodingForTypeImpl(T, S,
6540 ObjCEncOptions()
6541 .setExpandPointedToStructures()
6542 .setExpandStructures()
6543 .setIsOutermostType(),
6544 Field, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006545}
6546
Joe Groff98ac7d22014-07-07 22:25:15 +00006547void ASTContext::getObjCEncodingForPropertyType(QualType T,
6548 std::string& S) const {
6549 // Encode result type.
6550 // GCC has some special rules regarding encoding of properties which
6551 // closely resembles encoding of ivars.
Nico Weber2e9591c2019-05-14 12:32:37 +00006552 getObjCEncodingForTypeImpl(T, S,
6553 ObjCEncOptions()
6554 .setExpandPointedToStructures()
6555 .setExpandStructures()
6556 .setIsOutermostType()
6557 .setEncodingProperty(),
6558 /*Field=*/nullptr);
Joe Groff98ac7d22014-07-07 22:25:15 +00006559}
6560
John McCall393a78d2012-12-20 02:45:14 +00006561static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6562 BuiltinType::Kind kind) {
6563 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006564 case BuiltinType::Void: return 'v';
6565 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006566 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006567 case BuiltinType::Char_U:
6568 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006569 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006570 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006571 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006572 case BuiltinType::UInt: return 'I';
6573 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006574 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006575 case BuiltinType::UInt128: return 'T';
6576 case BuiltinType::ULongLong: return 'Q';
6577 case BuiltinType::Char_S:
6578 case BuiltinType::SChar: return 'c';
6579 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006580 case BuiltinType::WChar_S:
6581 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006582 case BuiltinType::Int: return 'i';
6583 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006584 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006585 case BuiltinType::LongLong: return 'q';
6586 case BuiltinType::Int128: return 't';
6587 case BuiltinType::Float: return 'f';
6588 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006589 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006590 case BuiltinType::NullPtr: return '*'; // like char*
6591
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006592 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006593 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006594 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006595 case BuiltinType::ShortAccum:
6596 case BuiltinType::Accum:
6597 case BuiltinType::LongAccum:
6598 case BuiltinType::UShortAccum:
6599 case BuiltinType::UAccum:
6600 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006601 case BuiltinType::ShortFract:
6602 case BuiltinType::Fract:
6603 case BuiltinType::LongFract:
6604 case BuiltinType::UShortFract:
6605 case BuiltinType::UFract:
6606 case BuiltinType::ULongFract:
6607 case BuiltinType::SatShortAccum:
6608 case BuiltinType::SatAccum:
6609 case BuiltinType::SatLongAccum:
6610 case BuiltinType::SatUShortAccum:
6611 case BuiltinType::SatUAccum:
6612 case BuiltinType::SatULongAccum:
6613 case BuiltinType::SatShortFract:
6614 case BuiltinType::SatFract:
6615 case BuiltinType::SatLongFract:
6616 case BuiltinType::SatUShortFract:
6617 case BuiltinType::SatUFract:
6618 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006619 // FIXME: potentially need @encodes for these!
6620 return ' ';
6621
6622 case BuiltinType::ObjCId:
6623 case BuiltinType::ObjCClass:
6624 case BuiltinType::ObjCSel:
6625 llvm_unreachable("@encoding ObjC primitive type");
6626
6627 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006628#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6629 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006630#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006631#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6632 case BuiltinType::Id:
6633#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006634 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006635 case BuiltinType::OCLClkEvent:
6636 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006637 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006638 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006639 case BuiltinType::Dependent:
6640#define BUILTIN_TYPE(KIND, ID)
6641#define PLACEHOLDER_TYPE(KIND, ID) \
6642 case BuiltinType::KIND:
6643#include "clang/AST/BuiltinTypes.def"
6644 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006645 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006646 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006647}
6648
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006649static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6650 EnumDecl *Enum = ET->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00006651
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006652 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6653 if (!Enum->isFixed())
6654 return 'i';
Fangrui Song6907ce22018-07-30 19:24:48 +00006655
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006656 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006657 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006658 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006659}
6660
Jay Foad39c79802011-01-12 09:06:06 +00006661static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006662 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006663 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006664 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006665 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6666 // The GNU runtime requires more information; bitfields are encoded as b,
6667 // then the offset (in bits) of the first element, then the type of the
6668 // bitfield, then the size in bits. For example, in this structure:
6669 //
6670 // struct
6671 // {
6672 // int integer;
6673 // int flags:2;
6674 // };
6675 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6676 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6677 // information is not especially sensible, but we're stuck with it for
6678 // compatibility with GCC, although providing it breaks anything that
6679 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006680 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006681 uint64_t Offset;
6682
6683 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6684 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6685 IVD);
6686 } else {
6687 const RecordDecl *RD = FD->getParent();
6688 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6689 Offset = RL.getFieldOffset(FD->getFieldIndex());
6690 }
6691
6692 S += llvm::utostr(Offset);
6693
Eugene Zelenko7855e772018-04-03 00:11:50 +00006694 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006695 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006696 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006697 const auto *BT = T->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006698 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6699 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006700 }
Richard Smithcaf33902011-10-10 18:28:20 +00006701 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006702}
6703
Daniel Dunbar07d07852009-10-18 21:17:35 +00006704// FIXME: Use SmallString for accumulating string.
Nico Weber2e9591c2019-05-14 12:32:37 +00006705void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
6706 const ObjCEncOptions Options,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006707 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006708 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006709 CanQualType CT = getCanonicalType(T);
6710 switch (CT->getTypeClass()) {
6711 case Type::Builtin:
6712 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006713 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006714 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006715 if (const auto *BT = dyn_cast<BuiltinType>(CT))
John McCall393a78d2012-12-20 02:45:14 +00006716 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6717 else
6718 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006719 return;
Mike Stump11289f42009-09-09 15:08:12 +00006720
John McCall393a78d2012-12-20 02:45:14 +00006721 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006722 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006723 S += 'j';
Nico Weber2e9591c2019-05-14 12:32:37 +00006724 getObjCEncodingForTypeImpl(CT->getElementType(), S, ObjCEncOptions(),
6725 /*Field=*/nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006726 return;
6727 }
John McCall393a78d2012-12-20 02:45:14 +00006728
6729 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006730 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006731 S += 'A';
Nico Weber2e9591c2019-05-14 12:32:37 +00006732 getObjCEncodingForTypeImpl(AT->getValueType(), S, ObjCEncOptions(),
6733 /*Field=*/nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006734 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006735 }
John McCall393a78d2012-12-20 02:45:14 +00006736
6737 // encoding for pointer or reference types.
6738 case Type::Pointer:
6739 case Type::LValueReference:
6740 case Type::RValueReference: {
6741 QualType PointeeTy;
6742 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006743 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006744 if (PT->isObjCSelType()) {
6745 S += ':';
6746 return;
6747 }
6748 PointeeTy = PT->getPointeeType();
6749 } else {
6750 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6751 }
6752
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006753 bool isReadOnly = false;
6754 // For historical/compatibility reasons, the read-only qualifier of the
6755 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6756 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006757 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006758 if (isa<TypedefType>(T.getTypePtr())) {
Nico Weber2e9591c2019-05-14 12:32:37 +00006759 if (Options.IsOutermostType() && T.isConstQualified()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006760 isReadOnly = true;
6761 S += 'r';
6762 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006763 } else if (Options.IsOutermostType()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006764 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006765 while (P->getAs<PointerType>())
6766 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006767 if (P.isConstQualified()) {
6768 isReadOnly = true;
6769 S += 'r';
6770 }
6771 }
6772 if (isReadOnly) {
6773 // Another legacy compatibility encoding. Some ObjC qualifier and type
6774 // combinations need to be rearranged.
6775 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006776 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006777 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006778 }
Mike Stump11289f42009-09-09 15:08:12 +00006779
Anders Carlssond8499822007-10-29 05:01:08 +00006780 if (PointeeTy->isCharType()) {
6781 // char pointer types should be encoded as '*' unless it is a
6782 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006783 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006784 S += '*';
6785 return;
6786 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006787 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006788 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6789 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6790 S += '#';
6791 return;
6792 }
6793 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6794 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6795 S += '@';
6796 return;
6797 }
6798 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006799 }
Anders Carlssond8499822007-10-29 05:01:08 +00006800 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006801 getLegacyIntegralTypeEncoding(PointeeTy);
6802
Nico Weber2e9591c2019-05-14 12:32:37 +00006803 ObjCEncOptions NewOptions;
6804 if (Options.ExpandPointedToStructures())
6805 NewOptions.setExpandStructures();
6806 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
6807 /*Field=*/nullptr, NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006808 return;
6809 }
John McCall393a78d2012-12-20 02:45:14 +00006810
6811 case Type::ConstantArray:
6812 case Type::IncompleteArray:
6813 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006814 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006815
Nico Weber2e9591c2019-05-14 12:32:37 +00006816 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006817 // Incomplete arrays are encoded as a pointer to the array element.
6818 S += '^';
6819
Nico Weber2e9591c2019-05-14 12:32:37 +00006820 getObjCEncodingForTypeImpl(
6821 AT->getElementType(), S,
6822 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006823 } else {
6824 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006825
Eugene Zelenko7855e772018-04-03 00:11:50 +00006826 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006827 S += llvm::utostr(CAT->getSize().getZExtValue());
6828 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006829 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006830 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6831 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006832 S += '0';
6833 }
Mike Stump11289f42009-09-09 15:08:12 +00006834
Nico Weberdf129332019-05-10 13:56:56 +00006835 getObjCEncodingForTypeImpl(
6836 AT->getElementType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006837 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
6838 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006839 S += ']';
6840 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006841 return;
6842 }
Mike Stump11289f42009-09-09 15:08:12 +00006843
John McCall393a78d2012-12-20 02:45:14 +00006844 case Type::FunctionNoProto:
6845 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006846 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006847 return;
Mike Stump11289f42009-09-09 15:08:12 +00006848
John McCall393a78d2012-12-20 02:45:14 +00006849 case Type::Record: {
6850 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006851 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006852 // Anonymous structures print as '?'
6853 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6854 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006855 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006856 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006857 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006858 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6859 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006860 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006861 } else {
6862 S += '?';
6863 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006864 if (Options.ExpandStructures()) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006865 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006866 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006867 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006868 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006869 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006870 if (FD) {
6871 S += '"';
6872 S += Field->getNameAsString();
6873 S += '"';
6874 }
Mike Stump11289f42009-09-09 15:08:12 +00006875
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006876 // Special case bit-fields.
6877 if (Field->isBitField()) {
Nico Weberdf129332019-05-10 13:56:56 +00006878 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006879 ObjCEncOptions().setExpandStructures(),
6880 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006881 } else {
6882 QualType qt = Field->getType();
6883 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00006884 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00006885 qt, S,
6886 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
6887 NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006888 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006889 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006890 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006891 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006892 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006893 return;
6894 }
Mike Stump11289f42009-09-09 15:08:12 +00006895
John McCall393a78d2012-12-20 02:45:14 +00006896 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006897 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006898 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Nico Weber2e9591c2019-05-14 12:32:37 +00006899 if (Options.EncodeBlockParameters()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006900 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00006901
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006902 S += '<';
6903 // Block return type
Nico Weber2e9591c2019-05-14 12:32:37 +00006904 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
6905 Options.forComponentType(), FD, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006906 // Block self
6907 S += "@?";
6908 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00006909 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006910 for (const auto &I : FPT->param_types())
Nico Weber2e9591c2019-05-14 12:32:37 +00006911 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
6912 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006913 }
6914 S += '>';
6915 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006916 return;
6917 }
Mike Stump11289f42009-09-09 15:08:12 +00006918
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006919 case Type::ObjCObject: {
6920 // hack to match legacy encoding of *id and *Class
6921 QualType Ty = getObjCObjectPointerType(CT);
6922 if (Ty->isObjCIdType()) {
6923 S += "{objc_object=}";
6924 return;
6925 }
6926 else if (Ty->isObjCClassType()) {
6927 S += "{objc_class=}";
6928 return;
6929 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006930 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006931 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006932 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006933
John McCall393a78d2012-12-20 02:45:14 +00006934 case Type::ObjCInterface: {
6935 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006936 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006937 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006938 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006939 S += OI->getObjCRuntimeNameAsString();
Nico Weber2e9591c2019-05-14 12:32:37 +00006940 if (Options.ExpandStructures()) {
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006941 S += '=';
6942 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6943 DeepCollectObjCIvars(OI, true, Ivars);
6944 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006945 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006946 if (Field->isBitField())
Nico Weberdf129332019-05-10 13:56:56 +00006947 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006948 ObjCEncOptions().setExpandStructures(),
6949 Field);
Akira Hatanakaf3c89b12019-05-29 21:23:30 +00006950 else
6951 getObjCEncodingForTypeImpl(Field->getType(), S,
6952 ObjCEncOptions().setExpandStructures(), FD,
Nico Weber2e9591c2019-05-14 12:32:37 +00006953 NotEncodedT);
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006954 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006955 }
6956 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006957 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006958 }
Mike Stump11289f42009-09-09 15:08:12 +00006959
John McCall393a78d2012-12-20 02:45:14 +00006960 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006961 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006962 if (OPT->isObjCIdType()) {
6963 S += '@';
6964 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006965 }
Mike Stump11289f42009-09-09 15:08:12 +00006966
Steve Narofff0c86112009-10-28 22:03:49 +00006967 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6968 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
Nico Weberdf129332019-05-10 13:56:56 +00006969 // Since this is a binary compatibility issue, need to consult with
6970 // runtime folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006971 S += '#';
6972 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006973 }
Mike Stump11289f42009-09-09 15:08:12 +00006974
Chris Lattnere7cabb92009-07-13 00:10:46 +00006975 if (OPT->isObjCQualifiedIdType()) {
Nico Weber2e9591c2019-05-14 12:32:37 +00006976 getObjCEncodingForTypeImpl(
6977 getObjCIdType(), S,
6978 Options.keepingOnly(ObjCEncOptions()
6979 .setExpandPointedToStructures()
6980 .setExpandStructures()),
6981 FD);
6982 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006983 // Note that we do extended encoding of protocol qualifer list
6984 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006985 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006986 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006987 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006988 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006989 S += '>';
6990 }
6991 S += '"';
6992 }
6993 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006994 }
Mike Stump11289f42009-09-09 15:08:12 +00006995
Chris Lattnere7cabb92009-07-13 00:10:46 +00006996 S += '@';
Fangrui Song6907ce22018-07-30 19:24:48 +00006997 if (OPT->getInterfaceDecl() &&
Nico Weber2e9591c2019-05-14 12:32:37 +00006998 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006999 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007000 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00007001 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007002 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007003 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00007004 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00007005 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007006 S += '"';
7007 }
7008 return;
7009 }
Mike Stump11289f42009-09-09 15:08:12 +00007010
John McCalla9e6e8d2010-05-17 23:56:34 +00007011 // gcc just blithely ignores member pointers.
Nico Weber2e9591c2019-05-14 12:32:37 +00007012 // FIXME: we should do better than that. 'M' is available.
John McCall393a78d2012-12-20 02:45:14 +00007013 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007014 // This matches gcc's encoding, even though technically it is insufficient.
7015 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00007016 case Type::Vector:
7017 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007018 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007019 if (NotEncodedT)
7020 *NotEncodedT = T;
7021 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00007022
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007023 // We could see an undeduced auto type here during error recovery.
7024 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00007025 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007026 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00007027 return;
7028
Xiuli Pan9c14e282016-01-09 12:53:17 +00007029 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00007030#define ABSTRACT_TYPE(KIND, BASE)
7031#define TYPE(KIND, BASE)
7032#define DEPENDENT_TYPE(KIND, BASE) \
7033 case Type::KIND:
7034#define NON_CANONICAL_TYPE(KIND, BASE) \
7035 case Type::KIND:
7036#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7037 case Type::KIND:
7038#include "clang/AST/TypeNodes.def"
7039 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00007040 }
John McCall393a78d2012-12-20 02:45:14 +00007041 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00007042}
7043
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007044void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7045 std::string &S,
7046 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007047 bool includeVBases,
7048 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007049 assert(RDecl && "Expected non-null RecordDecl");
7050 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00007051 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007052 return;
7053
Eugene Zelenko7855e772018-04-03 00:11:50 +00007054 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007055 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7056 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7057
7058 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00007059 for (const auto &BI : CXXRec->bases()) {
7060 if (!BI.isVirtual()) {
7061 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007062 if (base->isEmpty())
7063 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007064 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007065 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7066 std::make_pair(offs, base));
7067 }
7068 }
7069 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007070
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007071 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00007072 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007073 uint64_t offs = layout.getFieldOffset(i);
7074 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00007075 std::make_pair(offs, Field));
7076 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007077 }
7078
7079 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00007080 for (const auto &BI : CXXRec->vbases()) {
7081 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007082 if (base->isEmpty())
7083 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007084 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00007085 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7086 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00007087 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7088 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007089 }
7090 }
7091
7092 CharUnits size;
7093 if (CXXRec) {
7094 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7095 } else {
7096 size = layout.getSize();
7097 }
7098
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007099#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007100 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007101#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007102 std::multimap<uint64_t, NamedDecl *>::iterator
7103 CurLayObj = FieldOrBaseOffsets.begin();
7104
Douglas Gregorf5d6c742012-04-27 22:30:01 +00007105 if (CXXRec && CXXRec->isDynamicClass() &&
7106 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007107 if (FD) {
7108 S += "\"_vptr$";
7109 std::string recname = CXXRec->getNameAsString();
7110 if (recname.empty()) recname = "?";
7111 S += recname;
7112 S += '"';
7113 }
7114 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007115#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007116 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007117#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007118 }
7119
7120 if (!RDecl->hasFlexibleArrayMember()) {
7121 // Mark the end of the structure.
7122 uint64_t offs = toBits(size);
7123 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00007124 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007125 }
7126
7127 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007128#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007129 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007130 if (CurOffs < CurLayObj->first) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007131 uint64_t padding = CurLayObj->first - CurOffs;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007132 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7133 // packing/alignment of members is different that normal, in which case
7134 // the encoding will be out-of-sync with the real layout.
7135 // If the runtime switches to just consider the size of types without
7136 // taking into account alignment, we could make padding explicit in the
7137 // encoding (e.g. using arrays of chars). The encoding strings would be
7138 // longer then though.
7139 CurOffs += padding;
7140 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007141#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007142
7143 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00007144 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007145 break; // reached end of structure.
7146
Eugene Zelenko7855e772018-04-03 00:11:50 +00007147 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007148 // We expand the bases without their virtual bases since those are going
7149 // in the initial structure. Note that this differs from gcc which
7150 // expands virtual bases each time one is encountered in the hierarchy,
7151 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007152 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7153 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007154 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007155#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007156 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007157#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007158 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007159 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007160 if (FD) {
7161 S += '"';
7162 S += field->getNameAsString();
7163 S += '"';
7164 }
7165
7166 if (field->isBitField()) {
7167 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007168#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00007169 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007170#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007171 } else {
7172 QualType qt = field->getType();
7173 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00007174 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00007175 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7176 FD, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007177#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007178 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007179#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007180 }
7181 }
7182 }
7183}
7184
Mike Stump11289f42009-09-09 15:08:12 +00007185void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00007186 std::string& S) const {
7187 if (QT & Decl::OBJC_TQ_In)
7188 S += 'n';
7189 if (QT & Decl::OBJC_TQ_Inout)
7190 S += 'N';
7191 if (QT & Decl::OBJC_TQ_Out)
7192 S += 'o';
7193 if (QT & Decl::OBJC_TQ_Bycopy)
7194 S += 'O';
7195 if (QT & Decl::OBJC_TQ_Byref)
7196 S += 'R';
7197 if (QT & Decl::OBJC_TQ_Oneway)
7198 S += 'V';
7199}
7200
Douglas Gregor3ea72692011-08-12 05:46:01 +00007201TypedefDecl *ASTContext::getObjCIdDecl() const {
7202 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007203 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00007204 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007205 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00007206 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00007207 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00007208}
7209
Douglas Gregor52e02802011-08-12 06:17:30 +00007210TypedefDecl *ASTContext::getObjCSelDecl() const {
7211 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007212 QualType T = getPointerType(ObjCBuiltinSelTy);
7213 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00007214 }
7215 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00007216}
7217
Douglas Gregor0a586182011-08-12 05:59:41 +00007218TypedefDecl *ASTContext::getObjCClassDecl() const {
7219 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007220 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00007221 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007222 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00007223 }
Douglas Gregor0a586182011-08-12 05:59:41 +00007224 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00007225}
7226
Douglas Gregord53ae832012-01-17 18:09:05 +00007227ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7228 if (!ObjCProtocolClassDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007229 ObjCProtocolClassDecl
7230 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregord53ae832012-01-17 18:09:05 +00007231 SourceLocation(),
7232 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00007233 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00007234 /*PrevDecl=*/nullptr,
Fangrui Song6907ce22018-07-30 19:24:48 +00007235 SourceLocation(), true);
Douglas Gregord53ae832012-01-17 18:09:05 +00007236 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007237
Douglas Gregord53ae832012-01-17 18:09:05 +00007238 return ObjCProtocolClassDecl;
7239}
7240
Meador Inge5d3fb222012-06-16 03:34:49 +00007241//===----------------------------------------------------------------------===//
7242// __builtin_va_list Construction Functions
7243//===----------------------------------------------------------------------===//
7244
Charles Davisc7d5c942015-09-17 20:55:33 +00007245static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7246 StringRef Name) {
7247 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007248 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00007249 return Context->buildImplicitTypedef(T, Name);
7250}
7251
7252static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7253 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7254}
7255
7256static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7257 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007258}
7259
7260static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7261 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007262 QualType T = Context->getPointerType(Context->VoidTy);
7263 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007264}
7265
Tim Northover9bb857a2013-01-31 12:13:10 +00007266static TypedefDecl *
7267CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007268 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007269 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007270 if (Context->getLangOpts().CPlusPlus) {
7271 // namespace std { struct __va_list {
7272 NamespaceDecl *NS;
7273 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7274 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007275 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007276 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007277 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007278 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007279 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007280 }
7281
7282 VaListTagDecl->startDefinition();
7283
7284 const size_t NumFields = 5;
7285 QualType FieldTypes[NumFields];
7286 const char *FieldNames[NumFields];
7287
7288 // void *__stack;
7289 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7290 FieldNames[0] = "__stack";
7291
7292 // void *__gr_top;
7293 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7294 FieldNames[1] = "__gr_top";
7295
7296 // void *__vr_top;
7297 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7298 FieldNames[2] = "__vr_top";
7299
7300 // int __gr_offs;
7301 FieldTypes[3] = Context->IntTy;
7302 FieldNames[3] = "__gr_offs";
7303
7304 // int __vr_offs;
7305 FieldTypes[4] = Context->IntTy;
7306 FieldNames[4] = "__vr_offs";
7307
7308 // Create fields
7309 for (unsigned i = 0; i < NumFields; ++i) {
7310 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7311 VaListTagDecl,
7312 SourceLocation(),
7313 SourceLocation(),
7314 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007315 FieldTypes[i], /*TInfo=*/nullptr,
7316 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007317 /*Mutable=*/false,
7318 ICIS_NoInit);
7319 Field->setAccess(AS_public);
7320 VaListTagDecl->addDecl(Field);
7321 }
7322 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007323 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007324 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007325
7326 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007327 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007328}
7329
Meador Inge5d3fb222012-06-16 03:34:49 +00007330static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7331 // typedef struct __va_list_tag {
7332 RecordDecl *VaListTagDecl;
7333
Alp Toker2dea15b2013-12-17 01:22:38 +00007334 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007335 VaListTagDecl->startDefinition();
7336
7337 const size_t NumFields = 5;
7338 QualType FieldTypes[NumFields];
7339 const char *FieldNames[NumFields];
7340
7341 // unsigned char gpr;
7342 FieldTypes[0] = Context->UnsignedCharTy;
7343 FieldNames[0] = "gpr";
7344
7345 // unsigned char fpr;
7346 FieldTypes[1] = Context->UnsignedCharTy;
7347 FieldNames[1] = "fpr";
7348
7349 // unsigned short reserved;
7350 FieldTypes[2] = Context->UnsignedShortTy;
7351 FieldNames[2] = "reserved";
7352
7353 // void* overflow_arg_area;
7354 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7355 FieldNames[3] = "overflow_arg_area";
7356
7357 // void* reg_save_area;
7358 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7359 FieldNames[4] = "reg_save_area";
7360
7361 // Create fields
7362 for (unsigned i = 0; i < NumFields; ++i) {
7363 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7364 SourceLocation(),
7365 SourceLocation(),
7366 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007367 FieldTypes[i], /*TInfo=*/nullptr,
7368 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007369 /*Mutable=*/false,
7370 ICIS_NoInit);
7371 Field->setAccess(AS_public);
7372 VaListTagDecl->addDecl(Field);
7373 }
7374 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007375 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007376 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7377
7378 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007379 TypedefDecl *VaListTagTypedefDecl =
7380 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7381
Meador Inge5d3fb222012-06-16 03:34:49 +00007382 QualType VaListTagTypedefType =
7383 Context->getTypedefType(VaListTagTypedefDecl);
7384
7385 // typedef __va_list_tag __builtin_va_list[1];
7386 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7387 QualType VaListTagArrayType
7388 = Context->getConstantArrayType(VaListTagTypedefType,
7389 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007390 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007391}
7392
7393static TypedefDecl *
7394CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007395 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007396 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007397 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007398 VaListTagDecl->startDefinition();
7399
7400 const size_t NumFields = 4;
7401 QualType FieldTypes[NumFields];
7402 const char *FieldNames[NumFields];
7403
7404 // unsigned gp_offset;
7405 FieldTypes[0] = Context->UnsignedIntTy;
7406 FieldNames[0] = "gp_offset";
7407
7408 // unsigned fp_offset;
7409 FieldTypes[1] = Context->UnsignedIntTy;
7410 FieldNames[1] = "fp_offset";
7411
7412 // void* overflow_arg_area;
7413 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7414 FieldNames[2] = "overflow_arg_area";
7415
7416 // void* reg_save_area;
7417 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7418 FieldNames[3] = "reg_save_area";
7419
7420 // Create fields
7421 for (unsigned i = 0; i < NumFields; ++i) {
7422 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7423 VaListTagDecl,
7424 SourceLocation(),
7425 SourceLocation(),
7426 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007427 FieldTypes[i], /*TInfo=*/nullptr,
7428 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007429 /*Mutable=*/false,
7430 ICIS_NoInit);
7431 Field->setAccess(AS_public);
7432 VaListTagDecl->addDecl(Field);
7433 }
7434 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007435 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007436 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7437
Richard Smith9b88a4c2015-07-27 05:40:23 +00007438 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007439
Richard Smith9b88a4c2015-07-27 05:40:23 +00007440 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007441 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007442 QualType VaListTagArrayType =
7443 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007444 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007445}
7446
7447static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7448 // typedef int __builtin_va_list[4];
7449 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007450 QualType IntArrayType =
7451 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007452 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007453}
7454
Logan Chien57086ce2012-10-10 06:56:20 +00007455static TypedefDecl *
7456CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007457 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007458 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007459 if (Context->getLangOpts().CPlusPlus) {
7460 // namespace std { struct __va_list {
7461 NamespaceDecl *NS;
7462 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7463 Context->getTranslationUnitDecl(),
7464 /*Inline*/false, SourceLocation(),
7465 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007466 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007467 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007468 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007469 }
7470
7471 VaListDecl->startDefinition();
7472
7473 // void * __ap;
7474 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7475 VaListDecl,
7476 SourceLocation(),
7477 SourceLocation(),
7478 &Context->Idents.get("__ap"),
7479 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007480 /*TInfo=*/nullptr,
7481 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007482 /*Mutable=*/false,
7483 ICIS_NoInit);
7484 Field->setAccess(AS_public);
7485 VaListDecl->addDecl(Field);
7486
7487 // };
7488 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007489 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007490
7491 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007492 QualType T = Context->getRecordType(VaListDecl);
7493 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007494}
7495
Ulrich Weigand47445072013-05-06 16:26:41 +00007496static TypedefDecl *
7497CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007498 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007499 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007500 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007501 VaListTagDecl->startDefinition();
7502
7503 const size_t NumFields = 4;
7504 QualType FieldTypes[NumFields];
7505 const char *FieldNames[NumFields];
7506
7507 // long __gpr;
7508 FieldTypes[0] = Context->LongTy;
7509 FieldNames[0] = "__gpr";
7510
7511 // long __fpr;
7512 FieldTypes[1] = Context->LongTy;
7513 FieldNames[1] = "__fpr";
7514
7515 // void *__overflow_arg_area;
7516 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7517 FieldNames[2] = "__overflow_arg_area";
7518
7519 // void *__reg_save_area;
7520 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7521 FieldNames[3] = "__reg_save_area";
7522
7523 // Create fields
7524 for (unsigned i = 0; i < NumFields; ++i) {
7525 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7526 VaListTagDecl,
7527 SourceLocation(),
7528 SourceLocation(),
7529 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007530 FieldTypes[i], /*TInfo=*/nullptr,
7531 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007532 /*Mutable=*/false,
7533 ICIS_NoInit);
7534 Field->setAccess(AS_public);
7535 VaListTagDecl->addDecl(Field);
7536 }
7537 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007538 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007539 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007540
Richard Smith9b88a4c2015-07-27 05:40:23 +00007541 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007542
7543 // typedef __va_list_tag __builtin_va_list[1];
7544 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007545 QualType VaListTagArrayType =
7546 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007547
Alp Toker56b5cc92013-12-15 10:36:26 +00007548 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007549}
7550
Meador Inge5d3fb222012-06-16 03:34:49 +00007551static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7552 TargetInfo::BuiltinVaListKind Kind) {
7553 switch (Kind) {
7554 case TargetInfo::CharPtrBuiltinVaList:
7555 return CreateCharPtrBuiltinVaListDecl(Context);
7556 case TargetInfo::VoidPtrBuiltinVaList:
7557 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007558 case TargetInfo::AArch64ABIBuiltinVaList:
7559 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007560 case TargetInfo::PowerABIBuiltinVaList:
7561 return CreatePowerABIBuiltinVaListDecl(Context);
7562 case TargetInfo::X86_64ABIBuiltinVaList:
7563 return CreateX86_64ABIBuiltinVaListDecl(Context);
7564 case TargetInfo::PNaClABIBuiltinVaList:
7565 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007566 case TargetInfo::AAPCSABIBuiltinVaList:
7567 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007568 case TargetInfo::SystemZBuiltinVaList:
7569 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007570 }
7571
7572 llvm_unreachable("Unhandled __builtin_va_list type kind");
7573}
7574
7575TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007576 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007577 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007578 assert(BuiltinVaListDecl->isImplicit());
7579 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007580
7581 return BuiltinVaListDecl;
7582}
7583
Richard Smith9b88a4c2015-07-27 05:40:23 +00007584Decl *ASTContext::getVaListTagDecl() const {
7585 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007586 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007587 if (!VaListTagDecl)
7588 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007589
Richard Smith9b88a4c2015-07-27 05:40:23 +00007590 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007591}
7592
Charles Davisc7d5c942015-09-17 20:55:33 +00007593TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7594 if (!BuiltinMSVaListDecl)
7595 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7596
7597 return BuiltinMSVaListDecl;
7598}
7599
Erich Keane41af9712018-04-16 21:30:08 +00007600bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7601 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7602}
7603
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007604void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007605 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007606 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007607
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007608 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007609}
7610
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007611/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007612/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007613TemplateName
7614ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7615 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007616 unsigned size = End - Begin;
7617 assert(size > 1 && "set is not overloaded!");
7618
7619 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7620 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007621 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007622
7623 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007624 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007625 NamedDecl *D = *I;
7626 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007627 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007628 (isa<UsingShadowDecl>(D) &&
7629 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7630 *Storage++ = D;
7631 }
7632
7633 return TemplateName(OT);
7634}
7635
Richard Smithb23c5e82019-05-09 03:31:27 +00007636/// Retrieve a template name representing an unqualified-id that has been
7637/// assumed to name a template for ADL purposes.
7638TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
7639 auto *OT = new (*this) AssumedTemplateStorage(Name);
7640 return TemplateName(OT);
7641}
7642
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007643/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007644/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007645TemplateName
7646ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7647 bool TemplateKeyword,
7648 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007649 assert(NNS && "Missing nested-name-specifier in qualified template name");
Fangrui Song6907ce22018-07-30 19:24:48 +00007650
Douglas Gregorc42075a2010-02-04 18:10:26 +00007651 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007652 llvm::FoldingSetNodeID ID;
7653 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7654
Craig Topper36250ad2014-05-12 05:36:57 +00007655 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007656 QualifiedTemplateName *QTN =
7657 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7658 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007659 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007660 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007661 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7662 }
7663
7664 return TemplateName(QTN);
7665}
7666
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007667/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007668/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007669TemplateName
7670ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7671 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007672 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007673 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007674
7675 llvm::FoldingSetNodeID ID;
7676 DependentTemplateName::Profile(ID, NNS, Name);
7677
Craig Topper36250ad2014-05-12 05:36:57 +00007678 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007679 DependentTemplateName *QTN =
7680 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7681
7682 if (QTN)
7683 return TemplateName(QTN);
7684
7685 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7686 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007687 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007688 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007689 } else {
7690 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007691 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007692 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007693 DependentTemplateName *CheckQTN =
7694 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7695 assert(!CheckQTN && "Dependent type name canonicalization broken");
7696 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007697 }
7698
7699 DependentTemplateNames.InsertNode(QTN, InsertPos);
7700 return TemplateName(QTN);
7701}
7702
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007703/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007704/// template name such as \c MetaFun::template operator+.
Fangrui Song6907ce22018-07-30 19:24:48 +00007705TemplateName
Douglas Gregor71395fa2009-11-04 00:56:37 +00007706ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007707 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007708 assert((!NNS || NNS->isDependent()) &&
7709 "Nested name specifier must be dependent");
Fangrui Song6907ce22018-07-30 19:24:48 +00007710
Douglas Gregor71395fa2009-11-04 00:56:37 +00007711 llvm::FoldingSetNodeID ID;
7712 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007713
7714 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007715 DependentTemplateName *QTN
7716 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007717
Douglas Gregor71395fa2009-11-04 00:56:37 +00007718 if (QTN)
7719 return TemplateName(QTN);
Fangrui Song6907ce22018-07-30 19:24:48 +00007720
Douglas Gregor71395fa2009-11-04 00:56:37 +00007721 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7722 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007723 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007724 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007725 } else {
7726 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007727 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007728 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007729
Douglas Gregorc42075a2010-02-04 18:10:26 +00007730 DependentTemplateName *CheckQTN
7731 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7732 assert(!CheckQTN && "Dependent template name canonicalization broken");
7733 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007734 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007735
Douglas Gregor71395fa2009-11-04 00:56:37 +00007736 DependentTemplateNames.InsertNode(QTN, InsertPos);
7737 return TemplateName(QTN);
7738}
7739
Fangrui Song6907ce22018-07-30 19:24:48 +00007740TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007741ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7742 TemplateName replacement) const {
7743 llvm::FoldingSetNodeID ID;
7744 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007745
7746 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007747 SubstTemplateTemplateParmStorage *subst
7748 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007749
John McCalld9dfe3a2011-06-30 08:33:18 +00007750 if (!subst) {
7751 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7752 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7753 }
7754
7755 return TemplateName(subst);
7756}
7757
Fangrui Song6907ce22018-07-30 19:24:48 +00007758TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007759ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7760 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007761 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007762 llvm::FoldingSetNodeID ID;
7763 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007764
7765 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007766 SubstTemplateTemplateParmPackStorage *Subst
7767 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007768
Douglas Gregor5590be02011-01-15 06:45:20 +00007769 if (!Subst) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007770 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007771 ArgPack.pack_size(),
7772 ArgPack.pack_begin());
7773 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7774 }
7775
7776 return TemplateName(Subst);
7777}
7778
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007779/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007780/// TargetInfo, produce the corresponding type. The unsigned @p Type
7781/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007782CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007783 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007784 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007785 case TargetInfo::SignedChar: return SignedCharTy;
7786 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007787 case TargetInfo::SignedShort: return ShortTy;
7788 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7789 case TargetInfo::SignedInt: return IntTy;
7790 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7791 case TargetInfo::SignedLong: return LongTy;
7792 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7793 case TargetInfo::SignedLongLong: return LongLongTy;
7794 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7795 }
7796
David Blaikie83d382b2011-09-23 05:06:16 +00007797 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007798}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007799
7800//===----------------------------------------------------------------------===//
7801// Type Predicates.
7802//===----------------------------------------------------------------------===//
7803
Fariborz Jahanian96207692009-02-18 21:49:28 +00007804/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7805/// garbage collection attribute.
7806///
John McCall553d45a2011-01-12 00:34:59 +00007807Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007808 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007809 return Qualifiers::GCNone;
7810
Erik Pilkingtonfa983902018-10-30 20:31:30 +00007811 assert(getLangOpts().ObjC);
John McCall553d45a2011-01-12 00:34:59 +00007812 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7813
7814 // Default behaviour under objective-C's gc is for ObjC pointers
7815 // (or pointers to them) be treated as though they were declared
7816 // as __strong.
7817 if (GCAttrs == Qualifiers::GCNone) {
7818 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7819 return Qualifiers::Strong;
7820 else if (Ty->isPointerType())
7821 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7822 } else {
7823 // It's not valid to set GC attributes on anything that isn't a
7824 // pointer.
7825#ifndef NDEBUG
7826 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007827 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007828 CT = AT->getElementType();
7829 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7830#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007831 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007832 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007833}
7834
Chris Lattner49af6a42008-04-07 06:51:04 +00007835//===----------------------------------------------------------------------===//
7836// Type Compatibility Testing
7837//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007838
Mike Stump11289f42009-09-09 15:08:12 +00007839/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007840/// compatible.
7841static bool areCompatVectorTypes(const VectorType *LHS,
7842 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007843 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007844 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007845 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007846}
7847
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007848bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7849 QualType SecondVec) {
7850 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7851 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7852
7853 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7854 return true;
7855
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007856 // Treat Neon vector types and most AltiVec vector types as if they are the
7857 // equivalent GCC vector types.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007858 const auto *First = FirstVec->getAs<VectorType>();
7859 const auto *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007860 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007861 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007862 First->getVectorKind() != VectorType::AltiVecPixel &&
7863 First->getVectorKind() != VectorType::AltiVecBool &&
7864 Second->getVectorKind() != VectorType::AltiVecPixel &&
7865 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007866 return true;
7867
7868 return false;
7869}
7870
Steve Naroff8e6aee52009-07-23 01:01:38 +00007871//===----------------------------------------------------------------------===//
7872// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7873//===----------------------------------------------------------------------===//
7874
7875/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7876/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007877bool
7878ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7879 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007880 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007881 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007882 for (auto *PI : rProto->protocols())
7883 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007884 return true;
7885 return false;
7886}
7887
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007888/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7889/// Class<pr1, ...>.
Fangrui Song6907ce22018-07-30 19:24:48 +00007890bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007891 QualType rhs) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007892 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7893 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007894 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fangrui Song6907ce22018-07-30 19:24:48 +00007895
Aaron Ballman83731462014-03-17 16:14:00 +00007896 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007897 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007898 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007899 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7900 match = true;
7901 break;
7902 }
7903 }
7904 if (!match)
7905 return false;
7906 }
7907 return true;
7908}
7909
Steve Naroff8e6aee52009-07-23 01:01:38 +00007910/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7911/// ObjCQualifiedIDType.
7912bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7913 bool compare) {
7914 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007915 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007916 lhs->isObjCIdType() || lhs->isObjCClassType())
7917 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007918 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007919 rhs->isObjCIdType() || rhs->isObjCClassType())
7920 return true;
7921
7922 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007923 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007924
Steve Naroff8e6aee52009-07-23 01:01:38 +00007925 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007926
Steve Naroff8e6aee52009-07-23 01:01:38 +00007927 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007928 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007929 // make sure we check the class hierarchy.
7930 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007931 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007932 // when comparing an id<P> on lhs with a static type on rhs,
7933 // see if static class implements all of id's protocols, directly or
7934 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007935 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007936 return false;
7937 }
7938 }
7939 // If there are no qualifiers and no interface, we have an 'id'.
7940 return true;
7941 }
Mike Stump11289f42009-09-09 15:08:12 +00007942 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007943 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007944 bool match = false;
7945
7946 // when comparing an id<P> on lhs with a static type on rhs,
7947 // see if static class implements all of id's protocols, directly or
7948 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007949 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007950 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7951 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7952 match = true;
7953 break;
7954 }
7955 }
Mike Stump11289f42009-09-09 15:08:12 +00007956 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007957 // make sure we check the class hierarchy.
7958 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007959 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007960 // when comparing an id<P> on lhs with a static type on rhs,
7961 // see if static class implements all of id's protocols, directly or
7962 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007963 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007964 match = true;
7965 break;
7966 }
7967 }
7968 }
7969 if (!match)
7970 return false;
7971 }
Mike Stump11289f42009-09-09 15:08:12 +00007972
Steve Naroff8e6aee52009-07-23 01:01:38 +00007973 return true;
7974 }
Mike Stump11289f42009-09-09 15:08:12 +00007975
Steve Naroff8e6aee52009-07-23 01:01:38 +00007976 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7977 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7978
Mike Stump11289f42009-09-09 15:08:12 +00007979 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007980 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007981 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007982 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007983 bool match = false;
7984
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007985 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007986 // see if static class implements all of id's protocols, directly or
7987 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007988 // First, lhs protocols in the qualifier list must be found, direct
7989 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007990 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007991 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7992 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7993 match = true;
7994 break;
7995 }
7996 }
7997 if (!match)
7998 return false;
7999 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008000
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008001 // Static class's protocols, or its super class or category protocols
8002 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8003 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
8004 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8005 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8006 // This is rather dubious but matches gcc's behavior. If lhs has
8007 // no type qualifier and its class has no static protocol(s)
8008 // assume that it is mismatch.
8009 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
8010 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00008011 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008012 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00008013 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008014 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8015 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8016 match = true;
8017 break;
8018 }
8019 }
8020 if (!match)
8021 return false;
8022 }
8023 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00008024 return true;
8025 }
8026 return false;
8027}
8028
Eli Friedman47f77112008-08-22 00:56:42 +00008029/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00008030/// compatible for assignment from RHS to LHS. This handles validation of any
8031/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00008032bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8033 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00008034 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8035 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8036
Steve Naroff1329fa02009-07-15 18:40:39 +00008037 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00008038 if (LHS->isObjCUnqualifiedIdOrClass() ||
8039 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00008040 return true;
8041
Douglas Gregorab209d82015-07-07 03:58:42 +00008042 // Function object that propagates a successful result or handles
8043 // __kindof types.
8044 auto finish = [&](bool succeeded) -> bool {
8045 if (succeeded)
8046 return true;
8047
8048 if (!RHS->isKindOfType())
8049 return false;
8050
8051 // Strip off __kindof and protocol qualifiers, then check whether
8052 // we can assign the other way.
8053 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8054 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8055 };
8056
8057 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8058 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8059 QualType(RHSOPT,0),
8060 false));
8061 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008062
Douglas Gregorab209d82015-07-07 03:58:42 +00008063 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8064 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
8065 QualType(RHSOPT,0)));
8066 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008067
John McCall8b07ec22010-05-15 11:32:37 +00008068 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00008069 if (LHS->getInterface() && RHS->getInterface()) {
8070 return finish(canAssignObjCInterfaces(LHS, RHS));
8071 }
Mike Stump11289f42009-09-09 15:08:12 +00008072
Steve Naroff8e6aee52009-07-23 01:01:38 +00008073 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008074}
8075
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008076/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Fangrui Song6907ce22018-07-30 19:24:48 +00008077/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008078/// arguments in block literals. When passed as arguments, passing 'A*' where
8079/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8080/// not OK. For the return type, the opposite is not OK.
8081bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8082 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008083 const ObjCObjectPointerType *RHSOPT,
8084 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008085
8086 // Function object that propagates a successful result or handles
8087 // __kindof types.
8088 auto finish = [&](bool succeeded) -> bool {
8089 if (succeeded)
8090 return true;
8091
8092 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8093 if (!Expected->isKindOfType())
8094 return false;
8095
8096 // Strip off __kindof and protocol qualifiers, then check whether
8097 // we can assign the other way.
8098 return canAssignObjCInterfacesInBlockPointer(
8099 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8100 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8101 BlockReturnType);
8102 };
8103
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008104 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008105 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008106
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008107 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008108 return finish(RHSOPT->isObjCBuiltinType() ||
8109 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008110 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008111
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008112 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00008113 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8114 QualType(RHSOPT,0),
8115 false));
Fangrui Song6907ce22018-07-30 19:24:48 +00008116
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008117 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8118 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8119 if (LHS && RHS) { // We have 2 user-defined types.
8120 if (LHS != RHS) {
8121 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008122 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008123 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008124 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008125 }
8126 else
8127 return true;
8128 }
8129 return false;
8130}
8131
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008132/// Comparison routine for Objective-C protocols to be used with
8133/// llvm::array_pod_sort.
8134static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8135 ObjCProtocolDecl * const *rhs) {
8136 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008137}
8138
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008139/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008140/// of protocols inherited from two distinct objective-c pointer objects with
8141/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008142/// It is used to build composite qualifier list of the composite type of
8143/// the conditional expression involving two objective-c pointer objects.
Fangrui Song6907ce22018-07-30 19:24:48 +00008144static
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008145void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008146 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008147 const ObjCObjectPointerType *LHSOPT,
8148 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008149 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008150
John McCall8b07ec22010-05-15 11:32:37 +00008151 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8152 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8153 assert(LHS->getInterface() && "LHS must have an interface base");
8154 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008155
8156 // Add all of the protocols for the LHS.
8157 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8158
8159 // Start with the protocol qualifiers.
8160 for (auto proto : LHS->quals()) {
8161 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008162 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008163
8164 // Also add the protocols associated with the LHS interface.
8165 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8166
Raphael Isemannb23ccec2018-12-10 12:37:46 +00008167 // Add all of the protocols for the RHS.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008168 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8169
8170 // Start with the protocol qualifiers.
8171 for (auto proto : RHS->quals()) {
8172 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008173 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008174
8175 // Also add the protocols associated with the RHS interface.
8176 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8177
8178 // Compute the intersection of the collected protocol sets.
8179 for (auto proto : LHSProtocolSet) {
8180 if (RHSProtocolSet.count(proto))
8181 IntersectionSet.push_back(proto);
8182 }
8183
8184 // Compute the set of protocols that is implied by either the common type or
8185 // the protocols within the intersection.
8186 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8187 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8188
8189 // Remove any implied protocols from the list of inherited protocols.
8190 if (!ImpliedProtocols.empty()) {
8191 IntersectionSet.erase(
8192 std::remove_if(IntersectionSet.begin(),
8193 IntersectionSet.end(),
8194 [&](ObjCProtocolDecl *proto) -> bool {
8195 return ImpliedProtocols.count(proto) > 0;
8196 }),
8197 IntersectionSet.end());
8198 }
8199
8200 // Sort the remaining protocols by name.
8201 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8202 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008203}
8204
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008205/// Determine whether the first type is a subtype of the second.
8206static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8207 QualType rhs) {
8208 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008209 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8210 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008211 if (lhsOPT && rhsOPT)
8212 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8213
8214 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008215 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8216 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008217 if (lhsBlock && rhsBlock)
8218 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8219
8220 // If either is an unqualified 'id' and the other is a block, it's
8221 // acceptable.
8222 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8223 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8224 return true;
8225
8226 return false;
8227}
8228
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008229// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008230static bool sameObjCTypeArgs(ASTContext &ctx,
8231 const ObjCInterfaceDecl *iface,
8232 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00008233 ArrayRef<QualType> rhsArgs,
8234 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008235 if (lhsArgs.size() != rhsArgs.size())
8236 return false;
8237
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008238 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008239 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008240 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8241 continue;
8242
8243 switch (typeParams->begin()[i]->getVariance()) {
8244 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00008245 if (!stripKindOf ||
8246 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8247 rhsArgs[i].stripObjCKindOfType(ctx))) {
8248 return false;
8249 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008250 break;
8251
8252 case ObjCTypeParamVariance::Covariant:
8253 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8254 return false;
8255 break;
8256
8257 case ObjCTypeParamVariance::Contravariant:
8258 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8259 return false;
8260 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00008261 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008262 }
8263
8264 return true;
8265}
8266
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008267QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008268 const ObjCObjectPointerType *Lptr,
8269 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008270 const ObjCObjectType *LHS = Lptr->getObjectType();
8271 const ObjCObjectType *RHS = Rptr->getObjectType();
8272 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8273 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008274
8275 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008276 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008277
Manman Renc46f7d12016-05-06 19:35:02 +00008278 // When either LHS or RHS is a kindof type, we should return a kindof type.
8279 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8280 // kindof(A).
8281 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8282
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008283 // Follow the left-hand side up the class hierarchy until we either hit a
8284 // root or find the RHS. Record the ancestors in case we don't find it.
8285 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8286 LHSAncestors;
8287 while (true) {
8288 // Record this ancestor. We'll need this if the common type isn't in the
8289 // path from the LHS to the root.
8290 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008291
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008292 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8293 // Get the type arguments.
8294 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8295 bool anyChanges = false;
8296 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8297 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008298 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8299 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008300 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008301 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008302 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8303 // If only one has type arguments, the result will not have type
8304 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008305 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008306 anyChanges = true;
8307 }
8308
8309 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008310 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008311 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8312 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008313 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008314 anyChanges = true;
8315
8316 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008317 // If we need to return a kindof type but LHS is not a kindof type, we
8318 // build a new result type.
8319 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008320 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008321 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008322 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008323 return getObjCObjectPointerType(Result);
8324 }
8325
8326 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008327 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008328
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008329 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008330 QualType LHSSuperType = LHS->getSuperClassType();
8331 if (LHSSuperType.isNull())
8332 break;
8333
8334 LHS = LHSSuperType->castAs<ObjCObjectType>();
8335 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008336
8337 // We didn't find anything by following the LHS to its root; now check
8338 // the RHS against the cached set of ancestors.
8339 while (true) {
8340 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8341 if (KnownLHS != LHSAncestors.end()) {
8342 LHS = KnownLHS->second;
8343
8344 // Get the type arguments.
8345 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8346 bool anyChanges = false;
8347 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8348 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008349 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8350 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008351 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008352 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008353 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8354 // If only one has type arguments, the result will not have type
8355 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008356 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008357 anyChanges = true;
8358 }
8359
8360 // Compute the intersection of protocols.
8361 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8362 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8363 Protocols);
8364 if (!Protocols.empty())
8365 anyChanges = true;
8366
Manman Renc46f7d12016-05-06 19:35:02 +00008367 // If we need to return a kindof type but RHS is not a kindof type, we
8368 // build a new result type.
8369 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008370 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008371 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008372 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008373 return getObjCObjectPointerType(Result);
8374 }
8375
8376 return getObjCObjectPointerType(QualType(RHS, 0));
8377 }
8378
8379 // Find the superclass of the RHS.
8380 QualType RHSSuperType = RHS->getSuperClassType();
8381 if (RHSSuperType.isNull())
8382 break;
8383
8384 RHS = RHSSuperType->castAs<ObjCObjectType>();
8385 }
8386
Eugene Zelenko7855e772018-04-03 00:11:50 +00008387 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008388}
8389
John McCall8b07ec22010-05-15 11:32:37 +00008390bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8391 const ObjCObjectType *RHS) {
8392 assert(LHS->getInterface() && "LHS is not an interface type");
8393 assert(RHS->getInterface() && "RHS is not an interface type");
8394
Chris Lattner49af6a42008-04-07 06:51:04 +00008395 // Verify that the base decls are compatible: the RHS must be a subclass of
8396 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008397 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8398 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8399 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008400 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008401
Douglas Gregore83b9562015-07-07 03:57:53 +00008402 // If the LHS has protocol qualifiers, determine whether all of them are
8403 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8404 // LHS).
8405 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008406 // OK if conversion of LHS to SuperClass results in narrowing of types
8407 // ; i.e., SuperClass may implement at least one of the protocols
8408 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8409 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8410 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8411 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8412 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8413 // qualifiers.
8414 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008415 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008416 // If there is no protocols associated with RHS, it is not a match.
8417 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008418 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008419
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008420 for (const auto *LHSProto : LHS->quals()) {
8421 bool SuperImplementsProtocol = false;
8422 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8423 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8424 SuperImplementsProtocol = true;
8425 break;
8426 }
8427 if (!SuperImplementsProtocol)
8428 return false;
8429 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008430 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008431
8432 // If the LHS is specialized, we may need to check type arguments.
8433 if (LHS->isSpecialized()) {
8434 // Follow the superclass chain until we've matched the LHS class in the
8435 // hierarchy. This substitutes type arguments through.
8436 const ObjCObjectType *RHSSuper = RHS;
8437 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8438 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8439
8440 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008441 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008442 !sameObjCTypeArgs(*this, LHS->getInterface(),
8443 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008444 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008445 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008446 }
8447 }
8448
8449 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008450}
8451
Steve Naroffb7605152009-02-12 17:52:19 +00008452bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8453 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008454 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8455 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008456
Steve Naroff7cae42b2009-07-10 23:34:53 +00008457 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008458 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008459
8460 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8461 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008462}
8463
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008464bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8465 return canAssignObjCInterfaces(
8466 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8467 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8468}
8469
Mike Stump11289f42009-09-09 15:08:12 +00008470/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008471/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008472/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008473/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008474bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8475 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008476 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008477 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008478
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008479 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008480}
8481
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008482bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008483 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008484}
8485
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008486bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8487 return !mergeTypes(LHS, RHS, true).isNull();
8488}
8489
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008490/// mergeTransparentUnionType - if T is a transparent union type and a member
8491/// of T is compatible with SubType, return the merged type, else return
8492/// QualType()
8493QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8494 bool OfBlockPointer,
8495 bool Unqualified) {
8496 if (const RecordType *UT = T->getAsUnionType()) {
8497 RecordDecl *UD = UT->getDecl();
8498 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008499 for (const auto *I : UD->fields()) {
8500 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008501 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8502 if (!MT.isNull())
8503 return MT;
8504 }
8505 }
8506 }
8507
Eugene Zelenko7855e772018-04-03 00:11:50 +00008508 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008509}
8510
Alp Toker9cacbab2014-01-20 20:26:09 +00008511/// mergeFunctionParameterTypes - merge two types which appear as function
8512/// parameter types
8513QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8514 bool OfBlockPointer,
8515 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008516 // GNU extension: two types are compatible if they appear as a function
8517 // argument, one of the types is a transparent union type and the other
8518 // type is compatible with a union member
8519 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8520 Unqualified);
8521 if (!lmerge.isNull())
8522 return lmerge;
8523
8524 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8525 Unqualified);
8526 if (!rmerge.isNull())
8527 return rmerge;
8528
8529 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8530}
8531
Fangrui Song6907ce22018-07-30 19:24:48 +00008532QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008533 bool OfBlockPointer,
8534 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008535 const auto *lbase = lhs->getAs<FunctionType>();
8536 const auto *rbase = rhs->getAs<FunctionType>();
8537 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8538 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008539 bool allLTypes = true;
8540 bool allRTypes = true;
8541
8542 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008543 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008544 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008545 QualType RHS = rbase->getReturnType();
8546 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008547 bool UnqualifiedResult = Unqualified;
8548 if (!UnqualifiedResult)
8549 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008550 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008551 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008552 else
Alp Toker314cc812014-01-25 16:55:45 +00008553 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008554 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008555 if (retType.isNull())
8556 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00008557
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008558 if (Unqualified)
8559 retType = retType.getUnqualifiedType();
8560
Alp Toker314cc812014-01-25 16:55:45 +00008561 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8562 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008563 if (Unqualified) {
8564 LRetType = LRetType.getUnqualifiedType();
8565 RRetType = RRetType.getUnqualifiedType();
8566 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008567
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008568 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008569 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008570 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008571 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008572
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008573 // FIXME: double check this
8574 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8575 // rbase->getRegParmAttr() != 0 &&
8576 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008577 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8578 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008579
Douglas Gregor8c940862010-01-18 17:14:39 +00008580 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008581 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008582 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008583
John McCall8c6b56f2010-12-15 01:06:38 +00008584 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008585 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008586 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008587 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008588 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008589
John McCall31168b02011-06-15 23:02:42 +00008590 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008591 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008592 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008593 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008594 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008595 return {};
John McCall31168b02011-06-15 23:02:42 +00008596
John McCall8c6b56f2010-12-15 01:06:38 +00008597 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8598 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008599
Rafael Espindola8778c282012-11-29 16:09:03 +00008600 if (lbaseInfo.getNoReturn() != NoReturn)
8601 allLTypes = false;
8602 if (rbaseInfo.getNoReturn() != NoReturn)
8603 allRTypes = false;
8604
John McCall31168b02011-06-15 23:02:42 +00008605 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008606
Eli Friedman47f77112008-08-22 00:56:42 +00008607 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008608 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8609 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008610 // Compatible functions must have the same number of parameters
8611 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008612 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008613
8614 // Variadic and non-variadic functions aren't compatible
8615 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008616 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008617
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008618 if (lproto->getMethodQuals() != rproto->getMethodQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008619 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008620
Akira Hatanaka98a49332017-09-22 00:41:05 +00008621 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8622 bool canUseLeft, canUseRight;
8623 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8624 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008625 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008626
Akira Hatanaka98a49332017-09-22 00:41:05 +00008627 if (!canUseLeft)
8628 allLTypes = false;
8629 if (!canUseRight)
8630 allRTypes = false;
8631
Alp Toker601b22c2014-01-21 23:35:24 +00008632 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008633 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008634 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8635 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8636 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8637 QualType paramType = mergeFunctionParameterTypes(
8638 lParamType, rParamType, OfBlockPointer, Unqualified);
8639 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008640 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008641
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008642 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008643 paramType = paramType.getUnqualifiedType();
8644
8645 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008646 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008647 lParamType = lParamType.getUnqualifiedType();
8648 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008649 }
Alp Toker601b22c2014-01-21 23:35:24 +00008650
8651 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008652 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008653 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008654 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008655 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008656
Eli Friedman47f77112008-08-22 00:56:42 +00008657 if (allLTypes) return lhs;
8658 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008659
8660 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8661 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008662 EPI.ExtParameterInfos =
8663 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008664 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008665 }
8666
8667 if (lproto) allRTypes = false;
8668 if (rproto) allLTypes = false;
8669
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008670 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008671 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008672 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008673 if (proto->isVariadic())
8674 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008675 // Check that the types are compatible with the types that
8676 // would result from default argument promotions (C99 6.7.5.3p15).
8677 // The only types actually affected are promotable integer
8678 // types and floats, which would be passed as a different
8679 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008680 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8681 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008682
Eli Friedman448ce402012-08-30 00:44:15 +00008683 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008684 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008685 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008686 paramTy = Enum->getDecl()->getIntegerType();
8687 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008688 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008689 }
Alp Toker601b22c2014-01-21 23:35:24 +00008690
8691 if (paramTy->isPromotableIntegerType() ||
8692 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008693 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008694 }
8695
8696 if (allLTypes) return lhs;
8697 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008698
8699 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8700 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008701 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008702 }
8703
8704 if (allLTypes) return lhs;
8705 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008706 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008707}
8708
John McCall433c2e62013-03-21 00:10:07 +00008709/// Given that we have an enum type and a non-enum type, try to merge them.
8710static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8711 QualType other, bool isBlockReturnType) {
8712 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8713 // a signed integer type, or an unsigned integer type.
8714 // Compatibility is based on the underlying type, not the promotion
8715 // type.
8716 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008717 if (underlyingType.isNull())
8718 return {};
John McCall433c2e62013-03-21 00:10:07 +00008719 if (Context.hasSameType(underlyingType, other))
8720 return other;
8721
8722 // In block return types, we're more permissive and accept any
8723 // integral type of the same size.
8724 if (isBlockReturnType && other->isIntegerType() &&
8725 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8726 return other;
8727
Eugene Zelenko7855e772018-04-03 00:11:50 +00008728 return {};
John McCall433c2e62013-03-21 00:10:07 +00008729}
8730
Fangrui Song6907ce22018-07-30 19:24:48 +00008731QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008732 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008733 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008734 // C++ [expr]: If an expression initially has the type "reference to T", the
8735 // type is adjusted to "T" prior to any further analysis, the expression
8736 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008737 // expression is an lvalue unless the reference is an rvalue reference and
8738 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008739 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8740 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008741
8742 if (Unqualified) {
8743 LHS = LHS.getUnqualifiedType();
8744 RHS = RHS.getUnqualifiedType();
8745 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008746
Eli Friedman47f77112008-08-22 00:56:42 +00008747 QualType LHSCan = getCanonicalType(LHS),
8748 RHSCan = getCanonicalType(RHS);
8749
8750 // If two types are identical, they are compatible.
8751 if (LHSCan == RHSCan)
8752 return LHS;
8753
John McCall8ccfcb52009-09-24 19:53:00 +00008754 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008755 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8756 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008757 if (LQuals != RQuals) {
8758 // If any of these qualifiers are different, we have a type
8759 // mismatch.
8760 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008761 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008762 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8763 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008764 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008765
8766 // Exactly one GC qualifier difference is allowed: __strong is
8767 // okay if the other type has no GC qualifier but is an Objective
8768 // C object pointer (i.e. implicitly strong by default). We fix
8769 // this by pretending that the unqualified type was actually
8770 // qualified __strong.
8771 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8772 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8773 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8774
8775 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008776 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008777
8778 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8779 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8780 }
8781 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8782 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8783 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008784 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008785 }
8786
8787 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008788
Eli Friedmandcca6332009-06-01 01:22:52 +00008789 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8790 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008791
Chris Lattnerfd652912008-01-14 05:45:46 +00008792 // We want to consider the two function types to be the same for these
8793 // comparisons, just force one to the other.
8794 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8795 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008796
8797 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008798 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8799 LHSClass = Type::ConstantArray;
8800 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8801 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008802
John McCall8b07ec22010-05-15 11:32:37 +00008803 // ObjCInterfaces are just specialized ObjCObjects.
8804 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8805 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8806
Nate Begemance4d7fc2008-04-18 23:10:10 +00008807 // Canonicalize ExtVector -> Vector.
8808 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8809 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008810
Chris Lattner95554662008-04-07 05:43:21 +00008811 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008812 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008813 // Note that we only have special rules for turning block enum
8814 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008815 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008816 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008817 }
John McCall9dd450b2009-09-21 23:43:11 +00008818 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008819 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008820 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008821 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008822 if (OfBlockPointer && !BlockReturnType) {
8823 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8824 return LHS;
8825 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8826 return RHS;
8827 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008828
Eugene Zelenko7855e772018-04-03 00:11:50 +00008829 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008830 }
Eli Friedman47f77112008-08-22 00:56:42 +00008831
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008832 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008833 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008834#define TYPE(Class, Base)
8835#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008836#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008837#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8838#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8839#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008840 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008841
Richard Smith27d807c2013-04-30 13:56:41 +00008842 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008843 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008844 case Type::LValueReference:
8845 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008846 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008847 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008848
John McCall8b07ec22010-05-15 11:32:37 +00008849 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008850 case Type::IncompleteArray:
8851 case Type::VariableArray:
8852 case Type::FunctionProto:
8853 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008854 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008855
Chris Lattnerfd652912008-01-14 05:45:46 +00008856 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008857 {
8858 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008859 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8860 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008861 if (Unqualified) {
8862 LHSPointee = LHSPointee.getUnqualifiedType();
8863 RHSPointee = RHSPointee.getUnqualifiedType();
8864 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008865 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008866 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008867 if (ResultType.isNull())
8868 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008869 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008870 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008871 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008872 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008873 return getPointerType(ResultType);
8874 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008875 case Type::BlockPointer:
8876 {
8877 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008878 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8879 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008880 if (Unqualified) {
8881 LHSPointee = LHSPointee.getUnqualifiedType();
8882 RHSPointee = RHSPointee.getUnqualifiedType();
8883 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008884 if (getLangOpts().OpenCL) {
8885 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8886 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8887 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8888 // 6.12.5) thus the following check is asymmetric.
8889 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008890 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008891 LHSPteeQual.removeAddressSpace();
8892 RHSPteeQual.removeAddressSpace();
8893 LHSPointee =
8894 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8895 RHSPointee =
8896 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8897 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008898 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8899 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008900 if (ResultType.isNull())
8901 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00008902 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8903 return LHS;
8904 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8905 return RHS;
8906 return getBlockPointerType(ResultType);
8907 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008908 case Type::Atomic:
8909 {
8910 // Merge two pointer types, while trying to preserve typedef info
8911 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8912 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8913 if (Unqualified) {
8914 LHSValue = LHSValue.getUnqualifiedType();
8915 RHSValue = RHSValue.getUnqualifiedType();
8916 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008917 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
Eli Friedman0dfb8892011-10-06 23:00:33 +00008918 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008919 if (ResultType.isNull())
8920 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00008921 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8922 return LHS;
8923 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8924 return RHS;
8925 return getAtomicType(ResultType);
8926 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008927 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008928 {
8929 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8930 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8931 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008932 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008933
8934 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8935 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008936 if (Unqualified) {
8937 LHSElem = LHSElem.getUnqualifiedType();
8938 RHSElem = RHSElem.getUnqualifiedType();
8939 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008940
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008941 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008942 if (ResultType.isNull())
8943 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00008944
8945 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8946 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8947
8948 // If either side is a variable array, and both are complete, check whether
8949 // the current dimension is definite.
8950 if (LVAT || RVAT) {
8951 auto SizeFetch = [this](const VariableArrayType* VAT,
8952 const ConstantArrayType* CAT)
8953 -> std::pair<bool,llvm::APInt> {
8954 if (VAT) {
8955 llvm::APSInt TheInt;
8956 Expr *E = VAT->getSizeExpr();
8957 if (E && E->isIntegerConstantExpr(TheInt, *this))
8958 return std::make_pair(true, TheInt);
8959 else
8960 return std::make_pair(false, TheInt);
8961 } else if (CAT) {
8962 return std::make_pair(true, CAT->getSize());
8963 } else {
8964 return std::make_pair(false, llvm::APInt());
8965 }
8966 };
8967
8968 bool HaveLSize, HaveRSize;
8969 llvm::APInt LSize, RSize;
8970 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
8971 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
8972 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
8973 return {}; // Definite, but unequal, array dimension
8974 }
8975
Chris Lattner465fa322008-10-05 17:34:18 +00008976 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8977 return LHS;
8978 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8979 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008980 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8981 ArrayType::ArraySizeModifier(), 0);
8982 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8983 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00008984 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8985 return LHS;
8986 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8987 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008988 if (LVAT) {
8989 // FIXME: This isn't correct! But tricky to implement because
8990 // the array's size has to be the size of LHS, but the type
8991 // has to be different.
8992 return LHS;
8993 }
8994 if (RVAT) {
8995 // FIXME: This isn't correct! But tricky to implement because
8996 // the array's size has to be the size of RHS, but the type
8997 // has to be different.
8998 return RHS;
8999 }
Eli Friedman3e62c212008-08-22 01:48:21 +00009000 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9001 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00009002 return getIncompleteArrayType(ResultType,
9003 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00009004 }
Chris Lattnerfd652912008-01-14 05:45:46 +00009005 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009006 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009007 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009008 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00009009 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00009010 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009011 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009012 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00009013 case Type::Complex:
9014 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009015 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009016 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00009017 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00009018 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
9019 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00009020 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009021 return {};
John McCall8b07ec22010-05-15 11:32:37 +00009022 case Type::ObjCObject: {
9023 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00009024 // FIXME: This should be type compatibility, e.g. whether
9025 // "LHS x; RHS x;" at global scope is legal.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009026 const auto *LHSIface = LHS->getAs<ObjCObjectType>();
9027 const auto *RHSIface = RHS->getAs<ObjCObjectType>();
John McCall8b07ec22010-05-15 11:32:37 +00009028 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00009029 return LHS;
9030
Eugene Zelenko7855e772018-04-03 00:11:50 +00009031 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00009032 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009033 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009034 if (OfBlockPointer) {
9035 if (canAssignObjCInterfacesInBlockPointer(
9036 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00009037 RHS->getAs<ObjCObjectPointerType>(),
9038 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00009039 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009040 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009041 }
John McCall9dd450b2009-09-21 23:43:11 +00009042 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
9043 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00009044 return LHS;
9045
Eugene Zelenko7855e772018-04-03 00:11:50 +00009046 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009047 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00009048 assert(LHS != RHS &&
9049 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00009050 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009051 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009052
David Blaikie8a40f702012-01-17 06:56:22 +00009053 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00009054}
Ted Kremenekfc581a92007-10-31 17:10:13 +00009055
Akira Hatanaka98a49332017-09-22 00:41:05 +00009056bool ASTContext::mergeExtParameterInfo(
9057 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9058 bool &CanUseFirst, bool &CanUseSecond,
9059 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9060 assert(NewParamInfos.empty() && "param info list not empty");
9061 CanUseFirst = CanUseSecond = true;
9062 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9063 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9064
John McCall18afab72016-03-01 00:49:02 +00009065 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00009066 // we match if and only if the second type also doesn't have them.
9067 if (!FirstHasInfo && !SecondHasInfo)
9068 return true;
John McCall18afab72016-03-01 00:49:02 +00009069
Akira Hatanaka98a49332017-09-22 00:41:05 +00009070 bool NeedParamInfo = false;
9071 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9072 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00009073
Akira Hatanaka98a49332017-09-22 00:41:05 +00009074 for (size_t I = 0; I < E; ++I) {
9075 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9076 if (FirstHasInfo)
9077 FirstParam = FirstFnType->getExtParameterInfo(I);
9078 if (SecondHasInfo)
9079 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00009080
Akira Hatanaka98a49332017-09-22 00:41:05 +00009081 // Cannot merge unless everything except the noescape flag matches.
9082 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00009083 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00009084
9085 bool FirstNoEscape = FirstParam.isNoEscape();
9086 bool SecondNoEscape = SecondParam.isNoEscape();
9087 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9088 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9089 if (NewParamInfos.back().getOpaqueValue())
9090 NeedParamInfo = true;
9091 if (FirstNoEscape != IsNoEscape)
9092 CanUseFirst = false;
9093 if (SecondNoEscape != IsNoEscape)
9094 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00009095 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00009096
9097 if (!NeedParamInfo)
9098 NewParamInfos.clear();
9099
Fariborz Jahanian97676972011-09-28 21:52:05 +00009100 return true;
9101}
9102
Chandler Carruth21c90602015-12-30 03:24:14 +00009103void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9104 ObjCLayouts[CD] = nullptr;
9105}
9106
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009107/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9108/// 'RHS' attributes and returns the merged version; including for function
9109/// return types.
9110QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9111 QualType LHSCan = getCanonicalType(LHS),
9112 RHSCan = getCanonicalType(RHS);
9113 // If two types are identical, they are compatible.
9114 if (LHSCan == RHSCan)
9115 return LHS;
9116 if (RHSCan->isFunctionType()) {
9117 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009118 return {};
Alp Toker314cc812014-01-25 16:55:45 +00009119 QualType OldReturnType =
9120 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009121 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00009122 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009123 QualType ResReturnType =
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009124 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9125 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009126 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009127 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9128 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9129 // In either case, use OldReturnType to build the new function type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009130 const auto *F = LHS->getAs<FunctionType>();
9131 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009132 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9133 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00009134 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00009135 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009136 return ResultType;
9137 }
9138 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009139 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009140 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009141
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009142 // If the qualifiers are different, the types can still be merged.
9143 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9144 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9145 if (LQuals != RQuals) {
9146 // If any of these qualifiers are different, we have a type mismatch.
9147 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9148 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009149 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009150
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009151 // Exactly one GC qualifier difference is allowed: __strong is
9152 // okay if the other type has no GC qualifier but is an Objective
9153 // C object pointer (i.e. implicitly strong by default). We fix
9154 // this by pretending that the unqualified type was actually
9155 // qualified __strong.
9156 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9157 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9158 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
Fangrui Song6907ce22018-07-30 19:24:48 +00009159
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009160 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009161 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009162
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009163 if (GC_L == Qualifiers::Strong)
9164 return LHS;
9165 if (GC_R == Qualifiers::Strong)
9166 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009167 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009168 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009169
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009170 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9171 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9172 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9173 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9174 if (ResQT == LHSBaseQT)
9175 return LHS;
9176 if (ResQT == RHSBaseQT)
9177 return RHS;
9178 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009179 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009180}
9181
Chris Lattner4ba0cef2008-04-07 07:01:58 +00009182//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009183// Integer Predicates
9184//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00009185
Jay Foad39c79802011-01-12 09:06:06 +00009186unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009187 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00009188 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009189 if (T->isBooleanType())
9190 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00009191 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009192 return (unsigned)getTypeSize(T);
9193}
9194
Abramo Bagnara13640492012-09-09 10:21:24 +00009195QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00009196 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9197 "Unexpected type");
Fangrui Song6907ce22018-07-30 19:24:48 +00009198
Chris Lattnerec3a1562009-10-17 20:33:28 +00009199 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00009200 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00009201 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00009202 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00009203
9204 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009205 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009206 T = ETy->getDecl()->getIntegerType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009207
Eugene Zelenko7855e772018-04-03 00:11:50 +00009208 const auto *BTy = T->getAs<BuiltinType>();
Leonard Chanab80f3c2018-06-14 14:53:51 +00009209 assert(BTy && "Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009210 switch (BTy->getKind()) {
9211 case BuiltinType::Char_S:
9212 case BuiltinType::SChar:
9213 return UnsignedCharTy;
9214 case BuiltinType::Short:
9215 return UnsignedShortTy;
9216 case BuiltinType::Int:
9217 return UnsignedIntTy;
9218 case BuiltinType::Long:
9219 return UnsignedLongTy;
9220 case BuiltinType::LongLong:
9221 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00009222 case BuiltinType::Int128:
9223 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00009224
9225 case BuiltinType::ShortAccum:
9226 return UnsignedShortAccumTy;
9227 case BuiltinType::Accum:
9228 return UnsignedAccumTy;
9229 case BuiltinType::LongAccum:
9230 return UnsignedLongAccumTy;
9231 case BuiltinType::SatShortAccum:
9232 return SatUnsignedShortAccumTy;
9233 case BuiltinType::SatAccum:
9234 return SatUnsignedAccumTy;
9235 case BuiltinType::SatLongAccum:
9236 return SatUnsignedLongAccumTy;
9237 case BuiltinType::ShortFract:
9238 return UnsignedShortFractTy;
9239 case BuiltinType::Fract:
9240 return UnsignedFractTy;
9241 case BuiltinType::LongFract:
9242 return UnsignedLongFractTy;
9243 case BuiltinType::SatShortFract:
9244 return SatUnsignedShortFractTy;
9245 case BuiltinType::SatFract:
9246 return SatUnsignedFractTy;
9247 case BuiltinType::SatLongFract:
9248 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009249 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009250 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009251 }
9252}
9253
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009254ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00009255
Richard Smith1fa5d642013-05-11 05:45:24 +00009256void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9257 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00009258
9259//===----------------------------------------------------------------------===//
9260// Builtin Type Computation
9261//===----------------------------------------------------------------------===//
9262
9263/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00009264/// pointer over the consumed characters. This returns the resultant type. If
9265/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9266/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9267/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009268///
9269/// RequiresICE is filled in on return to indicate whether the value is required
9270/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009271static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009272 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009273 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009274 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009275 // Modifiers.
9276 int HowLong = 0;
9277 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009278 RequiresICE = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009279
Chris Lattnerdc226c22010-10-01 22:42:38 +00009280 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009281 bool Done = false;
9282 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009283 bool IsSpecial = false;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009284 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009285 while (!Done) {
9286 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009287 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009288 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009289 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009290 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009291 case 'S':
9292 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9293 assert(!Signed && "Can't use 'S' modifier multiple times!");
9294 Signed = true;
9295 break;
9296 case 'U':
9297 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009298 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009299 Unsigned = true;
9300 break;
9301 case 'L':
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009302 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009303 assert(HowLong <= 2 && "Can't have LLLL modifier");
9304 ++HowLong;
9305 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009306 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009307 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009308 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009309 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009310 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009311 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009312 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009313 if (Context.getTargetInfo().getLongWidth() == 32)
9314 ++HowLong;
9315 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009316 case 'W':
9317 // This modifier represents int64 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009318 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009319 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009320 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009321 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009322 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009323 switch (Context.getTargetInfo().getInt64Type()) {
9324 default:
9325 llvm_unreachable("Unexpected integer type");
9326 case TargetInfo::SignedLong:
9327 HowLong = 1;
9328 break;
9329 case TargetInfo::SignedLongLong:
9330 HowLong = 2;
9331 break;
9332 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009333 break;
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009334 case 'Z':
9335 // This modifier represents int32 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009336 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009337 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
9338 #ifndef NDEBUG
9339 IsSpecial = true;
9340 #endif
9341 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
9342 default:
9343 llvm_unreachable("Unexpected integer type");
9344 case TargetInfo::SignedInt:
9345 HowLong = 0;
9346 break;
9347 case TargetInfo::SignedLong:
9348 HowLong = 1;
9349 break;
9350 case TargetInfo::SignedLongLong:
9351 HowLong = 2;
9352 break;
9353 }
9354 break;
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009355 case 'O':
9356 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9357 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
9358 #ifndef NDEBUG
9359 IsSpecial = true;
9360 #endif
9361 if (Context.getLangOpts().OpenCL)
9362 HowLong = 1;
9363 else
9364 HowLong = 2;
9365 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009366 }
9367 }
9368
9369 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009370
Chris Lattnerecd79c62009-06-14 00:45:47 +00009371 // Read the base type.
9372 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009373 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009374 case 'v':
9375 assert(HowLong == 0 && !Signed && !Unsigned &&
9376 "Bad modifiers used with 'v'!");
9377 Type = Context.VoidTy;
9378 break;
Jack Carter24bef982013-08-15 15:16:57 +00009379 case 'h':
9380 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009381 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009382 Type = Context.HalfTy;
9383 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009384 case 'f':
9385 assert(HowLong == 0 && !Signed && !Unsigned &&
9386 "Bad modifiers used with 'f'!");
9387 Type = Context.FloatTy;
9388 break;
9389 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009390 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009391 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009392 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009393 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009394 else if (HowLong == 2)
9395 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009396 else
9397 Type = Context.DoubleTy;
9398 break;
9399 case 's':
9400 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9401 if (Unsigned)
9402 Type = Context.UnsignedShortTy;
9403 else
9404 Type = Context.ShortTy;
9405 break;
9406 case 'i':
9407 if (HowLong == 3)
9408 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9409 else if (HowLong == 2)
9410 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9411 else if (HowLong == 1)
9412 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9413 else
9414 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9415 break;
9416 case 'c':
9417 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9418 if (Signed)
9419 Type = Context.SignedCharTy;
9420 else if (Unsigned)
9421 Type = Context.UnsignedCharTy;
9422 else
9423 Type = Context.CharTy;
9424 break;
9425 case 'b': // boolean
9426 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9427 Type = Context.BoolTy;
9428 break;
9429 case 'z': // size_t.
9430 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9431 Type = Context.getSizeType();
9432 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009433 case 'w': // wchar_t.
9434 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9435 Type = Context.getWideCharType();
9436 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009437 case 'F':
9438 Type = Context.getCFConstantStringType();
9439 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009440 case 'G':
9441 Type = Context.getObjCIdType();
9442 break;
9443 case 'H':
9444 Type = Context.getObjCSelType();
9445 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009446 case 'M':
9447 Type = Context.getObjCSuperType();
9448 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009449 case 'a':
9450 Type = Context.getBuiltinVaListType();
9451 assert(!Type.isNull() && "builtin va list type not initialized!");
9452 break;
9453 case 'A':
9454 // This is a "reference" to a va_list; however, what exactly
9455 // this means depends on how va_list is defined. There are two
9456 // different kinds of va_list: ones passed by value, and ones
9457 // passed by reference. An example of a by-value va_list is
9458 // x86, where va_list is a char*. An example of by-ref va_list
9459 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9460 // we want this argument to be a char*&; for x86-64, we want
9461 // it to be a __va_list_tag*.
9462 Type = Context.getBuiltinVaListType();
9463 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009464 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009465 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009466 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009467 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009468 break;
9469 case 'V': {
9470 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009471 unsigned NumElements = strtoul(Str, &End, 10);
9472 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009473 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009474
Fangrui Song6907ce22018-07-30 19:24:48 +00009475 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009476 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009477 assert(!RequiresICE && "Can't require vector ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009478
Chris Lattnerdc226c22010-10-01 22:42:38 +00009479 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009480 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009481 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009482 break;
9483 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009484 case 'E': {
9485 char *End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009486
Douglas Gregorfed66992012-06-07 18:08:25 +00009487 unsigned NumElements = strtoul(Str, &End, 10);
9488 assert(End != Str && "Missing vector size");
Fangrui Song6907ce22018-07-30 19:24:48 +00009489
Douglas Gregorfed66992012-06-07 18:08:25 +00009490 Str = End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009491
Douglas Gregorfed66992012-06-07 18:08:25 +00009492 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009493 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009494 Type = Context.getExtVectorType(ElementType, NumElements);
Fangrui Song6907ce22018-07-30 19:24:48 +00009495 break;
Douglas Gregorfed66992012-06-07 18:08:25 +00009496 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009497 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009498 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009499 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009500 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009501 Type = Context.getComplexType(ElementType);
9502 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00009503 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009504 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009505 Type = Context.getPointerDiffType();
9506 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009507 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009508 Type = Context.getFILEType();
9509 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009510 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009511 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009512 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009513 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009514 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009515 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009516 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009517 else
9518 Type = Context.getjmp_bufType();
9519
Mike Stump2adb4da2009-07-28 23:47:15 +00009520 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009521 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009522 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009523 }
9524 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009525 case 'K':
9526 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9527 Type = Context.getucontext_tType();
9528
9529 if (Type.isNull()) {
9530 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009531 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009532 }
9533 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009534 case 'p':
9535 Type = Context.getProcessIDType();
9536 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009537 }
Mike Stump11289f42009-09-09 15:08:12 +00009538
Chris Lattnerdc226c22010-10-01 22:42:38 +00009539 // If there are modifiers and if we're allowed to parse them, go for it.
9540 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009541 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009542 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009543 default: Done = true; --Str; break;
9544 case '*':
9545 case '&': {
9546 // Both pointers and references can have their pointee types
9547 // qualified with an address space.
9548 char *End;
9549 unsigned AddrSpace = strtoul(Str, &End, 10);
Matt Arsenaultc65f9662018-08-02 12:14:28 +00009550 if (End != Str) {
9551 // Note AddrSpace == 0 is not the same as an unspecified address space.
9552 Type = Context.getAddrSpaceQualType(
9553 Type,
9554 Context.getLangASForBuiltinAddressSpace(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009555 Str = End;
9556 }
9557 if (c == '*')
9558 Type = Context.getPointerType(Type);
9559 else
9560 Type = Context.getLValueReferenceType(Type);
9561 break;
9562 }
9563 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9564 case 'C':
9565 Type = Type.withConst();
9566 break;
9567 case 'D':
9568 Type = Context.getVolatileType(Type);
9569 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009570 case 'R':
9571 Type = Type.withRestrict();
9572 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009573 }
9574 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009575
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009576 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Fangrui Song6907ce22018-07-30 19:24:48 +00009577 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009578
Chris Lattnerecd79c62009-06-14 00:45:47 +00009579 return Type;
9580}
9581
9582/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009583QualType ASTContext::GetBuiltinType(unsigned Id,
9584 GetBuiltinTypeError &Error,
9585 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009586 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00009587 if (TypeStr[0] == '\0') {
9588 Error = GE_Missing_type;
9589 return {};
9590 }
Mike Stump11289f42009-09-09 15:08:12 +00009591
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009592 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009593
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009594 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009595 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009596 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9597 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009598 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009599 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009600
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009601 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009602
Chris Lattnerecd79c62009-06-14 00:45:47 +00009603 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009604 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009605 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009606 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009607
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009608 // If this argument is required to be an IntegerConstantExpression and the
9609 // caller cares, fill in the bitmask we return.
9610 if (RequiresICE && IntegerConstantArgs)
9611 *IntegerConstantArgs |= 1 << ArgTypes.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00009612
Chris Lattnerecd79c62009-06-14 00:45:47 +00009613 // Do array -> pointer decay. The builtin should use the decayed type.
9614 if (Ty->isArrayType())
9615 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009616
Chris Lattnerecd79c62009-06-14 00:45:47 +00009617 ArgTypes.push_back(Ty);
9618 }
9619
David Majnemerba3e5ec2015-03-13 18:26:17 +00009620 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009621 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009622
Chris Lattnerecd79c62009-06-14 00:45:47 +00009623 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9624 "'.' should only occur at end of builtin type list!");
9625
Erich Keane881e83d2019-03-04 14:54:52 +00009626 bool Variadic = (TypeStr[0] == '.');
9627
Erich Keane00022812019-05-23 16:05:21 +00009628 FunctionType::ExtInfo EI(getDefaultCallingConvention(
9629 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
John McCall991eb4b2010-12-21 00:44:39 +00009630 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9631
John McCall991eb4b2010-12-21 00:44:39 +00009632
Richard Smith836de6b2016-12-19 23:59:34 +00009633 // We really shouldn't be making a no-proto type here.
9634 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009635 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009636
John McCalldb40c7f2010-12-14 08:05:40 +00009637 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009638 EPI.ExtInfo = EI;
9639 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009640 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9641 EPI.ExceptionSpec.Type =
9642 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009643
Jordan Rose5c382722013-03-08 21:51:21 +00009644 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009645}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009646
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009647static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9648 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009649 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009650 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009651
Richard Smithe2467b72017-11-16 23:54:56 +00009652 // Non-user-provided functions get emitted as weak definitions with every
9653 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009654 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009655 if (!MD->isUserProvided())
9656 return GVA_DiscardableODR;
9657
Yaron Keren4cd211b2017-02-22 14:32:39 +00009658 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009659 switch (FD->getTemplateSpecializationKind()) {
9660 case TSK_Undeclared:
9661 case TSK_ExplicitSpecialization:
9662 External = GVA_StrongExternal;
9663 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009664
Rafael Espindola3ae00052013-05-13 00:12:11 +00009665 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009666 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009667
David Majnemerc3d07332014-05-15 06:25:57 +00009668 // C++11 [temp.explicit]p10:
9669 // [ Note: The intent is that an inline function that is the subject of
9670 // an explicit instantiation declaration will still be implicitly
9671 // instantiated when used so that the body can be considered for
9672 // inlining, but that no out-of-line copy of the inline function would be
9673 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009674 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009675 return GVA_AvailableExternally;
9676
Rafael Espindola3ae00052013-05-13 00:12:11 +00009677 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009678 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009679 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009680 }
9681
9682 if (!FD->isInlined())
9683 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009684
David Majnemer3f021502015-10-08 04:53:31 +00009685 if ((!Context.getLangOpts().CPlusPlus &&
9686 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009687 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009688 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009689 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9690
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009691 // GNU or C99 inline semantics. Determine whether this symbol should be
9692 // externally visible.
9693 if (FD->isInlineDefinitionExternallyVisible())
9694 return External;
9695
9696 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009697 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009698 }
9699
David Majnemer54e3ba52014-04-02 23:17:29 +00009700 // Functions specified with extern and inline in -fms-compatibility mode
9701 // forcibly get emitted. While the body of the function cannot be later
9702 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009703 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009704 return GVA_StrongODR;
9705
David Majnemer27d69db2014-04-28 22:17:59 +00009706 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009707}
9708
Artem Belevichca2b9512016-05-02 20:30:03 +00009709static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009710 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009711 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9712 // dllexport/dllimport on inline functions.
9713 if (D->hasAttr<DLLImportAttr>()) {
9714 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9715 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009716 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009717 if (L == GVA_DiscardableODR)
9718 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009719 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9720 D->hasAttr<CUDAGlobalAttr>()) {
9721 // Device-side functions with __global__ attribute must always be
9722 // visible externally so they can be launched from host.
9723 if (L == GVA_DiscardableODR || L == GVA_Internal)
9724 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009725 }
9726 return L;
9727}
9728
Richard Smitha4653622017-09-06 20:01:14 +00009729/// Adjust the GVALinkage for a declaration based on what an external AST source
9730/// knows about whether there can be other definitions of this declaration.
9731static GVALinkage
9732adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9733 GVALinkage L) {
9734 ExternalASTSource *Source = Ctx.getExternalSource();
9735 if (!Source)
9736 return L;
9737
9738 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009739 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009740 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009741 if (L == GVA_DiscardableODR)
9742 return GVA_StrongODR;
9743 break;
Richard Smitha4653622017-09-06 20:01:14 +00009744
David Blaikie9ffe5a32017-01-30 05:00:26 +00009745 case ExternalASTSource::EK_Always:
9746 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009747
David Blaikie9ffe5a32017-01-30 05:00:26 +00009748 case ExternalASTSource::EK_ReplyHazy:
9749 break;
9750 }
9751 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009752}
9753
Richard Smitha4653622017-09-06 20:01:14 +00009754GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9755 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9756 adjustGVALinkageForAttributes(*this, FD,
9757 basicGVALinkageForFunction(*this, FD)));
9758}
9759
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009760static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9761 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009762 if (!VD->isExternallyVisible())
9763 return GVA_Internal;
9764
David Majnemer27d69db2014-04-28 22:17:59 +00009765 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009766 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9767 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9768 LexicalContext = LexicalContext->getLexicalParent();
9769
David Blaikieeb210012017-01-27 23:11:10 +00009770 // ObjC Blocks can create local variables that don't have a FunctionDecl
9771 // LexicalContext.
9772 if (!LexicalContext)
9773 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009774
David Blaikieeb210012017-01-27 23:11:10 +00009775 // Otherwise, let the static local variable inherit its linkage from the
9776 // nearest enclosing function.
9777 auto StaticLocalLinkage =
9778 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9779
9780 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9781 // be emitted in any object with references to the symbol for the object it
9782 // contains, whether inline or out-of-line."
9783 // Similar behavior is observed with MSVC. An alternative ABI could use
9784 // StrongODR/AvailableExternally to match the function, but none are
9785 // known/supported currently.
9786 if (StaticLocalLinkage == GVA_StrongODR ||
9787 StaticLocalLinkage == GVA_AvailableExternally)
9788 return GVA_DiscardableODR;
9789 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009790 }
9791
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009792 // MSVC treats in-class initialized static data members as definitions.
9793 // By giving them non-strong linkage, out-of-line definitions won't
9794 // cause link errors.
9795 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9796 return GVA_DiscardableODR;
9797
Richard Smithd9b90092016-07-02 01:32:16 +00009798 // Most non-template variables have strong linkage; inline variables are
9799 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9800 GVALinkage StrongLinkage;
9801 switch (Context.getInlineVariableDefinitionKind(VD)) {
9802 case ASTContext::InlineVariableDefinitionKind::None:
9803 StrongLinkage = GVA_StrongExternal;
9804 break;
9805 case ASTContext::InlineVariableDefinitionKind::Weak:
9806 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009807 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009808 break;
9809 case ASTContext::InlineVariableDefinitionKind::Strong:
9810 StrongLinkage = GVA_StrongODR;
9811 break;
9812 }
Richard Smith62f19e72016-06-25 00:15:56 +00009813
Richard Smith8809a0c2013-09-27 20:14:12 +00009814 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009815 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009816 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009817
David Majnemer6d1780c2015-07-17 23:36:49 +00009818 case TSK_ExplicitSpecialization:
Reid Klecknere6f2ff22019-06-26 21:16:51 +00009819 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9820 VD->isStaticDataMember()
9821 ? GVA_StrongODR
9822 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009823
Rafael Espindola3ae00052013-05-13 00:12:11 +00009824 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009825 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009826
David Majnemer27d69db2014-04-28 22:17:59 +00009827 case TSK_ExplicitInstantiationDeclaration:
9828 return GVA_AvailableExternally;
9829
Rafael Espindola3ae00052013-05-13 00:12:11 +00009830 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009831 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009832 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009833
9834 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009835}
9836
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009837GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009838 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9839 adjustGVALinkageForAttributes(*this, VD,
9840 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009841}
9842
David Blaikiee6b7c282017-04-11 20:46:34 +00009843bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009844 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009845 if (!VD->isFileVarDecl())
9846 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009847 // Global named register variables (GNU extension) are never emitted.
9848 if (VD->getStorageClass() == SC_Register)
9849 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009850 if (VD->getDescribedVarTemplate() ||
9851 isa<VarTemplatePartialSpecializationDecl>(VD))
9852 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009853 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +00009854 // We never need to emit an uninstantiated function template.
9855 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9856 return false;
Nico Weber66220292016-03-02 17:28:48 +00009857 } else if (isa<PragmaCommentDecl>(D))
9858 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009859 else if (isa<PragmaDetectMismatchDecl>(D))
9860 return true;
Nico Weber66220292016-03-02 17:28:48 +00009861 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009862 return !D->getDeclContext()->isDependentContext();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009863 else if (isa<OMPAllocateDecl>(D))
9864 return !D->getDeclContext()->isDependentContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009865 else if (isa<OMPDeclareReductionDecl>(D))
9866 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009867 else if (isa<ImportDecl>(D))
9868 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009869 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009870 return false;
9871
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009872 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9873 assert(getExternalSource() && "It's from an AST file; must have a source.");
9874 // On Windows, PCH files are built together with an object file. If this
9875 // declaration comes from such a PCH and DeclMustBeEmitted would return
9876 // true, it would have returned true and the decl would have been emitted
9877 // into that object file, so it doesn't need to be emitted here.
9878 // Note that decls are still emitted if they're referenced, as usual;
9879 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9880 // if it's not referenced.
9881 //
9882 // Explicit template instantiation definitions are tricky. If there was an
9883 // explicit template instantiation decl in the PCH before, it will look like
9884 // the definition comes from there, even if that was just the declaration.
9885 // (Explicit instantiation defs of variable templates always get emitted.)
9886 bool IsExpInstDef =
9887 isa<FunctionDecl>(D) &&
9888 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
9889 TSK_ExplicitInstantiationDefinition;
9890
Hans Wennborgb51a7032018-09-14 15:18:30 +00009891 // Implicit member function definitions, such as operator= might not be
9892 // marked as template specializations, since they're not coming from a
9893 // template but synthesized directly on the class.
9894 IsExpInstDef |=
9895 isa<CXXMethodDecl>(D) &&
9896 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
9897 TSK_ExplicitInstantiationDefinition;
9898
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009899 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
9900 return false;
9901 }
9902
Richard Smith5205a8c2013-04-01 20:22:16 +00009903 // If this is a member of a class template, we do not need to emit it.
9904 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009905 return false;
9906
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009907 // Weak references don't produce any output by themselves.
9908 if (D->hasAttr<WeakRefAttr>())
9909 return false;
9910
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009911 // Aliases and used decls are required.
9912 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9913 return true;
9914
Eugene Zelenko7855e772018-04-03 00:11:50 +00009915 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009916 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009917 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009918 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009919
9920 // Constructors and destructors are required.
9921 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9922 return true;
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009923
John McCall6bd2a892013-01-25 22:31:03 +00009924 // The key function for a class is required. This rule only comes
9925 // into play when inline functions can be key functions, though.
9926 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009927 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +00009928 const CXXRecordDecl *RD = MD->getParent();
9929 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9930 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9931 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9932 return true;
9933 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009934 }
9935 }
9936
David Blaikie9ffe5a32017-01-30 05:00:26 +00009937 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9938
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009939 // static, static inline, always_inline, and extern inline functions can
9940 // always be deferred. Normal inline functions can be deferred in C99/C++.
9941 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009942 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009943 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009944
Eugene Zelenko7855e772018-04-03 00:11:50 +00009945 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009946 assert(VD->isFileVarDecl() && "Expected file scoped var");
9947
Alexey Bataevd01b7492018-08-15 19:45:12 +00009948 // If the decl is marked as `declare target to`, it should be emitted for the
9949 // host and for the device.
9950 if (LangOpts.OpenMP &&
9951 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
9952 return true;
9953
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009954 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9955 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009956 return false;
9957
Richard Smitha0e5e542012-11-12 21:38:00 +00009958 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009959 auto Linkage = GetGVALinkageForVariable(VD);
9960 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009961 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009962
Richard Smitha4653622017-09-06 20:01:14 +00009963 // We never need to emit a variable that is available in another TU.
9964 if (Linkage == GVA_AvailableExternally)
9965 return false;
9966
Richard Smitha0e5e542012-11-12 21:38:00 +00009967 // Variables that have destruction with side-effects are required.
9968 if (VD->getType().isDestructedType())
9969 return true;
9970
9971 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009972 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009973 // We can get a value-dependent initializer during error recovery.
9974 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009975 return true;
9976
Richard Smithda383632016-08-15 01:33:41 +00009977 // Likewise, variables with tuple-like bindings are required if their
9978 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009979 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
9980 for (const auto *BD : DD->bindings())
9981 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +00009982 if (DeclMustBeEmitted(BindingVD))
9983 return true;
9984
Richard Smitha0e5e542012-11-12 21:38:00 +00009985 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009986}
Charles Davis53c59df2010-08-16 03:33:14 +00009987
Erich Keane281d20b2018-01-08 21:34:17 +00009988void ASTContext::forEachMultiversionedFunctionVersion(
9989 const FunctionDecl *FD,
Erich Keane0fb16482018-08-13 18:33:20 +00009990 llvm::function_ref<void(FunctionDecl *)> Pred) const {
Erich Keane281d20b2018-01-08 21:34:17 +00009991 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
9992 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
Erich Keane7304f0a2018-11-28 20:58:43 +00009993 FD = FD->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00009994 for (auto *CurDecl :
9995 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
Erich Keane7304f0a2018-11-28 20:58:43 +00009996 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00009997 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
9998 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
9999 SeenDecls.insert(CurFD);
10000 Pred(CurFD);
10001 }
10002 }
10003}
10004
Reid Kleckner78af0702013-08-27 23:08:25 +000010005CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
Erich Keane00022812019-05-23 16:05:21 +000010006 bool IsCXXMethod,
10007 bool IsBuiltin) const {
Charles Davis99202b32010-11-09 18:04:24 +000010008 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +000010009 if (IsCXXMethod)
10010 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +000010011
Erich Keane00022812019-05-23 16:05:21 +000010012 // Builtins ignore user-specified default calling convention and remain the
10013 // Target's default calling convention.
10014 if (!IsBuiltin) {
10015 switch (LangOpts.getDefaultCallingConv()) {
10016 case LangOptions::DCC_None:
10017 break;
10018 case LangOptions::DCC_CDecl:
10019 return CC_C;
10020 case LangOptions::DCC_FastCall:
10021 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10022 return CC_X86FastCall;
10023 break;
10024 case LangOptions::DCC_StdCall:
10025 if (!IsVariadic)
10026 return CC_X86StdCall;
10027 break;
10028 case LangOptions::DCC_VectorCall:
10029 // __vectorcall cannot be applied to variadic functions.
10030 if (!IsVariadic)
10031 return CC_X86VectorCall;
10032 break;
10033 case LangOptions::DCC_RegCall:
10034 // __regcall cannot be applied to variadic functions.
10035 if (!IsVariadic)
10036 return CC_X86RegCall;
10037 break;
10038 }
Alexey Bataeva7547182016-05-18 09:06:38 +000010039 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000010040 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +000010041}
10042
Jay Foad39c79802011-01-12 09:06:06 +000010043bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +000010044 // Pass through to the C++ ABI object
10045 return ABI->isNearlyEmpty(RD);
10046}
10047
Reid Kleckner96f8f932014-02-05 17:27:08 +000010048VTableContextBase *ASTContext::getVTableContext() {
10049 if (!VTContext.get()) {
10050 if (Target->getCXXABI().isMicrosoft())
10051 VTContext.reset(new MicrosoftVTableContext(*this));
10052 else
10053 VTContext.reset(new ItaniumVTableContext(*this));
10054 }
10055 return VTContext.get();
10056}
10057
Yaxun Liuc18e9ec2019-02-14 02:00:09 +000010058MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10059 if (!T)
10060 T = Target;
10061 switch (T->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000010062 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +000010063 case TargetCXXABI::GenericItanium:
10064 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000010065 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +000010066 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000010067 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +000010068 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +000010069 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010070 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +000010071 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010072 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010073 }
David Blaikie83d382b2011-09-23 05:06:16 +000010074 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010075}
10076
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010077CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010078
10079size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +000010080 return ASTRecordLayouts.getMemorySize() +
10081 llvm::capacity_in_bytes(ObjCLayouts) +
10082 llvm::capacity_in_bytes(KeyFunctions) +
10083 llvm::capacity_in_bytes(ObjCImpls) +
10084 llvm::capacity_in_bytes(BlockVarCopyInits) +
10085 llvm::capacity_in_bytes(DeclAttrs) +
10086 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10087 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10088 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10089 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10090 llvm::capacity_in_bytes(OverriddenMethods) +
10091 llvm::capacity_in_bytes(Types) +
Richard Smithf19a8b02019-05-02 00:49:14 +000010092 llvm::capacity_in_bytes(VariableArrayTypes);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010093}
Ted Kremenek540017e2011-10-06 05:00:56 +000010094
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010095/// getIntTypeForBitwidth -
10096/// sets integer QualTy according to specified details:
10097/// bitwidth, signed/unsigned.
10098/// Returns empty type if there is no appropriate target types.
10099QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10100 unsigned Signed) const {
10101 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10102 CanQualType QualTy = getFromTargetType(Ty);
10103 if (!QualTy && DestWidth == 128)
10104 return Signed ? Int128Ty : UnsignedInt128Ty;
10105 return QualTy;
10106}
10107
10108/// getRealTypeForBitwidth -
10109/// sets floating point QualTy according to specified bitwidth.
10110/// Returns empty type if there is no appropriate target types.
10111QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
10112 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
10113 switch (Ty) {
10114 case TargetInfo::Float:
10115 return FloatTy;
10116 case TargetInfo::Double:
10117 return DoubleTy;
10118 case TargetInfo::LongDouble:
10119 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000010120 case TargetInfo::Float128:
10121 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010122 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +000010123 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010124 }
10125
10126 llvm_unreachable("Unhandled TargetInfo::RealType value");
10127}
10128
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010129void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10130 if (Number > 1)
10131 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +000010132}
10133
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010134unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010135 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010136 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +000010137}
10138
David Majnemer2206bf52014-03-05 08:57:59 +000010139void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10140 if (Number > 1)
10141 StaticLocalNumbers[VD] = Number;
10142}
10143
10144unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010145 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +000010146 return I != StaticLocalNumbers.end() ? I->second : 1;
10147}
10148
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010149MangleNumberingContext &
10150ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010151 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +000010152 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +000010153 if (!MCtx)
10154 MCtx = createMangleNumberingContext();
10155 return *MCtx;
10156}
10157
Justin Lebar20ebffc2016-10-10 16:26:19 +000010158std::unique_ptr<MangleNumberingContext>
10159ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010160 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +000010161}
10162
David Majnemere7a818f2015-03-06 18:53:55 +000010163const CXXConstructorDecl *
10164ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10165 return ABI->getCopyConstructorForExceptionObject(
10166 cast<CXXRecordDecl>(RD->getFirstDecl()));
10167}
10168
10169void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10170 CXXConstructorDecl *CD) {
10171 return ABI->addCopyConstructorForExceptionObject(
10172 cast<CXXRecordDecl>(RD->getFirstDecl()),
10173 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10174}
10175
David Majnemer00350522015-08-31 18:48:39 +000010176void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10177 TypedefNameDecl *DD) {
10178 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10179}
10180
10181TypedefNameDecl *
10182ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10183 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10184}
10185
10186void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10187 DeclaratorDecl *DD) {
10188 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10189}
10190
10191DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10192 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10193}
10194
Ted Kremenek540017e2011-10-06 05:00:56 +000010195void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10196 ParamIndices[D] = index;
10197}
10198
10199unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10200 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
Fangrui Song6907ce22018-07-30 19:24:48 +000010201 assert(I != ParamIndices.end() &&
Ted Kremenek540017e2011-10-06 05:00:56 +000010202 "ParmIndices lacks entry set by ParmVarDecl");
10203 return I->second;
10204}
Fariborz Jahanian615de762013-05-28 17:37:39 +000010205
Richard Smithe6c01442013-06-05 00:46:14 +000010206APValue *
10207ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
10208 bool MayCreate) {
10209 assert(E && E->getStorageDuration() == SD_Static &&
10210 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +000010211 if (MayCreate) {
10212 APValue *&MTVI = MaterializedTemporaryValues[E];
10213 if (!MTVI)
10214 MTVI = new (*this) APValue;
10215 return MTVI;
10216 }
Richard Smithe6c01442013-06-05 00:46:14 +000010217
David Majnemer2dcef9e2015-08-13 23:50:15 +000010218 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +000010219}
10220
Eric Fiselier708afb52019-05-16 21:04:15 +000010221QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
10222 unsigned Length) const {
10223 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
10224 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
10225 EltTy = EltTy.withConst();
10226
10227 EltTy = adjustStringLiteralBaseType(EltTy);
10228
10229 // Get an array type for the string, according to C99 6.4.5. This includes
10230 // the null terminator character.
10231 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1),
10232 ArrayType::Normal, /*IndexTypeQuals*/ 0);
10233}
10234
10235StringLiteral *
10236ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
10237 StringLiteral *&Result = StringLiteralCache[Key];
10238 if (!Result)
10239 Result = StringLiteral::Create(
10240 *this, Key, StringLiteral::Ascii,
10241 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
10242 SourceLocation());
10243 return Result;
10244}
10245
Fariborz Jahanian615de762013-05-28 17:37:39 +000010246bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10247 const llvm::Triple &T = getTargetInfo().getTriple();
10248 if (!T.isOSDarwin())
10249 return false;
10250
Bob Wilson2c82c3d2013-11-02 23:27:49 +000010251 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10252 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10253 return false;
10254
Fariborz Jahanian615de762013-05-28 17:37:39 +000010255 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10256 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10257 uint64_t Size = sizeChars.getQuantity();
10258 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10259 unsigned Align = alignChars.getQuantity();
10260 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10261 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10262}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010263
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010264/// Template specializations to abstract away from pointers and TypeLocs.
10265/// @{
10266template <typename T>
Sam McCall814e7972018-11-14 10:33:30 +000010267static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010268 return ast_type_traits::DynTypedNode::create(*Node);
10269}
10270template <>
10271ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10272 return ast_type_traits::DynTypedNode::create(Node);
10273}
10274template <>
10275ast_type_traits::DynTypedNode
10276createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10277 return ast_type_traits::DynTypedNode::create(Node);
10278}
10279/// @}
10280
Sam McCall814e7972018-11-14 10:33:30 +000010281/// A \c RecursiveASTVisitor that builds a map from nodes to their
10282/// parents as defined by the \c RecursiveASTVisitor.
10283///
10284/// Note that the relationship described here is purely in terms of AST
10285/// traversal - there are other relationships (for example declaration context)
10286/// in the AST that are better modeled by special matchers.
10287///
10288/// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10289class ASTContext::ParentMap::ASTVisitor
10290 : public RecursiveASTVisitor<ASTVisitor> {
10291public:
10292 ASTVisitor(ParentMap &Map) : Map(Map) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010293
Sam McCall814e7972018-11-14 10:33:30 +000010294private:
10295 friend class RecursiveASTVisitor<ASTVisitor>;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010296
Sam McCall814e7972018-11-14 10:33:30 +000010297 using VisitorBase = RecursiveASTVisitor<ASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010298
Sam McCall814e7972018-11-14 10:33:30 +000010299 bool shouldVisitTemplateInstantiations() const { return true; }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010300
Sam McCall814e7972018-11-14 10:33:30 +000010301 bool shouldVisitImplicitCode() const { return true; }
10302
10303 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10304 typename MapTy>
10305 bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
10306 MapTy *Parents) {
10307 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010308 return true;
Sam McCall814e7972018-11-14 10:33:30 +000010309 if (ParentStack.size() > 0) {
10310 // FIXME: Currently we add the same parent multiple times, but only
10311 // when no memoization data is available for the type.
10312 // For example when we visit all subexpressions of template
10313 // instantiations; this is suboptimal, but benign: the only way to
10314 // visit those is with hasAncestor / hasParent, and those do not create
10315 // new matches.
10316 // The plan is to enable DynTypedNode to be storable in a map or hash
10317 // map. The main problem there is to implement hash functions /
10318 // comparison operators for all types that DynTypedNode supports that
10319 // do not have pointer identity.
10320 auto &NodeOrVector = (*Parents)[MapNode];
10321 if (NodeOrVector.isNull()) {
10322 if (const auto *D = ParentStack.back().get<Decl>())
10323 NodeOrVector = D;
10324 else if (const auto *S = ParentStack.back().get<Stmt>())
10325 NodeOrVector = S;
10326 else
10327 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
10328 } else {
10329 if (!NodeOrVector.template is<ParentVector *>()) {
10330 auto *Vector = new ParentVector(
10331 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10332 delete NodeOrVector
10333 .template dyn_cast<ast_type_traits::DynTypedNode *>();
10334 NodeOrVector = Vector;
Manuel Klimek95403e62014-05-21 13:28:59 +000010335 }
Sam McCall814e7972018-11-14 10:33:30 +000010336
10337 auto *Vector = NodeOrVector.template get<ParentVector *>();
10338 // Skip duplicates for types that have memoization data.
10339 // We must check that the type has memoization data before calling
10340 // std::find() because DynTypedNode::operator== can't compare all
10341 // types.
10342 bool Found = ParentStack.back().getMemoizationData() &&
10343 std::find(Vector->begin(), Vector->end(),
10344 ParentStack.back()) != Vector->end();
10345 if (!Found)
10346 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010347 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010348 }
Sam McCall814e7972018-11-14 10:33:30 +000010349 ParentStack.push_back(createDynTypedNode(Node));
10350 bool Result = BaseTraverse();
10351 ParentStack.pop_back();
10352 return Result;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010353 }
Sam McCall814e7972018-11-14 10:33:30 +000010354
10355 bool TraverseDecl(Decl *DeclNode) {
10356 return TraverseNode(
10357 DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
10358 &Map.PointerParents);
Manuel Klimek95403e62014-05-21 13:28:59 +000010359 }
Sam McCall814e7972018-11-14 10:33:30 +000010360
10361 bool TraverseStmt(Stmt *StmtNode) {
10362 return TraverseNode(
10363 StmtNode, StmtNode, [&] { return VisitorBase::TraverseStmt(StmtNode); },
10364 &Map.PointerParents);
10365 }
10366
10367 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10368 return TraverseNode(
10369 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10370 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10371 &Map.OtherParents);
10372 }
10373
10374 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10375 return TraverseNode(
10376 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10377 [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
10378 &Map.OtherParents);
10379 }
10380
10381 ParentMap &Map;
10382 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
10383};
10384
10385ASTContext::ParentMap::ParentMap(ASTContext &Ctx) {
10386 ASTVisitor(*this).TraverseAST(Ctx);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010387}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010388
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010389ASTContext::DynTypedNodeList
10390ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
Sam McCall814e7972018-11-14 10:33:30 +000010391 if (!Parents)
10392 // We build the parent map for the traversal scope (usually whole TU), as
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010393 // hasAncestor can escape any subtree.
Sam McCall814e7972018-11-14 10:33:30 +000010394 Parents = llvm::make_unique<ParentMap>(*this);
10395 return Parents->getParents(Node);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010396}
10397
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010398bool
10399ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10400 const ObjCMethodDecl *MethodImpl) {
10401 // No point trying to match an unavailable/deprecated mothod.
10402 if (MethodDecl->hasAttr<UnavailableAttr>()
10403 || MethodDecl->hasAttr<DeprecatedAttr>())
10404 return false;
10405 if (MethodDecl->getObjCDeclQualifier() !=
10406 MethodImpl->getObjCDeclQualifier())
10407 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010408 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010409 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010410
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010411 if (MethodDecl->param_size() != MethodImpl->param_size())
10412 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010413
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010414 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10415 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10416 EF = MethodDecl->param_end();
10417 IM != EM && IF != EF; ++IM, ++IF) {
10418 const ParmVarDecl *DeclVar = (*IF);
10419 const ParmVarDecl *ImplVar = (*IM);
10420 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10421 return false;
10422 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10423 return false;
10424 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010425
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010426 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010427}
Richard Smith053f6c62014-05-16 23:01:30 +000010428
Yaxun Liu402804b2016-12-15 08:09:08 +000010429uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010430 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010431 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010432 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010433 else
10434 AS = QT->getPointeeType().getAddressSpace();
10435
10436 return getTargetInfo().getNullPointerValue(AS);
10437}
10438
Alexander Richardson6d989432017-10-15 18:48:14 +000010439unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10440 if (isTargetAddressSpace(AS))
10441 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010442 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010443 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010444}
10445
Leonard Chanab80f3c2018-06-14 14:53:51 +000010446QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10447 assert(Ty->isFixedPointType());
10448
10449 if (Ty->isSaturatedFixedPointType()) return Ty;
10450
10451 const auto &BT = Ty->getAs<BuiltinType>();
10452 switch (BT->getKind()) {
10453 default:
10454 llvm_unreachable("Not a fixed point type!");
10455 case BuiltinType::ShortAccum:
10456 return SatShortAccumTy;
10457 case BuiltinType::Accum:
10458 return SatAccumTy;
10459 case BuiltinType::LongAccum:
10460 return SatLongAccumTy;
10461 case BuiltinType::UShortAccum:
10462 return SatUnsignedShortAccumTy;
10463 case BuiltinType::UAccum:
10464 return SatUnsignedAccumTy;
10465 case BuiltinType::ULongAccum:
10466 return SatUnsignedLongAccumTy;
10467 case BuiltinType::ShortFract:
10468 return SatShortFractTy;
10469 case BuiltinType::Fract:
10470 return SatFractTy;
10471 case BuiltinType::LongFract:
10472 return SatLongFractTy;
10473 case BuiltinType::UShortFract:
10474 return SatUnsignedShortFractTy;
10475 case BuiltinType::UFract:
10476 return SatUnsignedFractTy;
10477 case BuiltinType::ULongFract:
10478 return SatUnsignedLongFractTy;
10479 }
10480}
10481
Matt Arsenaultc65f9662018-08-02 12:14:28 +000010482LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10483 if (LangOpts.OpenCL)
10484 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10485
10486 if (LangOpts.CUDA)
10487 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10488
10489 return getLangASFromTargetAS(AS);
10490}
10491
Richard Smith053f6c62014-05-16 23:01:30 +000010492// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10493// doesn't include ASTContext.h
10494template
10495clang::LazyGenerationalUpdatePtr<
10496 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10497clang::LazyGenerationalUpdatePtr<
10498 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10499 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010500
10501unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10502 assert(Ty->isFixedPointType());
10503
10504 const auto *BT = Ty->getAs<BuiltinType>();
10505 const TargetInfo &Target = getTargetInfo();
10506 switch (BT->getKind()) {
10507 default:
10508 llvm_unreachable("Not a fixed point type!");
10509 case BuiltinType::ShortAccum:
10510 case BuiltinType::SatShortAccum:
10511 return Target.getShortAccumScale();
10512 case BuiltinType::Accum:
10513 case BuiltinType::SatAccum:
10514 return Target.getAccumScale();
10515 case BuiltinType::LongAccum:
10516 case BuiltinType::SatLongAccum:
10517 return Target.getLongAccumScale();
10518 case BuiltinType::UShortAccum:
10519 case BuiltinType::SatUShortAccum:
10520 return Target.getUnsignedShortAccumScale();
10521 case BuiltinType::UAccum:
10522 case BuiltinType::SatUAccum:
10523 return Target.getUnsignedAccumScale();
10524 case BuiltinType::ULongAccum:
10525 case BuiltinType::SatULongAccum:
10526 return Target.getUnsignedLongAccumScale();
10527 case BuiltinType::ShortFract:
10528 case BuiltinType::SatShortFract:
10529 return Target.getShortFractScale();
10530 case BuiltinType::Fract:
10531 case BuiltinType::SatFract:
10532 return Target.getFractScale();
10533 case BuiltinType::LongFract:
10534 case BuiltinType::SatLongFract:
10535 return Target.getLongFractScale();
10536 case BuiltinType::UShortFract:
10537 case BuiltinType::SatUShortFract:
10538 return Target.getUnsignedShortFractScale();
10539 case BuiltinType::UFract:
10540 case BuiltinType::SatUFract:
10541 return Target.getUnsignedFractScale();
10542 case BuiltinType::ULongFract:
10543 case BuiltinType::SatULongFract:
10544 return Target.getUnsignedLongFractScale();
10545 }
10546}
10547
10548unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10549 assert(Ty->isFixedPointType());
10550
10551 const auto *BT = Ty->getAs<BuiltinType>();
10552 const TargetInfo &Target = getTargetInfo();
10553 switch (BT->getKind()) {
10554 default:
10555 llvm_unreachable("Not a fixed point type!");
10556 case BuiltinType::ShortAccum:
10557 case BuiltinType::SatShortAccum:
10558 return Target.getShortAccumIBits();
10559 case BuiltinType::Accum:
10560 case BuiltinType::SatAccum:
10561 return Target.getAccumIBits();
10562 case BuiltinType::LongAccum:
10563 case BuiltinType::SatLongAccum:
10564 return Target.getLongAccumIBits();
10565 case BuiltinType::UShortAccum:
10566 case BuiltinType::SatUShortAccum:
10567 return Target.getUnsignedShortAccumIBits();
10568 case BuiltinType::UAccum:
10569 case BuiltinType::SatUAccum:
10570 return Target.getUnsignedAccumIBits();
10571 case BuiltinType::ULongAccum:
10572 case BuiltinType::SatULongAccum:
10573 return Target.getUnsignedLongAccumIBits();
10574 case BuiltinType::ShortFract:
10575 case BuiltinType::SatShortFract:
10576 case BuiltinType::Fract:
10577 case BuiltinType::SatFract:
10578 case BuiltinType::LongFract:
10579 case BuiltinType::SatLongFract:
10580 case BuiltinType::UShortFract:
10581 case BuiltinType::SatUShortFract:
10582 case BuiltinType::UFract:
10583 case BuiltinType::SatUFract:
10584 case BuiltinType::ULongFract:
10585 case BuiltinType::SatULongFract:
10586 return 0;
10587 }
10588}
Leonard Chana6779422018-08-06 16:42:37 +000010589
10590FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
Erich Keane8e772162019-01-18 19:31:54 +000010591 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
10592 "Can only get the fixed point semantics for a "
10593 "fixed point or integer type.");
Leonard Chan2044ac82019-01-16 18:13:59 +000010594 if (Ty->isIntegerType())
10595 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
10596 Ty->isSignedIntegerType());
10597
Leonard Chana6779422018-08-06 16:42:37 +000010598 bool isSigned = Ty->isSignedFixedPointType();
10599 return FixedPointSemantics(
10600 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10601 Ty->isSaturatedFixedPointType(),
10602 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10603}
10604
10605APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10606 assert(Ty->isFixedPointType());
10607 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10608}
10609
10610APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10611 assert(Ty->isFixedPointType());
10612 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10613}
Leonard Chan2044ac82019-01-16 18:13:59 +000010614
10615QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
10616 assert(Ty->isUnsignedFixedPointType() &&
10617 "Expected unsigned fixed point type");
10618 const auto *BTy = Ty->getAs<BuiltinType>();
10619
10620 switch (BTy->getKind()) {
10621 case BuiltinType::UShortAccum:
10622 return ShortAccumTy;
10623 case BuiltinType::UAccum:
10624 return AccumTy;
10625 case BuiltinType::ULongAccum:
10626 return LongAccumTy;
10627 case BuiltinType::SatUShortAccum:
10628 return SatShortAccumTy;
10629 case BuiltinType::SatUAccum:
10630 return SatAccumTy;
10631 case BuiltinType::SatULongAccum:
10632 return SatLongAccumTy;
10633 case BuiltinType::UShortFract:
10634 return ShortFractTy;
10635 case BuiltinType::UFract:
10636 return FractTy;
10637 case BuiltinType::ULongFract:
10638 return LongFractTy;
10639 case BuiltinType::SatUShortFract:
10640 return SatShortFractTy;
10641 case BuiltinType::SatUFract:
10642 return SatFractTy;
10643 case BuiltinType::SatULongFract:
10644 return SatLongFractTy;
10645 default:
10646 llvm_unreachable("Unexpected unsigned fixed point type");
10647 }
10648}