blob: ca54d8f67598b511a6a6480f6e85a2afdaad0f18 [file] [log] [blame]
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
Chris Lattnerddc135e2006-11-10 06:34:16 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000016#include "clang/AST/APValue.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/ASTMutationListener.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000018#include "clang/AST/ASTTypeTraits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Attr.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000020#include "clang/AST/AttrIterator.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000021#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000022#include "clang/AST/Comment.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000023#include "clang/AST/Decl.h"
24#include "clang/AST/DeclBase.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000025#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000026#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000027#include "clang/AST/DeclObjC.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000028#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000029#include "clang/AST/DeclTemplate.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000030#include "clang/AST/DeclarationName.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000031#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000032#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000033#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000034#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000035#include "clang/AST/MangleNumberingContext.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000036#include "clang/AST/NestedNameSpecifier.h"
37#include "clang/AST/RawCommentList.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000038#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000039#include "clang/AST/RecursiveASTVisitor.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000040#include "clang/AST/Stmt.h"
41#include "clang/AST/TemplateBase.h"
42#include "clang/AST/TemplateName.h"
43#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000044#include "clang/AST/TypeLoc.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000045#include "clang/AST/UnresolvedSet.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000046#include "clang/AST/VTableBuilder.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000047#include "clang/Basic/AddressSpaces.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000048#include "clang/Basic/Builtins.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000049#include "clang/Basic/CommentOptions.h"
Eugene Zelenko7855e772018-04-03 00:11:50 +000050#include "clang/Basic/ExceptionSpecificationType.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
Douglas Gregor9672f922010-07-03 00:47:00 +000097unsigned ASTContext::NumImplicitDefaultConstructors;
98unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000099unsigned ASTContext::NumImplicitCopyConstructors;
100unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000101unsigned ASTContext::NumImplicitMoveConstructors;
102unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000103unsigned ASTContext::NumImplicitCopyAssignmentOperators;
104unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000105unsigned ASTContext::NumImplicitMoveAssignmentOperators;
106unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +0000107unsigned ASTContext::NumImplicitDestructors;
108unsigned ASTContext::NumImplicitDestructorsDeclared;
109
Steve Naroff0af91202007-04-27 21:51:21 +0000110enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +0000111 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +0000112};
113
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000114RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000115 if (!CommentsLoaded && ExternalSource) {
116 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +0000117
118#ifndef NDEBUG
119 ArrayRef<RawComment *> RawComments = Comments.getComments();
120 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
121 BeforeThanCompare<RawComment>(SourceMgr)));
122#endif
123
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000124 CommentsLoaded = true;
125 }
126
127 assert(D);
128
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000129 // User can not attach documentation to implicit declarations.
130 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +0000131 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000132
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000133 // User can not attach documentation to implicit instantiations.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000134 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000135 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000136 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000137 }
138
Eugene Zelenko7855e772018-04-03 00:11:50 +0000139 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000140 if (VD->isStaticDataMember() &&
141 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000142 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000143 }
144
Eugene Zelenko7855e772018-04-03 00:11:50 +0000145 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000146 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000147 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000148 }
149
Eugene Zelenko7855e772018-04-03 00:11:50 +0000150 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000151 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
152 if (TSK == TSK_ImplicitInstantiation ||
153 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000154 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000155 }
156
Eugene Zelenko7855e772018-04-03 00:11:50 +0000157 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000158 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000159 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000160 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000161 if (const auto *TD = dyn_cast<TagDecl>(D)) {
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000162 // When tag declaration (but not definition!) is part of the
163 // decl-specifier-seq of some other declaration, it doesn't get comment
164 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000165 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000166 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // TODO: handle comments for function parameters properly.
168 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000169 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000170
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000171 // TODO: we could look up template parameter documentation in the template
172 // documentation.
173 if (isa<TemplateTypeParmDecl>(D) ||
174 isa<NonTypeTemplateParmDecl>(D) ||
175 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000176 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000177
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000178 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000179
180 // If there are no comments anywhere, we won't find anything.
181 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000182 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000183
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000184 // Find declaration location.
185 // For Objective-C declarations we generally don't expect to have multiple
186 // declarators, thus use declaration starting location as the "declaration
187 // location".
188 // For all other declarations multiple declarators are used quite frequently,
189 // so we use the location of the identifier as the "declaration location".
190 SourceLocation DeclLoc;
191 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000192 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000193 isa<RedeclarableTemplateDecl>(D) ||
194 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000195 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000196 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000197 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000198 if (DeclLoc.isMacroID()) {
199 if (isa<TypedefDecl>(D)) {
200 // If location of the typedef name is in a macro, it is because being
201 // declared via a macro. Try using declaration's starting location as
202 // the "declaration location".
203 DeclLoc = D->getLocStart();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000204 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000205 // If location of the tag decl is inside a macro, but the spelling of
206 // the tag name comes from a macro argument, it looks like a special
207 // macro like NS_ENUM is being used to define the tag decl. In that
208 // case, adjust the source location to the expansion loc so that we can
209 // attach the comment to the tag decl.
210 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
211 TD->isCompleteDefinition())
212 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
213 }
214 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000215 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000216
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000217 // If the declaration doesn't map directly to a location in a file, we
218 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000219 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000220 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000221
222 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000223 ArrayRef<RawComment *>::iterator Comment;
224 {
225 // When searching for comments during parsing, the comment we are looking
226 // for is usually among the last two comments we parsed -- check them
227 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000228 RawComment CommentAtDeclLoc(
David L. Jones13d5a872018-03-02 00:07:45 +0000229 SourceMgr, SourceRange(DeclLoc), LangOpts.CommentOpts, false);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000230 BeforeThanCompare<RawComment> Compare(SourceMgr);
231 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
232 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
233 if (!Found && RawComments.size() >= 2) {
234 MaybeBeforeDecl--;
235 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
236 }
237
238 if (Found) {
239 Comment = MaybeBeforeDecl + 1;
240 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
241 &CommentAtDeclLoc, Compare));
242 } else {
243 // Slow path.
244 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
245 &CommentAtDeclLoc, Compare);
246 }
247 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000248
249 // Decompose the location for the declaration and find the beginning of the
250 // file buffer.
251 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
252
253 // First check whether we have a trailing comment.
254 if (Comment != RawComments.end() &&
David L. Jones13d5a872018-03-02 00:07:45 +0000255 ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
256 && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000257 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000258 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000259 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000260 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000261 // Check that Doxygen trailing comment comes after the declaration, starts
262 // on the same line and in the same file as the declaration.
263 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
264 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
265 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
266 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000267 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000268 }
269 }
270
271 // The comment just after the declaration was not a trailing comment.
272 // Let's look at the previous comment.
273 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000274 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000275 --Comment;
276
277 // Check that we actually have a non-member Doxygen comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000278 if (!((*Comment)->isDocumentation() ||
279 LangOpts.CommentOpts.ParseAllComments) ||
280 (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000281 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000282
283 // Decompose the end of the comment.
284 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000285 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000286
287 // If the comment and the declaration aren't in the same file, then they
288 // aren't related.
289 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000290 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000291
292 // Get the corresponding buffer.
293 bool Invalid = false;
294 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
295 &Invalid).data();
296 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000297 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000298
299 // Extract text between the comment and declaration.
300 StringRef Text(Buffer + CommentEndDecomp.second,
301 DeclLocDecomp.second - CommentEndDecomp.second);
302
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000303 // There should be no other declarations or preprocessor directives between
304 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000305 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000306 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000307
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000308 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000309}
310
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000311/// If we have a 'templated' declaration for a template, adjust 'D' to
312/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000313/// If we have an implicit instantiation, adjust 'D' to refer to template.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000314static const Decl *adjustDeclToTemplate(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000315 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000316 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000317 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000318 return FTD;
319
320 // Nothing to do if function is not an implicit instantiation.
321 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
322 return D;
323
324 // Function is an implicit instantiation of a function template?
325 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
326 return FTD;
327
328 // Function is instantiated from a member definition of a class template?
329 if (const FunctionDecl *MemberDecl =
330 FD->getInstantiatedFromMemberFunction())
331 return MemberDecl;
332
333 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000334 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000335 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000336 // Static data member is instantiated from a member definition of a class
337 // template?
338 if (VD->isStaticDataMember())
339 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
340 return MemberDecl;
341
342 return D;
343 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000344 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000345 // Is this class declaration part of a class template?
346 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
347 return CTD;
348
349 // Class is an implicit instantiation of a class template or partial
350 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000351 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000352 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
353 return D;
354 llvm::PointerUnion<ClassTemplateDecl *,
355 ClassTemplatePartialSpecializationDecl *>
356 PU = CTSD->getSpecializedTemplateOrPartial();
357 return PU.is<ClassTemplateDecl*>() ?
358 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
359 static_cast<const Decl*>(
360 PU.get<ClassTemplatePartialSpecializationDecl *>());
361 }
362
363 // Class is instantiated from a member definition of a class template?
364 if (const MemberSpecializationInfo *Info =
365 CRD->getMemberSpecializationInfo())
366 return Info->getInstantiatedFrom();
367
368 return D;
369 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000370 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000371 // Enum is instantiated from a member definition of a class template?
372 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
373 return MemberDecl;
374
375 return D;
376 }
377 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000378 return D;
379}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000380
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000381const RawComment *ASTContext::getRawCommentForAnyRedecl(
382 const Decl *D,
383 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000384 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000385
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 // Check whether we have cached a comment for this declaration already.
387 {
388 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
389 RedeclComments.find(D);
390 if (Pos != RedeclComments.end()) {
391 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000392 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
393 if (OriginalDecl)
394 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000395 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000396 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000397 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000398 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000399
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000400 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000401 const RawComment *RC = nullptr;
402 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000403 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000404 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000405 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000406 if (Pos != RedeclComments.end()) {
407 const RawCommentAndCacheFlags &Raw = Pos->second;
408 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
409 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000410 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000411 break;
412 }
413 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000414 RC = getRawCommentForDeclNoCache(I);
415 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000416 RawCommentAndCacheFlags Raw;
417 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000418 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
419 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000420 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000421 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000422 } else
423 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000424 Raw.setOriginalDecl(I);
425 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000426 if (RC)
427 break;
428 }
429 }
430
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000431 // If we found a comment, it should be a documentation comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000432 assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000433
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000434 if (OriginalDecl)
435 *OriginalDecl = OriginalDeclForRC;
436
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000437 // Update cache for every declaration in the redeclaration chain.
438 RawCommentAndCacheFlags Raw;
439 Raw.setRaw(RC);
440 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000441 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000442
Aaron Ballman86c93902014-03-06 23:45:36 +0000443 for (auto I : D->redecls()) {
444 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000445 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
446 R = Raw;
447 }
448
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000449 return RC;
450}
451
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
453 SmallVectorImpl<const NamedDecl *> &Redeclared) {
454 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000455 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000456 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
457 if (!ID)
458 return;
459 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000460 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000462 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000463 ObjCMethod->isInstanceMethod()))
464 Redeclared.push_back(RedeclaredMethod);
465 }
466 }
467}
468
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000469comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
470 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000471 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000472 ThisDeclInfo->CommentDecl = D;
473 ThisDeclInfo->IsFilled = false;
474 ThisDeclInfo->fill();
475 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000476 if (!ThisDeclInfo->TemplateParameters)
477 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000478 comments::FullComment *CFC =
479 new (*this) comments::FullComment(FC->getBlocks(),
480 ThisDeclInfo);
481 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000482}
483
Richard Smithb39b9d52013-05-21 05:24:00 +0000484comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
485 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000486 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000487}
488
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000489comments::FullComment *ASTContext::getCommentForDecl(
490 const Decl *D,
491 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000492 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000493 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000494 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000495
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000496 const Decl *Canonical = D->getCanonicalDecl();
497 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
498 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000499
500 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000501 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000502 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000503 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000504 return CFC;
505 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000506 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000507 }
508
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000509 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000510
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000511 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000512 if (!RC) {
513 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000514 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000515 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000516 if (OMD && OMD->isPropertyAccessor())
517 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
518 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
519 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000520 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000521 addRedeclaredMethods(OMD, Overridden);
522 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000523 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
524 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
525 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000526 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000527 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000528 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000529 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000530 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000531 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000532 if (const Decl *TD = TT->getDecl())
533 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000534 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000535 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000536 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000537 while (IC->getSuperClass()) {
538 IC = IC->getSuperClass();
539 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
540 return cloneFullComment(FC, D);
541 }
542 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000543 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000544 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
545 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
546 return cloneFullComment(FC, D);
547 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000548 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000549 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000550 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000551 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000552 for (const auto &I : RD->bases()) {
553 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000554 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000555 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000556 if (Ty.isNull())
557 continue;
558 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
559 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
560 continue;
561
562 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
563 return cloneFullComment(FC, D);
564 }
565 }
566 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000567 for (const auto &I : RD->vbases()) {
568 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000569 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000570 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000571 if (Ty.isNull())
572 continue;
573 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
574 if (!(VirtualBase= VirtualBase->getDefinition()))
575 continue;
576 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
577 return cloneFullComment(FC, D);
578 }
579 }
580 }
Craig Topper36250ad2014-05-12 05:36:57 +0000581 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000582 }
583
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000584 // If the RawComment was attached to other redeclaration of this Decl, we
585 // should parse the comment in context of that other Decl. This is important
586 // because comments can contain references to parameter names which can be
587 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000588 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000589 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000590
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000591 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000592 ParsedComments[Canonical] = FC;
593 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000594}
595
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000596void
597ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
598 TemplateTemplateParmDecl *Parm) {
599 ID.AddInteger(Parm->getDepth());
600 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000601 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000602
603 TemplateParameterList *Params = Parm->getTemplateParameters();
604 ID.AddInteger(Params->size());
605 for (TemplateParameterList::const_iterator P = Params->begin(),
606 PEnd = Params->end();
607 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000608 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000609 ID.AddInteger(0);
610 ID.AddBoolean(TTP->isParameterPack());
611 continue;
612 }
613
Eugene Zelenko7855e772018-04-03 00:11:50 +0000614 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000615 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000616 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000617 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000618 if (NTTP->isExpandedParameterPack()) {
619 ID.AddBoolean(true);
620 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000621 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622 QualType T = NTTP->getExpansionType(I);
623 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
624 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000625 } else
626 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000627 continue;
628 }
629
Eugene Zelenko7855e772018-04-03 00:11:50 +0000630 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000631 ID.AddInteger(2);
632 Profile(ID, TTP);
633 }
634}
635
636TemplateTemplateParmDecl *
637ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000638 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000639 // Check if we already have a canonical template template parameter.
640 llvm::FoldingSetNodeID ID;
641 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000642 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000643 CanonicalTemplateTemplateParm *Canonical
644 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
645 if (Canonical)
646 return Canonical->getParam();
647
648 // Build a canonical template parameter list.
649 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000650 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000651 CanonParams.reserve(Params->size());
652 for (TemplateParameterList::const_iterator P = Params->begin(),
653 PEnd = Params->end();
654 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000655 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000656 CanonParams.push_back(
657 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000658 SourceLocation(),
659 SourceLocation(),
660 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000661 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000662 TTP->isParameterPack()));
Eugene Zelenko7855e772018-04-03 00:11:50 +0000663 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000664 QualType T = getCanonicalType(NTTP->getType());
665 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
666 NonTypeTemplateParmDecl *Param;
667 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000668 SmallVector<QualType, 2> ExpandedTypes;
669 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000670 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
671 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
672 ExpandedTInfos.push_back(
673 getTrivialTypeSourceInfo(ExpandedTypes.back()));
674 }
675
676 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000677 SourceLocation(),
678 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000679 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000680 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000681 T,
682 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000683 ExpandedTypes,
684 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000685 } else {
686 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000687 SourceLocation(),
688 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000689 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000690 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000691 T,
692 NTTP->isParameterPack(),
693 TInfo);
694 }
695 CanonParams.push_back(Param);
696
697 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000698 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
699 cast<TemplateTemplateParmDecl>(*P)));
700 }
701
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000702 assert(!TTP->getRequiresClause() &&
703 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000704 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000705
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000706 TemplateTemplateParmDecl *CanonTTP
707 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
708 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000709 TTP->getPosition(),
710 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000711 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000712 TemplateParameterList::Create(*this, SourceLocation(),
713 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000714 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000715 SourceLocation(),
716 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000717
718 // Get the new insert position for the node we care about.
719 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000720 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000721 (void)Canonical;
722
723 // Create the canonical template template parameter entry.
724 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
725 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
726 return CanonTTP;
727}
728
Charles Davis53c59df2010-08-16 03:33:14 +0000729CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000730 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000731
John McCall359b8852013-01-25 22:30:49 +0000732 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000733 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000734 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000735 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000736 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000737 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000738 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000739 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000740 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000741 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000742 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000743 return CreateMicrosoftCXXABI(*this);
744 }
David Blaikie8a40f702012-01-17 06:56:22 +0000745 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000746}
747
Alexander Richardson6d989432017-10-15 18:48:14 +0000748static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
749 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000750 if (LOpts.FakeAddressSpaceMap) {
751 // The fake address space map must have a distinct entry for each
752 // language-specific address space.
753 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000754 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000755 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000756 3, // opencl_local
757 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000758 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000759 4, // opencl_generic
760 5, // cuda_device
761 6, // cuda_constant
762 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000763 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000764 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000765 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000766 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000767 }
768}
769
David Tweed31d09b02013-09-13 12:04:22 +0000770static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
771 const LangOptions &LangOpts) {
772 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000773 case LangOptions::ASMM_Target:
774 return TI.useAddressSpaceMapMangling();
775 case LangOptions::ASMM_On:
776 return true;
777 case LangOptions::ASMM_Off:
778 return false;
779 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000780 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000781}
782
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000783ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000784 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000785 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000786 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
787 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000788 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000789 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000790 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000791 LangOpts.XRayNeverInstrumentFiles,
792 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000793 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000794 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000795 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
796 CompCategories(this_()), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000797 TUDecl = TranslationUnitDecl::Create(*this);
798}
799
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000800ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000801 ReleaseParentMapEntries();
802
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000803 // Release the DenseMaps associated with DeclContext objects.
804 // FIXME: Is this the ideal solution?
805 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000806
Manuel Klimeka7328992013-06-03 13:51:33 +0000807 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000808 for (auto &Pair : Deallocations)
809 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000810
Ted Kremenek076baeb2010-06-08 23:00:58 +0000811 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000812 // because they can contain DenseMaps.
813 for (llvm::DenseMap<const ObjCContainerDecl*,
814 const ASTRecordLayout*>::iterator
815 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
816 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000817 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000818 R->Destroy(*this);
819
Ted Kremenek076baeb2010-06-08 23:00:58 +0000820 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
821 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
822 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000823 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000824 R->Destroy(*this);
825 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000826
827 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
828 AEnd = DeclAttrs.end();
829 A != AEnd; ++A)
830 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000831
David Majnemere694f3e2015-08-14 14:43:50 +0000832 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
833 MaterializedTemporaryValues)
834 MTVPair.second->~APValue();
835
Richard Smith423f46f2016-07-20 21:38:26 +0000836 for (const auto &Value : ModuleInitializers)
837 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000838}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000839
Manuel Klimek95403e62014-05-21 13:28:59 +0000840void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000841 if (!PointerParents) return;
842 for (const auto &Entry : *PointerParents) {
843 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
844 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
845 } else if (Entry.second.is<ParentVector *>()) {
846 delete Entry.second.get<ParentVector *>();
847 }
848 }
849 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000850 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
851 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000852 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000853 delete Entry.second.get<ParentVector *>();
854 }
855 }
856}
857
Douglas Gregor1a809332010-05-23 18:26:36 +0000858void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000859 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000860}
861
Mike Stump11289f42009-09-09 15:08:12 +0000862void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000863ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000864 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000865}
866
Chris Lattner4eb445d2007-01-26 01:27:23 +0000867void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000868 llvm::errs() << "\n*** AST Context Stats:\n";
869 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000870
Douglas Gregora30d0462009-05-26 14:40:08 +0000871 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000872#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000873#define ABSTRACT_TYPE(Name, Parent)
874#include "clang/AST/TypeNodes.def"
875 0 // Extra
876 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000877
Chris Lattner4eb445d2007-01-26 01:27:23 +0000878 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
879 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000880 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000881 }
882
Douglas Gregora30d0462009-05-26 14:40:08 +0000883 unsigned Idx = 0;
884 unsigned TotalBytes = 0;
885#define TYPE(Name, Parent) \
886 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000887 llvm::errs() << " " << counts[Idx] << " " << #Name \
888 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000889 TotalBytes += counts[Idx] * sizeof(Name##Type); \
890 ++Idx;
891#define ABSTRACT_TYPE(Name, Parent)
892#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000893
Chandler Carruth3c147a72011-07-04 05:32:14 +0000894 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
895
Douglas Gregor7454c562010-07-02 20:37:36 +0000896 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000897 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
898 << NumImplicitDefaultConstructors
899 << " implicit default constructors created\n";
900 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
901 << NumImplicitCopyConstructors
902 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000903 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000904 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
905 << NumImplicitMoveConstructors
906 << " implicit move constructors created\n";
907 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
908 << NumImplicitCopyAssignmentOperators
909 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000910 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000911 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
912 << NumImplicitMoveAssignmentOperators
913 << " implicit move assignment operators created\n";
914 llvm::errs() << NumImplicitDestructorsDeclared << "/"
915 << NumImplicitDestructors
916 << " implicit destructors created\n";
917
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000918 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000919 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000920 ExternalSource->PrintStats();
921 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000922
Douglas Gregor5b11d492010-07-25 17:53:33 +0000923 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000924}
925
Richard Smith42413142015-05-15 20:05:43 +0000926void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
927 bool NotifyListeners) {
928 if (NotifyListeners)
929 if (auto *Listener = getASTMutationListener())
930 Listener->RedefinedHiddenDefinition(ND, M);
931
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000932 if (getLangOpts().ModulesLocalVisibility)
933 MergedDefModules[ND].push_back(M);
934 else
Richard Smith90dc5252017-06-23 01:04:34 +0000935 ND->setVisibleDespiteOwningModule();
Richard Smith42413142015-05-15 20:05:43 +0000936}
937
938void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
939 auto It = MergedDefModules.find(ND);
940 if (It == MergedDefModules.end())
941 return;
942
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000943 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000944 llvm::DenseSet<Module*> Found;
945 for (Module *&M : Merged)
946 if (!Found.insert(M).second)
947 M = nullptr;
948 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
949}
950
Richard Smithdc1f0422016-07-20 19:10:16 +0000951void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
952 if (LazyInitializers.empty())
953 return;
954
955 auto *Source = Ctx.getExternalSource();
956 assert(Source && "lazy initializers but no external source");
957
958 auto LazyInits = std::move(LazyInitializers);
959 LazyInitializers.clear();
960
961 for (auto ID : LazyInits)
962 Initializers.push_back(Source->GetExternalDecl(ID));
963
964 assert(LazyInitializers.empty() &&
965 "GetExternalDecl for lazy module initializer added more inits");
966}
967
968void ASTContext::addModuleInitializer(Module *M, Decl *D) {
969 // One special case: if we add a module initializer that imports another
970 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000971 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +0000972 auto It = ModuleInitializers.find(ID->getImportedModule());
973
974 // Maybe the ImportDecl does nothing at all. (Common case.)
975 if (It == ModuleInitializers.end())
976 return;
977
978 // Maybe the ImportDecl only imports another ImportDecl.
979 auto &Imported = *It->second;
980 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
981 Imported.resolve(*this);
982 auto *OnlyDecl = Imported.Initializers.front();
983 if (isa<ImportDecl>(OnlyDecl))
984 D = OnlyDecl;
985 }
986 }
987
988 auto *&Inits = ModuleInitializers[M];
989 if (!Inits)
990 Inits = new (*this) PerModuleInitializers;
991 Inits->Initializers.push_back(D);
992}
993
994void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
995 auto *&Inits = ModuleInitializers[M];
996 if (!Inits)
997 Inits = new (*this) PerModuleInitializers;
998 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
999 IDs.begin(), IDs.end());
1000}
1001
Eugene Zelenko7855e772018-04-03 00:11:50 +00001002ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001003 auto It = ModuleInitializers.find(M);
1004 if (It == ModuleInitializers.end())
1005 return None;
1006
1007 auto *Inits = It->second;
1008 Inits->resolve(*this);
1009 return Inits->Initializers;
1010}
1011
Richard Smithf19e1272015-03-07 00:04:49 +00001012ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1013 if (!ExternCContext)
1014 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1015
1016 return ExternCContext;
1017}
1018
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001019BuiltinTemplateDecl *
1020ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1021 const IdentifierInfo *II) const {
1022 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1023 BuiltinTemplate->setImplicit();
1024 TUDecl->addDecl(BuiltinTemplate);
1025
1026 return BuiltinTemplate;
1027}
1028
1029BuiltinTemplateDecl *
1030ASTContext::getMakeIntegerSeqDecl() const {
1031 if (!MakeIntegerSeqDecl)
1032 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1033 getMakeIntegerSeqName());
1034 return MakeIntegerSeqDecl;
1035}
1036
Eric Fiselier6ad68552016-07-01 01:24:09 +00001037BuiltinTemplateDecl *
1038ASTContext::getTypePackElementDecl() const {
1039 if (!TypePackElementDecl)
1040 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1041 getTypePackElementName());
1042 return TypePackElementDecl;
1043}
1044
Alp Toker2dea15b2013-12-17 01:22:38 +00001045RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1046 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001047 SourceLocation Loc;
1048 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001049 if (getLangOpts().CPlusPlus)
1050 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1051 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001052 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001053 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1054 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001055 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001056 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1057 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001058 return NewDecl;
1059}
1060
1061TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1062 StringRef Name) const {
1063 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1064 TypedefDecl *NewDecl = TypedefDecl::Create(
1065 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1066 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1067 NewDecl->setImplicit();
1068 return NewDecl;
1069}
1070
Douglas Gregor801c99d2011-08-12 06:49:56 +00001071TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001072 if (!Int128Decl)
1073 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001074 return Int128Decl;
1075}
1076
1077TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001078 if (!UInt128Decl)
1079 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001080 return UInt128Decl;
1081}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001082
John McCall48f2d582009-10-23 23:03:21 +00001083void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001084 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001085 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001086 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001087}
1088
Artem Belevichb5bc9232015-09-22 17:23:22 +00001089void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1090 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001091 assert((!this->Target || this->Target == &Target) &&
1092 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001093 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001094
Douglas Gregore8bbc122011-09-02 00:18:52 +00001095 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001096 this->AuxTarget = AuxTarget;
1097
Douglas Gregore8bbc122011-09-02 00:18:52 +00001098 ABI.reset(createCXXABI(Target));
1099 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001100 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001101
Chris Lattner970e54e2006-11-12 00:37:36 +00001102 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001103 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001104
Chris Lattner970e54e2006-11-12 00:37:36 +00001105 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001106 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001107 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001108 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001109 InitBuiltinType(CharTy, BuiltinType::Char_S);
1110 else
1111 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001112 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001113 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1114 InitBuiltinType(ShortTy, BuiltinType::Short);
1115 InitBuiltinType(IntTy, BuiltinType::Int);
1116 InitBuiltinType(LongTy, BuiltinType::Long);
1117 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001118
Chris Lattner970e54e2006-11-12 00:37:36 +00001119 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001120 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1121 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1122 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1123 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1124 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001125
Chris Lattner970e54e2006-11-12 00:37:36 +00001126 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001127 InitBuiltinType(FloatTy, BuiltinType::Float);
1128 InitBuiltinType(DoubleTy, BuiltinType::Double);
1129 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001130
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001131 // GNU extension, __float128 for IEEE quadruple precision
1132 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1133
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001134 // C11 extension ISO/IEC TS 18661-3
1135 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1136
Leonard Chanf921d852018-06-04 16:07:52 +00001137 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001138 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1139 InitBuiltinType(AccumTy, BuiltinType::Accum);
1140 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1141 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1142 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1143 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1144 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1145 InitBuiltinType(FractTy, BuiltinType::Fract);
1146 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1147 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1148 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1149 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1150 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1151 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1152 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1153 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1154 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1155 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1156 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1157 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1158 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1159 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1160 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1161 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001162
Chris Lattnerf122cef2009-04-30 02:43:43 +00001163 // GNU extension, 128-bit integers.
1164 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1165 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1166
Hans Wennborg0d81e012013-05-10 10:08:40 +00001167 // C++ 3.9.1p5
1168 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1169 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1170 else // -fshort-wchar makes wchar_t be unsigned.
1171 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1172 if (LangOpts.CPlusPlus && LangOpts.WChar)
1173 WideCharTy = WCharTy;
1174 else {
1175 // C99 (or C++ using -fno-wchar).
1176 WideCharTy = getFromTargetType(Target.getWCharType());
1177 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001178
James Molloy36365542012-05-04 10:55:22 +00001179 WIntTy = getFromTargetType(Target.getWIntType());
1180
Richard Smith3a8244d2018-05-01 05:02:45 +00001181 // C++20 (proposed)
1182 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1183
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001184 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1185 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1186 else // C99
1187 Char16Ty = getFromTargetType(Target.getChar16Type());
1188
1189 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1190 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1191 else // C99
1192 Char32Ty = getFromTargetType(Target.getChar32Type());
1193
Douglas Gregor4619e432008-12-05 23:32:09 +00001194 // Placeholder type for type-dependent expressions whose type is
1195 // completely unknown. No code should ever check a type against
1196 // DependentTy and users should never see it; however, it is here to
1197 // help diagnose failures to properly check for type-dependent
1198 // expressions.
1199 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001200
John McCall36e7fe32010-10-12 00:20:44 +00001201 // Placeholder type for functions.
1202 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1203
John McCall0009fcc2011-04-26 20:42:42 +00001204 // Placeholder type for bound members.
1205 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1206
John McCall526ab472011-10-25 17:37:35 +00001207 // Placeholder type for pseudo-objects.
1208 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1209
John McCall31996342011-04-07 08:22:57 +00001210 // "any" type; useful for debugger-like clients.
1211 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1212
John McCall8a6b59a2011-10-17 18:09:15 +00001213 // Placeholder type for unbridged ARC casts.
1214 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1215
Eli Friedman34866c72012-08-31 00:14:07 +00001216 // Placeholder type for builtin functions.
1217 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1218
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001219 // Placeholder type for OMP array sections.
1220 if (LangOpts.OpenMP)
1221 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1222
Chris Lattner970e54e2006-11-12 00:37:36 +00001223 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001224 FloatComplexTy = getComplexType(FloatTy);
1225 DoubleComplexTy = getComplexType(DoubleTy);
1226 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001227 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001228
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001229 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001230 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1231 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001232 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001233
Alexey Bader954ba212016-04-08 13:40:33 +00001234 if (LangOpts.OpenCL) {
1235#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1236 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001237#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001238
Guy Benyei61054192013-02-07 10:55:47 +00001239 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001240 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001241 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1242 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001243 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001244 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001245
1246 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001247 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1248 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001249
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001250 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001251
1252 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001253
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001254 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001255 if (LangOpts.OpenCLVersion >= 200) {
1256 auto Q = VoidTy.getQualifiers();
1257 Q.setAddressSpace(LangAS::opencl_generic);
1258 VoidPtrTy = getPointerType(getCanonicalType(
1259 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1260 } else {
1261 VoidPtrTy = getPointerType(VoidTy);
1262 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001263
1264 // nullptr type (C++0x 2.14.7)
1265 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001266
1267 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1268 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001269
1270 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001271 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001272}
1273
David Blaikie9c902b52011-09-25 23:23:43 +00001274DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001275 return SourceMgr.getDiagnostics();
1276}
1277
Douglas Gregor561eceb2010-08-30 16:49:28 +00001278AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1279 AttrVec *&Result = DeclAttrs[D];
1280 if (!Result) {
1281 void *Mem = Allocate(sizeof(AttrVec));
1282 Result = new (Mem) AttrVec;
1283 }
1284
1285 return *Result;
1286}
1287
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001288/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001289void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001290 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1291 if (Pos != DeclAttrs.end()) {
1292 Pos->second->~AttrVec();
1293 DeclAttrs.erase(Pos);
1294 }
1295}
1296
Larisse Voufo39a1e502013-08-06 01:03:05 +00001297// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001298MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001299ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001300 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001301 return getTemplateOrSpecializationInfo(Var)
1302 .dyn_cast<MemberSpecializationInfo *>();
1303}
1304
1305ASTContext::TemplateOrSpecializationInfo
1306ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1307 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1308 TemplateOrInstantiation.find(Var);
1309 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001310 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001311
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001312 return Pos->second;
1313}
1314
Mike Stump11289f42009-09-09 15:08:12 +00001315void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001316ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001317 TemplateSpecializationKind TSK,
1318 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001319 assert(Inst->isStaticDataMember() && "Not a static data member");
1320 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001321 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1322 Tmpl, TSK, PointOfInstantiation));
1323}
1324
1325void
1326ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1327 TemplateOrSpecializationInfo TSI) {
1328 assert(!TemplateOrInstantiation[Inst] &&
1329 "Already noted what the variable was instantiated from");
1330 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001331}
1332
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001333FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1334 const FunctionDecl *FD){
1335 assert(FD && "Specialization is 0");
1336 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001337 = ClassScopeSpecializationPattern.find(FD);
1338 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001339 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001340
1341 return Pos->second;
1342}
1343
1344void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1345 FunctionDecl *Pattern) {
1346 assert(FD && "Specialization is 0");
1347 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001348 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001349}
1350
John McCalle61f2ba2009-11-18 02:36:19 +00001351NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001352ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1353 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001354 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001355 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001356
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001357 return Pos->second;
1358}
1359
1360void
Richard Smithd8a9e372016-12-18 21:39:37 +00001361ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001362 assert((isa<UsingDecl>(Pattern) ||
1363 isa<UnresolvedUsingValueDecl>(Pattern) ||
1364 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1365 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001366 assert((isa<UsingDecl>(Inst) ||
1367 isa<UnresolvedUsingValueDecl>(Inst) ||
1368 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1369 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001370 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1371 InstantiatedFromUsingDecl[Inst] = Pattern;
1372}
1373
1374UsingShadowDecl *
1375ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1376 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1377 = InstantiatedFromUsingShadowDecl.find(Inst);
1378 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001379 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001380
1381 return Pos->second;
1382}
1383
1384void
1385ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1386 UsingShadowDecl *Pattern) {
1387 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1388 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001389}
1390
Anders Carlsson5da84842009-09-01 04:26:58 +00001391FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1392 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1393 = InstantiatedFromUnnamedFieldDecl.find(Field);
1394 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001395 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001396
Anders Carlsson5da84842009-09-01 04:26:58 +00001397 return Pos->second;
1398}
1399
1400void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1401 FieldDecl *Tmpl) {
1402 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1403 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1404 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1405 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001406
Anders Carlsson5da84842009-09-01 04:26:58 +00001407 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1408}
1409
Douglas Gregor832940b2010-03-02 23:58:15 +00001410ASTContext::overridden_cxx_method_iterator
1411ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001412 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001413}
1414
1415ASTContext::overridden_cxx_method_iterator
1416ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001417 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001418}
1419
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001420unsigned
1421ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001422 auto Range = overridden_methods(Method);
1423 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001424}
1425
Clement Courbet6ecaec82016-07-05 07:49:31 +00001426ASTContext::overridden_method_range
1427ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001428 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1429 OverriddenMethods.find(Method->getCanonicalDecl());
1430 if (Pos == OverriddenMethods.end())
1431 return overridden_method_range(nullptr, nullptr);
1432 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001433}
1434
Douglas Gregor832940b2010-03-02 23:58:15 +00001435void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1436 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001437 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001438 OverriddenMethods[Method].push_back(Overridden);
1439}
1440
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001441void ASTContext::getOverriddenMethods(
1442 const NamedDecl *D,
1443 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001444 assert(D);
1445
Eugene Zelenko7855e772018-04-03 00:11:50 +00001446 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001447 Overridden.append(overridden_methods_begin(CXXMethod),
1448 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001449 return;
1450 }
1451
Eugene Zelenko7855e772018-04-03 00:11:50 +00001452 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001453 if (!Method)
1454 return;
1455
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001456 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1457 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001458 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001459}
1460
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001461void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1462 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1463 assert(!Import->isFromASTFile() && "Non-local import declaration");
1464 if (!FirstLocalImport) {
1465 FirstLocalImport = Import;
1466 LastLocalImport = Import;
1467 return;
1468 }
1469
1470 LastLocalImport->NextLocalImport = Import;
1471 LastLocalImport = Import;
1472}
1473
Chris Lattner53cfe802007-07-18 17:52:12 +00001474//===----------------------------------------------------------------------===//
1475// Type Sizing and Analysis
1476//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001477
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001478/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1479/// scalar floating point type.
1480const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001481 const auto *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001482 assert(BT && "Not a floating point type!");
1483 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001484 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001485 case BuiltinType::Float16:
1486 case BuiltinType::Half:
1487 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001488 case BuiltinType::Float: return Target->getFloatFormat();
1489 case BuiltinType::Double: return Target->getDoubleFormat();
1490 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001491 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001492 }
1493}
1494
Rafael Espindola71eccb32013-08-08 19:53:46 +00001495CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001496 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001497
John McCall94268702010-10-08 18:24:19 +00001498 bool UseAlignAttrOnly = false;
1499 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1500 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001501
John McCall94268702010-10-08 18:24:19 +00001502 // __attribute__((aligned)) can increase or decrease alignment
1503 // *except* on a struct or struct member, where it only increases
1504 // alignment unless 'packed' is also specified.
1505 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001506 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001507 // ignore that possibility; Sema should diagnose it.
1508 if (isa<FieldDecl>(D)) {
1509 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1510 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1511 } else {
1512 UseAlignAttrOnly = true;
1513 }
1514 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001515 else if (isa<FieldDecl>(D))
1516 UseAlignAttrOnly =
1517 D->hasAttr<PackedAttr>() ||
1518 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001519
John McCall4e819612011-01-20 07:57:12 +00001520 // If we're using the align attribute only, just ignore everything
1521 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001522 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001523 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001524 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001525 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001526 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001527 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001528 T = RT->getPointeeType();
1529 else
1530 T = getPointerType(RT->getPointeeType());
1531 }
Richard Smithf6d70302014-06-10 23:34:28 +00001532 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001533 if (T->isFunctionType())
1534 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1535 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001536 // Adjust alignments of declarations with array type by the
1537 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001538 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001539 unsigned MinWidth = Target->getLargeArrayMinWidth();
1540 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001541 if (isa<VariableArrayType>(arrayType))
1542 Align = std::max(Align, Target->getLargeArrayAlign());
1543 else if (isa<ConstantArrayType>(arrayType) &&
1544 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1545 Align = std::max(Align, Target->getLargeArrayAlign());
1546 }
John McCall33ddac02011-01-19 10:06:00 +00001547 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001548 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001549 if (BaseT.getQualifiers().hasUnaligned())
1550 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001551 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001552 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001553 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1554 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001555 }
John McCall4e819612011-01-20 07:57:12 +00001556
1557 // Fields can be subject to extra alignment constraints, like if
1558 // the field is packed, the struct is packed, or the struct has a
1559 // a max-field-alignment constraint (#pragma pack). So calculate
1560 // the actual alignment of the field within the struct, and then
1561 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001562 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001563 const RecordDecl *Parent = Field->getParent();
1564 // We can only produce a sensible answer if the record is valid.
1565 if (!Parent->isInvalidDecl()) {
1566 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001567
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001568 // Start with the record's overall alignment.
1569 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001570
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001571 // Use the GCD of that and the offset within the record.
1572 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1573 if (Offset > 0) {
1574 // Alignment is always a power of 2, so the GCD will be a power of 2,
1575 // which means we get to do this crazy thing instead of Euclid's.
1576 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1577 if (LowBitOfOffset < FieldAlign)
1578 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1579 }
1580
1581 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001582 }
Charles Davis3fc51072010-02-23 04:52:00 +00001583 }
Chris Lattner68061312009-01-24 21:53:27 +00001584 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001585
Ken Dyckcc56c542011-01-15 18:38:59 +00001586 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001587}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001588
John McCallf1249922012-08-21 04:10:00 +00001589// getTypeInfoDataSizeInChars - Return the size of a type, in
1590// chars. If the type is a record, its data size is returned. This is
1591// the size of the memcpy that's performed when assigning this type
1592// using a trivial copy/move assignment operator.
1593std::pair<CharUnits, CharUnits>
1594ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1595 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1596
1597 // In C++, objects can sometimes be allocated into the tail padding
1598 // of a base-class subobject. We decide whether that's possible
1599 // during class layout, so here we can just trust the layout results.
1600 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001601 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001602 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1603 sizeAndAlign.first = layout.getDataSize();
1604 }
1605 }
1606
1607 return sizeAndAlign;
1608}
1609
Richard Trieu04d2d942013-05-14 21:59:17 +00001610/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1611/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1612std::pair<CharUnits, CharUnits>
1613static getConstantArrayInfoInChars(const ASTContext &Context,
1614 const ConstantArrayType *CAT) {
1615 std::pair<CharUnits, CharUnits> EltInfo =
1616 Context.getTypeInfoInChars(CAT->getElementType());
1617 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001618 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1619 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001620 "Overflow in array type char size evaluation");
1621 uint64_t Width = EltInfo.first.getQuantity() * Size;
1622 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001623 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1624 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001625 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001626 return std::make_pair(CharUnits::fromQuantity(Width),
1627 CharUnits::fromQuantity(Align));
1628}
1629
John McCall87fe5d52010-05-20 01:18:31 +00001630std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001631ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001632 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001633 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001634 TypeInfo Info = getTypeInfo(T);
1635 return std::make_pair(toCharUnitsFromBits(Info.Width),
1636 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001637}
1638
1639std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001640ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001641 return getTypeInfoInChars(T.getTypePtr());
1642}
1643
David Majnemer34b57492014-07-30 01:30:47 +00001644bool ASTContext::isAlignmentRequired(const Type *T) const {
1645 return getTypeInfo(T).AlignIsRequired;
1646}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001647
David Majnemer34b57492014-07-30 01:30:47 +00001648bool ASTContext::isAlignmentRequired(QualType T) const {
1649 return isAlignmentRequired(T.getTypePtr());
1650}
1651
Richard Smithb2f0f052016-10-10 18:54:32 +00001652unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1653 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001654 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001655 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1656 return Align;
1657
1658 // If we have an (array of) complete type, we're done.
1659 T = getBaseElementType(T);
1660 if (!T->isIncompleteType())
1661 return getTypeAlign(T);
1662
1663 // If we had an array type, its element type might be a typedef
1664 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001665 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001666 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1667 return Align;
1668
1669 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001670 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001671 return TT->getDecl()->getMaxAlignment();
1672
1673 return 0;
1674}
1675
David Majnemer34b57492014-07-30 01:30:47 +00001676TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001677 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1678 if (I != MemoizedTypeInfo.end())
1679 return I->second;
1680
1681 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1682 TypeInfo TI = getTypeInfoImpl(T);
1683 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001684 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001685}
1686
1687/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1688/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001689///
1690/// FIXME: Pointers into different addr spaces could have different sizes and
1691/// alignment requirements: getPointerInfo should take an AddrSpace, this
1692/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001693TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1694 uint64_t Width = 0;
1695 unsigned Align = 8;
1696 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001697 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001698 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001699#define TYPE(Class, Base)
1700#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001701#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001702#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001703#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1704 case Type::Class: \
1705 assert(!T->isDependentType() && "should not see dependent types here"); \
1706 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001707#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001708 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001709
Chris Lattner355332d2007-07-13 22:27:08 +00001710 case Type::FunctionNoProto:
1711 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001712 // GCC extension: alignof(function) = 32 bits
1713 Width = 0;
1714 Align = 32;
1715 break;
1716
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001717 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001718 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001719 Width = 0;
1720 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1721 break;
1722
Steve Naroff5c131802007-08-30 01:06:46 +00001723 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001724 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001725
David Majnemer34b57492014-07-30 01:30:47 +00001726 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001727 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001728 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001729 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001730 Width = EltInfo.Width * Size;
1731 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001732 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1733 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001734 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001735 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001736 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001737 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001738 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001739 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001740 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1741 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001742 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001743 // If the alignment is not a power of 2, round up to the next power of 2.
1744 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001745 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001746 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001747 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001748 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001749 // Adjust the alignment based on the target max.
1750 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1751 if (TargetVectorAlign && TargetVectorAlign < Align)
1752 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001753 break;
1754 }
Chris Lattner647fb222007-07-18 18:26:58 +00001755
Chris Lattner7570e9c2008-03-08 08:52:55 +00001756 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001757 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001758 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001759 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001760 // GCC extension: alignof(void) = 8 bits.
1761 Width = 0;
1762 Align = 8;
1763 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001764 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001765 Width = Target->getBoolWidth();
1766 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001767 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001768 case BuiltinType::Char_S:
1769 case BuiltinType::Char_U:
1770 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001771 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001772 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001773 Width = Target->getCharWidth();
1774 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001775 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001776 case BuiltinType::WChar_S:
1777 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001778 Width = Target->getWCharWidth();
1779 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001780 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001781 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001782 Width = Target->getChar16Width();
1783 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001784 break;
1785 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001786 Width = Target->getChar32Width();
1787 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001788 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001789 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001790 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001791 Width = Target->getShortWidth();
1792 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001793 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001794 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001795 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001796 Width = Target->getIntWidth();
1797 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001798 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001799 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001800 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001801 Width = Target->getLongWidth();
1802 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001803 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001804 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001805 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001806 Width = Target->getLongLongWidth();
1807 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001808 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001809 case BuiltinType::Int128:
1810 case BuiltinType::UInt128:
1811 Width = 128;
1812 Align = 128; // int128_t is 128-bit aligned on all targets.
1813 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001814 case BuiltinType::ShortAccum:
1815 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001816 case BuiltinType::SatShortAccum:
1817 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001818 Width = Target->getShortAccumWidth();
1819 Align = Target->getShortAccumAlign();
1820 break;
1821 case BuiltinType::Accum:
1822 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001823 case BuiltinType::SatAccum:
1824 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001825 Width = Target->getAccumWidth();
1826 Align = Target->getAccumAlign();
1827 break;
1828 case BuiltinType::LongAccum:
1829 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001830 case BuiltinType::SatLongAccum:
1831 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001832 Width = Target->getLongAccumWidth();
1833 Align = Target->getLongAccumAlign();
1834 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00001835 case BuiltinType::ShortFract:
1836 case BuiltinType::UShortFract:
1837 case BuiltinType::SatShortFract:
1838 case BuiltinType::SatUShortFract:
1839 Width = Target->getShortFractWidth();
1840 Align = Target->getShortFractAlign();
1841 break;
1842 case BuiltinType::Fract:
1843 case BuiltinType::UFract:
1844 case BuiltinType::SatFract:
1845 case BuiltinType::SatUFract:
1846 Width = Target->getFractWidth();
1847 Align = Target->getFractAlign();
1848 break;
1849 case BuiltinType::LongFract:
1850 case BuiltinType::ULongFract:
1851 case BuiltinType::SatLongFract:
1852 case BuiltinType::SatULongFract:
1853 Width = Target->getLongFractWidth();
1854 Align = Target->getLongFractAlign();
1855 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001856 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001857 case BuiltinType::Half:
1858 Width = Target->getHalfWidth();
1859 Align = Target->getHalfAlign();
1860 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001861 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001862 Width = Target->getFloatWidth();
1863 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001864 break;
1865 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001866 Width = Target->getDoubleWidth();
1867 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001868 break;
1869 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001870 Width = Target->getLongDoubleWidth();
1871 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001872 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001873 case BuiltinType::Float128:
1874 Width = Target->getFloat128Width();
1875 Align = Target->getFloat128Align();
1876 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001877 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001878 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1879 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001880 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001881 case BuiltinType::ObjCId:
1882 case BuiltinType::ObjCClass:
1883 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001884 Width = Target->getPointerWidth(0);
1885 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001886 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001887 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001888 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001889 case BuiltinType::OCLClkEvent:
1890 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001891 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001892#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1893 case BuiltinType::Id:
1894#include "clang/Basic/OpenCLImageTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00001895 AS = getTargetAddressSpace(
1896 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001897 Width = Target->getPointerWidth(AS);
1898 Align = Target->getPointerAlign(AS);
1899 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001900 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001901 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001902 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001903 Width = Target->getPointerWidth(0);
1904 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001905 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001906 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001907 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001908 Width = Target->getPointerWidth(AS);
1909 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001910 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001911 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001912 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001913 // alignof and sizeof should never enter this code path here, so we go
1914 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001915 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001916 Width = Target->getPointerWidth(AS);
1917 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001918 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001919 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001920 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001921 Width = Target->getPointerWidth(AS);
1922 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001923 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001924 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001925 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00001926 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1927 Width = MPI.Width;
1928 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00001929 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001930 }
Chris Lattner647fb222007-07-18 18:26:58 +00001931 case Type::Complex: {
1932 // Complex types have the same alignment as their elements, but twice the
1933 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001934 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1935 Width = EltInfo.Width * 2;
1936 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001937 break;
1938 }
John McCall8b07ec22010-05-15 11:32:37 +00001939 case Type::ObjCObject:
1940 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001941 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001942 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001943 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001944 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001945 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001946 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001947 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001948 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001949 break;
1950 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001951 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001952 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001953 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001954
1955 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001956 Width = 8;
1957 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001958 break;
1959 }
Mike Stump11289f42009-09-09 15:08:12 +00001960
Eugene Zelenko7855e772018-04-03 00:11:50 +00001961 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00001962 const EnumDecl *ED = ET->getDecl();
1963 TypeInfo Info =
1964 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1965 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1966 Info.Align = AttrAlign;
1967 Info.AlignIsRequired = true;
1968 }
1969 return Info;
1970 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001971
Eugene Zelenko7855e772018-04-03 00:11:50 +00001972 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001973 const RecordDecl *RD = RT->getDecl();
1974 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001975 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001976 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001977 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001978 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001979 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001980
Chris Lattner63d2b362009-10-22 05:17:15 +00001981 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001982 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1983 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001984
Richard Smith600b5262017-01-26 20:40:47 +00001985 case Type::Auto:
1986 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001987 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001988 assert(!A->getDeducedType().isNull() &&
1989 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001990 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001991 }
1992
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001993 case Type::Paren:
1994 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1995
Manman Rene6be26c2016-09-13 17:25:08 +00001996 case Type::ObjCTypeParam:
1997 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1998
Douglas Gregoref462e62009-04-30 17:32:17 +00001999 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002000 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002001 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002002 // If the typedef has an aligned attribute on it, it overrides any computed
2003 // alignment we have. This violates the GCC documentation (which says that
2004 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002005 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002006 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002007 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002008 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002009 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002010 AlignIsRequired = Info.AlignIsRequired;
2011 }
David Majnemer34b57492014-07-30 01:30:47 +00002012 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002013 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002014 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002015
Abramo Bagnara6150c882010-05-11 21:36:43 +00002016 case Type::Elaborated:
2017 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002018
John McCall81904512011-01-06 01:58:22 +00002019 case Type::Attributed:
2020 return getTypeInfo(
2021 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2022
Eli Friedman0dfb8892011-10-06 23:00:33 +00002023 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002024 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002025 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2026 Width = Info.Width;
2027 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002028
JF Bastien801fca22018-05-09 03:51:12 +00002029 if (!Width) {
2030 // An otherwise zero-sized type should still generate an
2031 // atomic operation.
2032 Width = Target->getCharWidth();
2033 assert(Align);
2034 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2035 // If the size of the type doesn't exceed the platform's max
2036 // atomic promotion width, make the size and alignment more
2037 // favorable to atomic operations:
2038
John McCalla8ec7eb2013-03-07 21:37:17 +00002039 // Round the size up to a power of 2.
2040 if (!llvm::isPowerOf2_64(Width))
2041 Width = llvm::NextPowerOf2(Width);
2042
2043 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002044 Align = static_cast<unsigned>(Width);
2045 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002046 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002047 break;
2048
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002049 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002050 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2051 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002052 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002053 }
Mike Stump11289f42009-09-09 15:08:12 +00002054
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002055 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002056 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002057}
2058
Alexey Bataev00396512015-07-02 03:40:19 +00002059unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2060 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2061 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2062 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2063 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2064 getTargetInfo().getABI() == "elfv1-qpx" &&
2065 T->isSpecificBuiltinType(BuiltinType::Double))
2066 SimdAlign = 256;
2067 return SimdAlign;
2068}
2069
Ken Dyckcc56c542011-01-15 18:38:59 +00002070/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2071CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2072 return CharUnits::fromQuantity(BitSize / getCharWidth());
2073}
2074
Ken Dyckb0fcc592011-02-11 01:54:29 +00002075/// toBits - Convert a size in characters to a size in characters.
2076int64_t ASTContext::toBits(CharUnits CharSize) const {
2077 return CharSize.getQuantity() * getCharWidth();
2078}
2079
Ken Dyck8c89d592009-12-22 14:23:30 +00002080/// getTypeSizeInChars - Return the size of the specified type, in characters.
2081/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002082CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002083 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002084}
Jay Foad39c79802011-01-12 09:06:06 +00002085CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002086 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002087}
2088
Ken Dycka6046ab2010-01-26 17:25:18 +00002089/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002090/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002091CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002092 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002093}
Jay Foad39c79802011-01-12 09:06:06 +00002094CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002095 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002096}
2097
Chris Lattnera3402cd2009-01-27 18:08:34 +00002098/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2099/// type for the current target in bits. This can be different than the ABI
2100/// alignment in cases where it is beneficial for performance to overalign
2101/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002102unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002103 TypeInfo TI = getTypeInfo(T);
2104 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002105
David Majnemere1544562015-04-24 01:25:05 +00002106 T = T->getBaseElementTypeUnsafe();
2107
2108 // The preferred alignment of member pointers is that of a pointer.
2109 if (T->isMemberPointerType())
2110 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2111
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002112 if (!Target->allowsLargerPreferedTypeAlignment())
2113 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002114
Eli Friedman7ab09572009-05-25 21:27:19 +00002115 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002116 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002117 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002118 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002119 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002120 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002121 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2122 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002123 // Don't increase the alignment if an alignment attribute was specified on a
2124 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002125 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002126 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002127
Chris Lattnera3402cd2009-01-27 18:08:34 +00002128 return ABIAlign;
2129}
2130
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002131/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2132/// for __attribute__((aligned)) on this target, to be used if no alignment
2133/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002134unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002135 return getTargetInfo().getDefaultAlignForAttributeAligned();
2136}
2137
Ulrich Weigandfa806422013-05-06 16:23:57 +00002138/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2139/// to a global variable of the specified type.
2140unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2141 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2142}
2143
2144/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2145/// should be given to a global variable of the specified type.
2146CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2147 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2148}
2149
David Majnemer08ef2ba2015-06-23 20:34:18 +00002150CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2151 CharUnits Offset = CharUnits::Zero();
2152 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2153 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2154 Offset += Layout->getBaseClassOffset(Base);
2155 Layout = &getASTRecordLayout(Base);
2156 }
2157 return Offset;
2158}
2159
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002160/// DeepCollectObjCIvars -
2161/// This routine first collects all declared, but not synthesized, ivars in
2162/// super class and then collects all ivars, including those synthesized for
2163/// current class. This routine is used for implementation of current class
2164/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002165void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2166 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002167 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002168 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2169 DeepCollectObjCIvars(SuperClass, false, Ivars);
2170 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002171 for (const auto *I : OI->ivars())
2172 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002173 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002174 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002175 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002176 Iv= Iv->getNextIvar())
2177 Ivars.push_back(Iv);
2178 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002179}
2180
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002181/// CollectInheritedProtocols - Collect all protocols in current class and
2182/// those inherited by it.
2183void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002184 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002185 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002186 // We can use protocol_iterator here instead of
2187 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002188 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002189 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002190 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002191
2192 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002193 for (const auto *Cat : OI->visible_categories())
2194 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002195
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002196 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2197 while (SD) {
2198 CollectInheritedProtocols(SD, Protocols);
2199 SD = SD->getSuperClass();
2200 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002201 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002202 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002203 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002204 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002205 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002206 // Insert the protocol.
2207 if (!Protocols.insert(
2208 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2209 return;
2210
2211 for (auto *Proto : OP->protocols())
2212 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002213 }
2214}
2215
Erich Keane8a6b7402017-11-30 16:37:02 +00002216static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2217 const RecordDecl *RD) {
2218 assert(RD->isUnion() && "Must be union type");
2219 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2220
2221 for (const auto *Field : RD->fields()) {
2222 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2223 return false;
2224 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2225 if (FieldSize != UnionSize)
2226 return false;
2227 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002228 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002229}
2230
Benjamin Kramer802e6252017-12-24 12:46:22 +00002231static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002232 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2233
2234 if (!RD->field_empty())
2235 return false;
2236
2237 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2238 return ClassDecl->isEmpty();
2239
2240 return true;
2241}
2242
2243static llvm::Optional<int64_t>
2244structHasUniqueObjectRepresentations(const ASTContext &Context,
2245 const RecordDecl *RD) {
2246 assert(!RD->isUnion() && "Must be struct/class type");
2247 const auto &Layout = Context.getASTRecordLayout(RD);
2248
2249 int64_t CurOffsetInBits = 0;
2250 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2251 if (ClassDecl->isDynamicClass())
2252 return llvm::None;
2253
2254 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2255 for (const auto Base : ClassDecl->bases()) {
2256 // Empty types can be inherited from, and non-empty types can potentially
2257 // have tail padding, so just make sure there isn't an error.
2258 if (!isStructEmpty(Base.getType())) {
2259 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2260 Context, Base.getType()->getAs<RecordType>()->getDecl());
2261 if (!Size)
2262 return llvm::None;
2263 Bases.emplace_back(Base.getType(), Size.getValue());
2264 }
2265 }
2266
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00002267 llvm::sort(
Erich Keane8a6b7402017-11-30 16:37:02 +00002268 Bases.begin(), Bases.end(), [&](const std::pair<QualType, int64_t> &L,
2269 const std::pair<QualType, int64_t> &R) {
2270 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2271 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2272 });
2273
2274 for (const auto Base : Bases) {
2275 int64_t BaseOffset = Context.toBits(
2276 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2277 int64_t BaseSize = Base.second;
2278 if (BaseOffset != CurOffsetInBits)
2279 return llvm::None;
2280 CurOffsetInBits = BaseOffset + BaseSize;
2281 }
2282 }
2283
2284 for (const auto *Field : RD->fields()) {
2285 if (!Field->getType()->isReferenceType() &&
2286 !Context.hasUniqueObjectRepresentations(Field->getType()))
2287 return llvm::None;
2288
2289 int64_t FieldSizeInBits =
2290 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2291 if (Field->isBitField()) {
2292 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2293
2294 if (BitfieldSize > FieldSizeInBits)
2295 return llvm::None;
2296 FieldSizeInBits = BitfieldSize;
2297 }
2298
2299 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2300
2301 if (FieldOffsetInBits != CurOffsetInBits)
2302 return llvm::None;
2303
2304 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2305 }
2306
2307 return CurOffsetInBits;
2308}
2309
2310bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2311 // C++17 [meta.unary.prop]:
2312 // The predicate condition for a template specialization
2313 // has_unique_object_representations<T> shall be
2314 // satisfied if and only if:
2315 // (9.1) - T is trivially copyable, and
2316 // (9.2) - any two objects of type T with the same value have the same
2317 // object representation, where two objects
2318 // of array or non-union class type are considered to have the same value
2319 // if their respective sequences of
2320 // direct subobjects have the same values, and two objects of union type
2321 // are considered to have the same
2322 // value if they have the same active member and the corresponding members
2323 // have the same value.
2324 // The set of scalar types for which this condition holds is
2325 // implementation-defined. [ Note: If a type has padding
2326 // bits, the condition does not hold; otherwise, the condition holds true
2327 // for unsigned integral types. -- end note ]
2328 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2329
2330 // Arrays are unique only if their element type is unique.
2331 if (Ty->isArrayType())
2332 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2333
2334 // (9.1) - T is trivially copyable...
2335 if (!Ty.isTriviallyCopyableType(*this))
2336 return false;
2337
2338 // All integrals and enums are unique.
2339 if (Ty->isIntegralOrEnumerationType())
2340 return true;
2341
2342 // All other pointers are unique.
2343 if (Ty->isPointerType())
2344 return true;
2345
2346 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002347 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002348 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2349 }
2350
2351 if (Ty->isRecordType()) {
2352 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2353
Erich Keanebd2197c2017-12-12 16:02:06 +00002354 if (Record->isInvalidDecl())
2355 return false;
2356
Erich Keane8a6b7402017-11-30 16:37:02 +00002357 if (Record->isUnion())
2358 return unionHasUniqueObjectRepresentations(*this, Record);
2359
2360 Optional<int64_t> StructSize =
2361 structHasUniqueObjectRepresentations(*this, Record);
2362
2363 return StructSize &&
2364 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2365 }
2366
2367 // FIXME: More cases to handle here (list by rsmith):
2368 // vectors (careful about, eg, vector of 3 foo)
2369 // _Complex int and friends
2370 // _Atomic T
2371 // Obj-C block pointers
2372 // Obj-C object pointers
2373 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2374 // clk_event_t, queue_t, reserve_id_t)
2375 // There're also Obj-C class types and the Obj-C selector type, but I think it
2376 // makes sense for those to return false here.
2377
2378 return false;
2379}
2380
Jay Foad39c79802011-01-12 09:06:06 +00002381unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002382 unsigned count = 0;
2383 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002384 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002385 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002386
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002387 // Count ivar defined in this class's implementation. This
2388 // includes synthesized ivars.
2389 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002390 count += ImplDecl->ivar_size();
2391
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002392 return count;
2393}
2394
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002395bool ASTContext::isSentinelNullExpr(const Expr *E) {
2396 if (!E)
2397 return false;
2398
2399 // nullptr_t is always treated as null.
2400 if (E->getType()->isNullPtrType()) return true;
2401
2402 if (E->getType()->isAnyPointerType() &&
2403 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2404 Expr::NPC_ValueDependentIsNull))
2405 return true;
2406
2407 // Unfortunately, __null has type 'int'.
2408 if (isa<GNUNullExpr>(E)) return true;
2409
2410 return false;
2411}
2412
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002413/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002414/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002415ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2416 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2417 I = ObjCImpls.find(D);
2418 if (I != ObjCImpls.end())
2419 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002420 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002421}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002422
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002423/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002424/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002425ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2426 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2427 I = ObjCImpls.find(D);
2428 if (I != ObjCImpls.end())
2429 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002430 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002431}
2432
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002433/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002434void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2435 ObjCImplementationDecl *ImplD) {
2436 assert(IFaceD && ImplD && "Passed null params");
2437 ObjCImpls[IFaceD] = ImplD;
2438}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002439
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002440/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002441void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2442 ObjCCategoryImplDecl *ImplD) {
2443 assert(CatD && ImplD && "Passed null params");
2444 ObjCImpls[CatD] = ImplD;
2445}
2446
Chandler Carruth21c90602015-12-30 03:24:14 +00002447const ObjCMethodDecl *
2448ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2449 return ObjCMethodRedecls.lookup(MD);
2450}
2451
2452void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2453 const ObjCMethodDecl *Redecl) {
2454 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2455 ObjCMethodRedecls[MD] = Redecl;
2456}
2457
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002458const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2459 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002460 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002461 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002462 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002463 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002464 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002465 return IMD->getClassInterface();
2466
Craig Topper36250ad2014-05-12 05:36:57 +00002467 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002468}
2469
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002470/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002471/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002472Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002473 assert(VD && "Passed null params");
2474 assert(VD->hasAttr<BlocksAttr>() &&
2475 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002476 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002477 I = BlockVarCopyInits.find(VD);
George Burgess IV00f70bd2018-03-01 05:43:23 +00002478 return (I != BlockVarCopyInits.end()) ? I->second : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002479}
2480
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002481/// Set the copy inialization expression of a block var decl.
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002482void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2483 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002484 assert(VD->hasAttr<BlocksAttr>() &&
2485 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002486 BlockVarCopyInits[VD] = Init;
2487}
2488
John McCallbcd03502009-12-07 02:54:59 +00002489TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002490 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002491 if (!DataSize)
2492 DataSize = TypeLoc::getFullDataSizeForType(T);
2493 else
2494 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002495 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002496
Eugene Zelenko7855e772018-04-03 00:11:50 +00002497 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002498 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2499 new (TInfo) TypeSourceInfo(T);
2500 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002501}
2502
John McCallbcd03502009-12-07 02:54:59 +00002503TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002504 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002505 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002506 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002507 return DI;
2508}
2509
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002510const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002511ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002512 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002513}
2514
2515const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002516ASTContext::getASTObjCImplementationLayout(
2517 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002518 return getObjCLayout(D->getClassInterface(), D);
2519}
2520
Chris Lattner983a8bb2007-07-13 22:13:22 +00002521//===----------------------------------------------------------------------===//
2522// Type creation/memoization methods
2523//===----------------------------------------------------------------------===//
2524
Jay Foad39c79802011-01-12 09:06:06 +00002525QualType
John McCall33ddac02011-01-19 10:06:00 +00002526ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2527 unsigned fastQuals = quals.getFastQualifiers();
2528 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002529
2530 // Check if we've already instantiated this type.
2531 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002532 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002533 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002534 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2535 assert(eq->getQualifiers() == quals);
2536 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002537 }
2538
John McCall33ddac02011-01-19 10:06:00 +00002539 // If the base type is not canonical, make the appropriate canonical type.
2540 QualType canon;
2541 if (!baseType->isCanonicalUnqualified()) {
2542 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002543 canonSplit.Quals.addConsistentQualifiers(quals);
2544 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002545
2546 // Re-find the insert position.
2547 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2548 }
2549
Eugene Zelenko7855e772018-04-03 00:11:50 +00002550 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002551 ExtQualNodes.InsertNode(eq, insertPos);
2552 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002553}
2554
Alexander Richardson6d989432017-10-15 18:48:14 +00002555QualType ASTContext::getAddrSpaceQualType(QualType T,
2556 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002557 QualType CanT = getCanonicalType(T);
2558 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002559 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002560
John McCall8ccfcb52009-09-24 19:53:00 +00002561 // If we are composing extended qualifiers together, merge together
2562 // into one ExtQuals node.
2563 QualifierCollector Quals;
2564 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002565
John McCall8ccfcb52009-09-24 19:53:00 +00002566 // If this type already has an address space specified, it cannot get
2567 // another one.
2568 assert(!Quals.hasAddressSpace() &&
2569 "Type cannot be in multiple addr spaces!");
2570 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002571
John McCall8ccfcb52009-09-24 19:53:00 +00002572 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002573}
2574
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002575QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2576 // If we are composing extended qualifiers together, merge together
2577 // into one ExtQuals node.
2578 QualifierCollector Quals;
2579 const Type *TypeNode = Quals.strip(T);
2580
2581 // If the qualifier doesn't have an address space just return it.
2582 if (!Quals.hasAddressSpace())
2583 return T;
2584
2585 Quals.removeAddressSpace();
2586
2587 // Removal of the address space can mean there are no longer any
2588 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2589 // or required.
2590 if (Quals.hasNonFastQualifiers())
2591 return getExtQualType(TypeNode, Quals);
2592 else
2593 return QualType(TypeNode, Quals.getFastQualifiers());
2594}
2595
Chris Lattnerd60183d2009-02-18 22:53:11 +00002596QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002597 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002598 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002599 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002600 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002601
Eugene Zelenko7855e772018-04-03 00:11:50 +00002602 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002603 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002604 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002605 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2606 return getPointerType(ResultType);
2607 }
2608 }
Mike Stump11289f42009-09-09 15:08:12 +00002609
John McCall8ccfcb52009-09-24 19:53:00 +00002610 // If we are composing extended qualifiers together, merge together
2611 // into one ExtQuals node.
2612 QualifierCollector Quals;
2613 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002614
John McCall8ccfcb52009-09-24 19:53:00 +00002615 // If this type already has an ObjCGC specified, it cannot get
2616 // another one.
2617 assert(!Quals.hasObjCGCAttr() &&
2618 "Type cannot have multiple ObjCGCs!");
2619 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002620
John McCall8ccfcb52009-09-24 19:53:00 +00002621 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002622}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002623
John McCall4f5019e2010-12-19 02:44:49 +00002624const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2625 FunctionType::ExtInfo Info) {
2626 if (T->getExtInfo() == Info)
2627 return T;
2628
2629 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002630 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002631 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002632 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002633 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002634 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2635 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002636 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002637 }
2638
2639 return cast<FunctionType>(Result.getTypePtr());
2640}
2641
Richard Smith2a7d4812013-05-04 07:00:32 +00002642void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2643 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002644 FD = FD->getMostRecentDecl();
2645 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002646 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002647 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002648 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002649 if (FunctionDecl *Next = FD->getPreviousDecl())
2650 FD = Next;
2651 else
2652 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002653 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002654 if (ASTMutationListener *L = getASTMutationListener())
2655 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002656}
2657
Richard Smith0b3a4622014-11-13 20:01:57 +00002658/// Get a function type and produce the equivalent function type with the
2659/// specified exception specification. Type sugar that can be present on a
2660/// declaration of a function with an exception specification is permitted
2661/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002662QualType ASTContext::getFunctionTypeWithExceptionSpec(
2663 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002664 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002665 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002666 return getParenType(
2667 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002668
2669 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002670 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002671 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002672 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002673 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2674 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002675
2676 // Anything else must be a function type. Rebuild it with the new exception
2677 // specification.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002678 const auto *Proto = cast<FunctionProtoType>(Orig);
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002679 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002680 Proto->getReturnType(), Proto->getParamTypes(),
2681 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2682}
2683
Richard Smithdfe85e22016-12-15 02:35:39 +00002684bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2685 QualType U) {
2686 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002687 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002688 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2689 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002690}
2691
Richard Smith0b3a4622014-11-13 20:01:57 +00002692void ASTContext::adjustExceptionSpec(
2693 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2694 bool AsWritten) {
2695 // Update the type.
2696 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002697 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002698 FD->setType(Updated);
2699
2700 if (!AsWritten)
2701 return;
2702
2703 // Update the type in the type source information too.
2704 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2705 // If the type and the type-as-written differ, we may need to update
2706 // the type-as-written too.
2707 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002708 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002709
2710 // FIXME: When we get proper type location information for exceptions,
2711 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2712 // up the TypeSourceInfo;
2713 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2714 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2715 "TypeLoc size mismatch from updating exception specification");
2716 TSInfo->overrideType(Updated);
2717 }
2718}
2719
Chris Lattnerc6395932007-06-22 20:56:16 +00002720/// getComplexType - Return the uniqued reference to the type for a complex
2721/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002722QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002723 // Unique pointers, to guarantee there is only one pointer of a particular
2724 // structure.
2725 llvm::FoldingSetNodeID ID;
2726 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002727
Craig Topper36250ad2014-05-12 05:36:57 +00002728 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002729 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2730 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002731
Chris Lattnerc6395932007-06-22 20:56:16 +00002732 // If the pointee type isn't canonical, this won't be a canonical type either,
2733 // so fill in the canonical type field.
2734 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002735 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002736 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002737
Chris Lattnerc6395932007-06-22 20:56:16 +00002738 // Get the new insert position for the node we care about.
2739 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002740 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002741 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002742 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002743 Types.push_back(New);
2744 ComplexTypes.InsertNode(New, InsertPos);
2745 return QualType(New, 0);
2746}
2747
Chris Lattner970e54e2006-11-12 00:37:36 +00002748/// getPointerType - Return the uniqued reference to the type for a pointer to
2749/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002750QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002751 // Unique pointers, to guarantee there is only one pointer of a particular
2752 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002753 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002754 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002755
Craig Topper36250ad2014-05-12 05:36:57 +00002756 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002757 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002758 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002759
Chris Lattner7ccecb92006-11-12 08:50:50 +00002760 // If the pointee type isn't canonical, this won't be a canonical type either,
2761 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002762 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002763 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002764 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002765
Bob Wilsonc8541f22013-03-15 17:12:43 +00002766 // Get the new insert position for the node we care about.
2767 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002768 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002769 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002770 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002771 Types.push_back(New);
2772 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002773 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002774}
2775
Reid Kleckner0503a872013-12-05 01:23:43 +00002776QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2777 llvm::FoldingSetNodeID ID;
2778 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002779 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002780 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2781 if (AT)
2782 return QualType(AT, 0);
2783
2784 QualType Canonical = getCanonicalType(New);
2785
2786 // Get the new insert position for the node we care about.
2787 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002788 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002789
2790 AT = new (*this, TypeAlignment)
2791 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2792 Types.push_back(AT);
2793 AdjustedTypes.InsertNode(AT, InsertPos);
2794 return QualType(AT, 0);
2795}
2796
Reid Kleckner8a365022013-06-24 17:51:48 +00002797QualType ASTContext::getDecayedType(QualType T) const {
2798 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2799
Reid Kleckner8a365022013-06-24 17:51:48 +00002800 QualType Decayed;
2801
2802 // C99 6.7.5.3p7:
2803 // A declaration of a parameter as "array of type" shall be
2804 // adjusted to "qualified pointer to type", where the type
2805 // qualifiers (if any) are those specified within the [ and ] of
2806 // the array type derivation.
2807 if (T->isArrayType())
2808 Decayed = getArrayDecayedType(T);
2809
2810 // C99 6.7.5.3p8:
2811 // A declaration of a parameter as "function returning type"
2812 // shall be adjusted to "pointer to function returning type", as
2813 // in 6.3.2.1.
2814 if (T->isFunctionType())
2815 Decayed = getPointerType(T);
2816
Reid Kleckner0503a872013-12-05 01:23:43 +00002817 llvm::FoldingSetNodeID ID;
2818 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002819 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002820 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2821 if (AT)
2822 return QualType(AT, 0);
2823
Reid Kleckner8a365022013-06-24 17:51:48 +00002824 QualType Canonical = getCanonicalType(Decayed);
2825
2826 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002827 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002828 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002829
Reid Kleckner0503a872013-12-05 01:23:43 +00002830 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2831 Types.push_back(AT);
2832 AdjustedTypes.InsertNode(AT, InsertPos);
2833 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002834}
2835
Mike Stump11289f42009-09-09 15:08:12 +00002836/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002837/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002838QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002839 assert(T->isFunctionType() && "block of function types only");
2840 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002841 // structure.
2842 llvm::FoldingSetNodeID ID;
2843 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002844
Craig Topper36250ad2014-05-12 05:36:57 +00002845 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002846 if (BlockPointerType *PT =
2847 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2848 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002849
2850 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002851 // type either so fill in the canonical type field.
2852 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002853 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002854 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002855
Steve Naroffec33ed92008-08-27 16:04:49 +00002856 // Get the new insert position for the node we care about.
2857 BlockPointerType *NewIP =
2858 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002859 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002860 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002861 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002862 Types.push_back(New);
2863 BlockPointerTypes.InsertNode(New, InsertPos);
2864 return QualType(New, 0);
2865}
2866
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002867/// getLValueReferenceType - Return the uniqued reference to the type for an
2868/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002869QualType
2870ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002871 assert(getCanonicalType(T) != OverloadTy &&
2872 "Unresolved overloaded function type");
2873
Bill Wendling3708c182007-05-27 10:15:43 +00002874 // Unique pointers, to guarantee there is only one pointer of a particular
2875 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002876 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002877 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002878
Craig Topper36250ad2014-05-12 05:36:57 +00002879 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002880 if (LValueReferenceType *RT =
2881 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002882 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002883
Eugene Zelenko7855e772018-04-03 00:11:50 +00002884 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002885
Bill Wendling3708c182007-05-27 10:15:43 +00002886 // If the referencee type isn't canonical, this won't be a canonical type
2887 // either, so fill in the canonical type field.
2888 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002889 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2890 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2891 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002892
Bill Wendling3708c182007-05-27 10:15:43 +00002893 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002894 LValueReferenceType *NewIP =
2895 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002896 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002897 }
2898
Eugene Zelenko7855e772018-04-03 00:11:50 +00002899 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2900 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002901 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002902 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002903
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002904 return QualType(New, 0);
2905}
2906
2907/// getRValueReferenceType - Return the uniqued reference to the type for an
2908/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002909QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002910 // Unique pointers, to guarantee there is only one pointer of a particular
2911 // structure.
2912 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002913 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002914
Craig Topper36250ad2014-05-12 05:36:57 +00002915 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002916 if (RValueReferenceType *RT =
2917 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2918 return QualType(RT, 0);
2919
Eugene Zelenko7855e772018-04-03 00:11:50 +00002920 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002921
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002922 // If the referencee type isn't canonical, this won't be a canonical type
2923 // either, so fill in the canonical type field.
2924 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002925 if (InnerRef || !T.isCanonical()) {
2926 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2927 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002928
2929 // Get the new insert position for the node we care about.
2930 RValueReferenceType *NewIP =
2931 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002932 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002933 }
2934
Eugene Zelenko7855e772018-04-03 00:11:50 +00002935 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002936 Types.push_back(New);
2937 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002938 return QualType(New, 0);
2939}
2940
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002941/// getMemberPointerType - Return the uniqued reference to the type for a
2942/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002943QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002944 // Unique pointers, to guarantee there is only one pointer of a particular
2945 // structure.
2946 llvm::FoldingSetNodeID ID;
2947 MemberPointerType::Profile(ID, T, Cls);
2948
Craig Topper36250ad2014-05-12 05:36:57 +00002949 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002950 if (MemberPointerType *PT =
2951 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2952 return QualType(PT, 0);
2953
2954 // If the pointee or class type isn't canonical, this won't be a canonical
2955 // type either, so fill in the canonical type field.
2956 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002957 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002958 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2959
2960 // Get the new insert position for the node we care about.
2961 MemberPointerType *NewIP =
2962 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002963 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002964 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002965 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002966 Types.push_back(New);
2967 MemberPointerTypes.InsertNode(New, InsertPos);
2968 return QualType(New, 0);
2969}
2970
Mike Stump11289f42009-09-09 15:08:12 +00002971/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002972/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002973QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002974 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002975 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002976 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002977 assert((EltTy->isDependentType() ||
2978 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002979 "Constant array of VLAs is illegal!");
2980
Chris Lattnere2df3f92009-05-13 04:12:56 +00002981 // Convert the array size into a canonical width matching the pointer size for
2982 // the target.
2983 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00002984 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00002985
Chris Lattner23b7eb62007-06-15 23:05:46 +00002986 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002987 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002988
Craig Topper36250ad2014-05-12 05:36:57 +00002989 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002990 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002991 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002992 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002993
John McCall33ddac02011-01-19 10:06:00 +00002994 // If the element type isn't canonical or has qualifiers, this won't
2995 // be a canonical type either, so fill in the canonical type field.
2996 QualType Canon;
2997 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2998 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002999 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003000 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003001 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003002
Chris Lattner36f8e652007-01-27 08:31:04 +00003003 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003004 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003005 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003006 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003007 }
Mike Stump11289f42009-09-09 15:08:12 +00003008
Eugene Zelenko7855e772018-04-03 00:11:50 +00003009 auto *New = new (*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003010 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003011 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003012 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003013 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003014}
3015
John McCall06549462011-01-18 08:40:38 +00003016/// getVariableArrayDecayedType - Turns the given type, which may be
3017/// variably-modified, into the corresponding type with all the known
3018/// sizes replaced with [*].
3019QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3020 // Vastly most common case.
3021 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003022
John McCall06549462011-01-18 08:40:38 +00003023 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003024
John McCall06549462011-01-18 08:40:38 +00003025 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003026 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003027 switch (ty->getTypeClass()) {
3028#define TYPE(Class, Base)
3029#define ABSTRACT_TYPE(Class, Base)
3030#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3031#include "clang/AST/TypeNodes.def"
3032 llvm_unreachable("didn't desugar past all non-canonical types?");
3033
3034 // These types should never be variably-modified.
3035 case Type::Builtin:
3036 case Type::Complex:
3037 case Type::Vector:
3038 case Type::ExtVector:
3039 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003040 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003041 case Type::ObjCObject:
3042 case Type::ObjCInterface:
3043 case Type::ObjCObjectPointer:
3044 case Type::Record:
3045 case Type::Enum:
3046 case Type::UnresolvedUsing:
3047 case Type::TypeOfExpr:
3048 case Type::TypeOf:
3049 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003050 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003051 case Type::DependentName:
3052 case Type::InjectedClassName:
3053 case Type::TemplateSpecialization:
3054 case Type::DependentTemplateSpecialization:
3055 case Type::TemplateTypeParm:
3056 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003057 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003058 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003059 case Type::PackExpansion:
3060 llvm_unreachable("type should never be variably-modified");
3061
3062 // These types can be variably-modified but should never need to
3063 // further decay.
3064 case Type::FunctionNoProto:
3065 case Type::FunctionProto:
3066 case Type::BlockPointer:
3067 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003068 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003069 return type;
3070
3071 // These types can be variably-modified. All these modifications
3072 // preserve structure except as noted by comments.
3073 // TODO: if we ever care about optimizing VLAs, there are no-op
3074 // optimizations available here.
3075 case Type::Pointer:
3076 result = getPointerType(getVariableArrayDecayedType(
3077 cast<PointerType>(ty)->getPointeeType()));
3078 break;
3079
3080 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003081 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003082 result = getLValueReferenceType(
3083 getVariableArrayDecayedType(lv->getPointeeType()),
3084 lv->isSpelledAsLValue());
3085 break;
3086 }
3087
3088 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003089 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003090 result = getRValueReferenceType(
3091 getVariableArrayDecayedType(lv->getPointeeType()));
3092 break;
3093 }
3094
Eli Friedman0dfb8892011-10-06 23:00:33 +00003095 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003096 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003097 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3098 break;
3099 }
3100
John McCall06549462011-01-18 08:40:38 +00003101 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003102 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003103 result = getConstantArrayType(
3104 getVariableArrayDecayedType(cat->getElementType()),
3105 cat->getSize(),
3106 cat->getSizeModifier(),
3107 cat->getIndexTypeCVRQualifiers());
3108 break;
3109 }
3110
3111 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003112 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003113 result = getDependentSizedArrayType(
3114 getVariableArrayDecayedType(dat->getElementType()),
3115 dat->getSizeExpr(),
3116 dat->getSizeModifier(),
3117 dat->getIndexTypeCVRQualifiers(),
3118 dat->getBracketsRange());
3119 break;
3120 }
3121
3122 // Turn incomplete types into [*] types.
3123 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003124 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003125 result = getVariableArrayType(
3126 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003127 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003128 ArrayType::Normal,
3129 iat->getIndexTypeCVRQualifiers(),
3130 SourceRange());
3131 break;
3132 }
3133
3134 // Turn VLA types into [*] types.
3135 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003136 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003137 result = getVariableArrayType(
3138 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003139 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003140 ArrayType::Star,
3141 vat->getIndexTypeCVRQualifiers(),
3142 vat->getBracketsRange());
3143 break;
3144 }
3145 }
3146
3147 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003148 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003149}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003150
Steve Naroffcadebd02007-08-30 18:14:25 +00003151/// getVariableArrayType - Returns a non-unique reference to the type for a
3152/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003153QualType ASTContext::getVariableArrayType(QualType EltTy,
3154 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003155 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003156 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003157 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003158 // Since we don't unique expressions, it isn't possible to unique VLA's
3159 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003160 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003161
John McCall33ddac02011-01-19 10:06:00 +00003162 // Be sure to pull qualifiers off the element type.
3163 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3164 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003165 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003166 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003167 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003168 }
3169
Eugene Zelenko7855e772018-04-03 00:11:50 +00003170 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003171 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003172
3173 VariableArrayTypes.push_back(New);
3174 Types.push_back(New);
3175 return QualType(New, 0);
3176}
3177
Douglas Gregor4619e432008-12-05 23:32:09 +00003178/// getDependentSizedArrayType - Returns a non-unique reference to
3179/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003180/// type.
John McCall33ddac02011-01-19 10:06:00 +00003181QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3182 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003183 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003184 unsigned elementTypeQuals,
3185 SourceRange brackets) const {
3186 assert((!numElements || numElements->isTypeDependent() ||
3187 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003188 "Size must be type- or value-dependent!");
3189
John McCall33ddac02011-01-19 10:06:00 +00003190 // Dependently-sized array types that do not have a specified number
3191 // of elements will have their sizes deduced from a dependent
3192 // initializer. We do no canonicalization here at all, which is okay
3193 // because they can't be used in most locations.
3194 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003195 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003196 = new (*this, TypeAlignment)
3197 DependentSizedArrayType(*this, elementType, QualType(),
3198 numElements, ASM, elementTypeQuals,
3199 brackets);
3200 Types.push_back(newType);
3201 return QualType(newType, 0);
3202 }
3203
3204 // Otherwise, we actually build a new type every time, but we
3205 // also build a canonical type.
3206
3207 SplitQualType canonElementType = getCanonicalType(elementType).split();
3208
Craig Topper36250ad2014-05-12 05:36:57 +00003209 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003210 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003211 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003212 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003213 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003214
John McCall33ddac02011-01-19 10:06:00 +00003215 // Look for an existing type with these properties.
3216 DependentSizedArrayType *canonTy =
3217 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003218
John McCall33ddac02011-01-19 10:06:00 +00003219 // If we don't have one, build one.
3220 if (!canonTy) {
3221 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003222 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003223 QualType(), numElements, ASM, elementTypeQuals,
3224 brackets);
3225 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3226 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003227 }
3228
John McCall33ddac02011-01-19 10:06:00 +00003229 // Apply qualifiers from the element type to the array.
3230 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003231 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003232
David Majnemer16a74702015-07-24 05:54:19 +00003233 // If we didn't need extra canonicalization for the element type or the size
3234 // expression, then just use that as our result.
3235 if (QualType(canonElementType.Ty, 0) == elementType &&
3236 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003237 return canon;
3238
3239 // Otherwise, we need to build a type which follows the spelling
3240 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003241 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003242 = new (*this, TypeAlignment)
3243 DependentSizedArrayType(*this, elementType, canon, numElements,
3244 ASM, elementTypeQuals, brackets);
3245 Types.push_back(sugaredType);
3246 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003247}
3248
John McCall33ddac02011-01-19 10:06:00 +00003249QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003250 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003251 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003252 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003253 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003254
Craig Topper36250ad2014-05-12 05:36:57 +00003255 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003256 if (IncompleteArrayType *iat =
3257 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3258 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003259
3260 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003261 // either, so fill in the canonical type field. We also have to pull
3262 // qualifiers off the element type.
3263 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003264
John McCall33ddac02011-01-19 10:06:00 +00003265 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3266 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003267 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003268 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003269 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003270
3271 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003272 IncompleteArrayType *existing =
3273 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3274 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003275 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003276
Eugene Zelenko7855e772018-04-03 00:11:50 +00003277 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003278 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003279
John McCall33ddac02011-01-19 10:06:00 +00003280 IncompleteArrayTypes.InsertNode(newType, insertPos);
3281 Types.push_back(newType);
3282 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003283}
3284
Steve Naroff91fcddb2007-07-18 18:00:27 +00003285/// getVectorType - Return the unique reference to a vector type of
3286/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003287QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003288 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003289 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003290
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003291 // Check if we've already instantiated a vector of this type.
3292 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003293 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003294
Craig Topper36250ad2014-05-12 05:36:57 +00003295 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003296 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3297 return QualType(VTP, 0);
3298
3299 // If the element type isn't canonical, this won't be a canonical type either,
3300 // so fill in the canonical type field.
3301 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003302 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003303 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003304
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003305 // Get the new insert position for the node we care about.
3306 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003307 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003308 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003309 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003310 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003311 VectorTypes.InsertNode(New, InsertPos);
3312 Types.push_back(New);
3313 return QualType(New, 0);
3314}
3315
Nate Begemance4d7fc2008-04-18 23:10:10 +00003316/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003317/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003318QualType
3319ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003320 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003321
Steve Naroff91fcddb2007-07-18 18:00:27 +00003322 // Check if we've already instantiated a vector of this type.
3323 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003324 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003325 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003326 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003327 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3328 return QualType(VTP, 0);
3329
3330 // If the element type isn't canonical, this won't be a canonical type either,
3331 // so fill in the canonical type field.
3332 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003333 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003334 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003335
Steve Naroff91fcddb2007-07-18 18:00:27 +00003336 // Get the new insert position for the node we care about.
3337 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003338 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003339 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003340 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003341 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003342 VectorTypes.InsertNode(New, InsertPos);
3343 Types.push_back(New);
3344 return QualType(New, 0);
3345}
3346
Jay Foad39c79802011-01-12 09:06:06 +00003347QualType
3348ASTContext::getDependentSizedExtVectorType(QualType vecType,
3349 Expr *SizeExpr,
3350 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003351 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003352 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003353 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003354
Craig Topper36250ad2014-05-12 05:36:57 +00003355 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003356 DependentSizedExtVectorType *Canon
3357 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3358 DependentSizedExtVectorType *New;
3359 if (Canon) {
3360 // We already have a canonical version of this array type; use it as
3361 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003362 New = new (*this, TypeAlignment)
3363 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3364 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003365 } else {
3366 QualType CanonVecTy = getCanonicalType(vecType);
3367 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003368 New = new (*this, TypeAlignment)
3369 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3370 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003371
3372 DependentSizedExtVectorType *CanonCheck
3373 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3374 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3375 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003376 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3377 } else {
3378 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3379 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003380 New = new (*this, TypeAlignment)
3381 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003382 }
3383 }
Mike Stump11289f42009-09-09 15:08:12 +00003384
Douglas Gregor758a8692009-06-17 21:51:59 +00003385 Types.push_back(New);
3386 return QualType(New, 0);
3387}
3388
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003389QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3390 Expr *AddrSpaceExpr,
3391 SourceLocation AttrLoc) const {
3392 assert(AddrSpaceExpr->isInstantiationDependent());
3393
3394 QualType canonPointeeType = getCanonicalType(PointeeType);
3395
3396 void *insertPos = nullptr;
3397 llvm::FoldingSetNodeID ID;
3398 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3399 AddrSpaceExpr);
3400
3401 DependentAddressSpaceType *canonTy =
3402 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3403
3404 if (!canonTy) {
3405 canonTy = new (*this, TypeAlignment)
3406 DependentAddressSpaceType(*this, canonPointeeType,
3407 QualType(), AddrSpaceExpr, AttrLoc);
3408 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3409 Types.push_back(canonTy);
3410 }
3411
3412 if (canonPointeeType == PointeeType &&
3413 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
3414 return QualType(canonTy, 0);
3415
Eugene Zelenko7855e772018-04-03 00:11:50 +00003416 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003417 = new (*this, TypeAlignment)
3418 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
3419 AddrSpaceExpr, AttrLoc);
3420 Types.push_back(sugaredType);
3421 return QualType(sugaredType, 0);
3422}
3423
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003424/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003425static bool isCanonicalResultType(QualType T) {
3426 return T.isCanonical() &&
3427 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3428 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3429}
3430
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003431/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003432QualType
3433ASTContext::getFunctionNoProtoType(QualType ResultTy,
3434 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003435 // Unique functions, to guarantee there is only one function of a particular
3436 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003437 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003438 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003439
Craig Topper36250ad2014-05-12 05:36:57 +00003440 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003441 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003442 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003443 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003444
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003445 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003446 if (!isCanonicalResultType(ResultTy)) {
3447 Canonical =
3448 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003449
Chris Lattner47955de2007-01-27 08:37:20 +00003450 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003451 FunctionNoProtoType *NewIP =
3452 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003453 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003454 }
Mike Stump11289f42009-09-09 15:08:12 +00003455
Eugene Zelenko7855e772018-04-03 00:11:50 +00003456 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003457 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003458 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003459 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003460 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003461}
3462
Douglas Gregora602a152015-10-01 20:20:47 +00003463CanQualType
3464ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3465 CanQualType CanResultType = getCanonicalType(ResultType);
3466
3467 // Canonical result types do not have ARC lifetime qualifiers.
3468 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3469 Qualifiers Qs = CanResultType.getQualifiers();
3470 Qs.removeObjCLifetime();
3471 return CanQualType::CreateUnsafe(
3472 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3473 }
3474
3475 return CanResultType;
3476}
3477
Richard Smith3c4f8d22016-10-16 17:54:23 +00003478static bool isCanonicalExceptionSpecification(
3479 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3480 if (ESI.Type == EST_None)
3481 return true;
3482 if (!NoexceptInType)
3483 return false;
3484
3485 // C++17 onwards: exception specification is part of the type, as a simple
3486 // boolean "can this function type throw".
3487 if (ESI.Type == EST_BasicNoexcept)
3488 return true;
3489
Richard Smitheaf11ad2018-05-03 03:58:32 +00003490 // A noexcept(expr) specification is (possibly) canonical if expr is
3491 // value-dependent.
3492 if (ESI.Type == EST_DependentNoexcept)
3493 return true;
3494
Richard Smith3c4f8d22016-10-16 17:54:23 +00003495 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003496 // expansions (so we can't tell whether it's non-throwing) and all its
3497 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003498 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003499 bool AnyPackExpansions = false;
3500 for (QualType ET : ESI.Exceptions) {
3501 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003502 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003503 if (ET->getAs<PackExpansionType>())
3504 AnyPackExpansions = true;
3505 }
3506 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003507 }
3508
Richard Smith3c4f8d22016-10-16 17:54:23 +00003509 return false;
3510}
3511
Richard Smith304b1242016-10-18 20:13:25 +00003512QualType ASTContext::getFunctionTypeInternal(
3513 QualType ResultTy, ArrayRef<QualType> ArgArray,
3514 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003515 size_t NumArgs = ArgArray.size();
3516
Richard Smith2a2cda52016-10-18 19:29:18 +00003517 // Unique functions, to guarantee there is only one function of a particular
3518 // structure.
3519 llvm::FoldingSetNodeID ID;
3520 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3521 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003522
Richard Smith2a2cda52016-10-18 19:29:18 +00003523 QualType Canonical;
3524 bool Unique = false;
3525
3526 void *InsertPos = nullptr;
3527 if (FunctionProtoType *FPT =
3528 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3529 QualType Existing = QualType(FPT, 0);
3530
3531 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3532 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003533 // noexcept expression, or we're just looking for a canonical type.
3534 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003535 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003536 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003537 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3538 return Existing;
3539
3540 // We need a new type sugar node for this one, to hold the new noexcept
3541 // expression. We do no canonicalization here, but that's OK since we don't
3542 // expect to see the same noexcept expression much more than once.
3543 Canonical = getCanonicalType(Existing);
3544 Unique = true;
3545 }
3546
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003547 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003548 bool IsCanonicalExceptionSpec =
3549 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3550
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003551 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003552 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003553 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003554 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003555 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003556 isCanonical = false;
3557
Richard Smith304b1242016-10-18 20:13:25 +00003558 if (OnlyWantCanonical)
3559 assert(isCanonical &&
3560 "given non-canonical parameters constructing canonical type");
3561
Richard Smith2a2cda52016-10-18 19:29:18 +00003562 // If this type isn't canonical, get the canonical version of it if we don't
3563 // already have it. The exception spec is only partially part of the
3564 // canonical type, and only in C++17 onwards.
3565 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003566 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003567 CanonicalArgs.reserve(NumArgs);
3568 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003569 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003570
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003571 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003572 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003573 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003574
3575 if (IsCanonicalExceptionSpec) {
3576 // Exception spec is already OK.
3577 } else if (NoexceptInType) {
3578 switch (EPI.ExceptionSpec.Type) {
3579 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3580 // We don't know yet. It shouldn't matter what we pick here; no-one
3581 // should ever look at this.
3582 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003583 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003584 CanonicalEPI.ExceptionSpec.Type = EST_None;
3585 break;
3586
Richard Smith2a2cda52016-10-18 19:29:18 +00003587 // A dynamic exception specification is almost always "not noexcept",
3588 // with the exception that a pack expansion might expand to no types.
3589 case EST_Dynamic: {
3590 bool AnyPacks = false;
3591 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3592 if (ET->getAs<PackExpansionType>())
3593 AnyPacks = true;
3594 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3595 }
3596 if (!AnyPacks)
3597 CanonicalEPI.ExceptionSpec.Type = EST_None;
3598 else {
3599 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3600 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3601 }
3602 break;
3603 }
3604
Richard Smitheaf11ad2018-05-03 03:58:32 +00003605 case EST_DynamicNone: case EST_BasicNoexcept: case EST_NoexceptTrue:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003606 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3607 break;
3608
Richard Smitheaf11ad2018-05-03 03:58:32 +00003609 case EST_DependentNoexcept:
3610 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003611 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003612 } else {
3613 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3614 }
John McCalldb40c7f2010-12-14 08:05:40 +00003615
Douglas Gregora602a152015-10-01 20:20:47 +00003616 // Adjust the canonical function result type.
3617 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003618 Canonical =
3619 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003620
Chris Lattnerfd4de792007-01-27 01:15:32 +00003621 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003622 FunctionProtoType *NewIP =
3623 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003624 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003625 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003626
John McCall31168b02011-06-15 23:02:42 +00003627 // FunctionProtoType objects are allocated with extra bytes after
3628 // them for three variable size arrays at the end:
3629 // - parameter types
3630 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003631 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003632 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003633 // expression, or information used to resolve the exception
3634 // specification.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003635 size_t Size =
3636 sizeof(FunctionProtoType) + NumArgs * sizeof(QualType) +
3637 FunctionProtoType::getExceptionSpecSize(
3638 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
John McCall18afab72016-03-01 00:49:02 +00003639
3640 // Put the ExtParameterInfos last. If all were equal, it would make
3641 // more sense to put these before the exception specification, because
3642 // it's much easier to skip past them compared to the elaborate switch
3643 // required to skip the exception specification. However, all is not
3644 // equal; ExtParameterInfos are used to model very uncommon features,
3645 // and it's better not to burden the more common paths.
3646 if (EPI.ExtParameterInfos) {
3647 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3648 }
John McCall31168b02011-06-15 23:02:42 +00003649
Eugene Zelenko7855e772018-04-03 00:11:50 +00003650 auto *FTP = (FunctionProtoType *) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003651 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003652 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003653 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003654 if (!Unique)
3655 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003656 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003657}
Chris Lattneref51c202006-11-10 07:17:23 +00003658
Joey Goulye3c85de2016-12-01 11:30:49 +00003659QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003660 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003661 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003662
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003663 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003664 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003665 return QualType(PT, 0);
3666
3667 // If the pipe element type isn't canonical, this won't be a canonical type
3668 // either, so fill in the canonical type field.
3669 QualType Canonical;
3670 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003671 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003672
3673 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003674 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003675 assert(!NewIP && "Shouldn't be in the map!");
3676 (void)NewIP;
3677 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003678 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003679 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003680 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003681 return QualType(New, 0);
3682}
3683
Anastasia Stulova59055b92018-05-09 13:23:26 +00003684QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3685 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3686 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3687 : Ty;
3688}
3689
Joey Goulye3c85de2016-12-01 11:30:49 +00003690QualType ASTContext::getReadPipeType(QualType T) const {
3691 return getPipeType(T, true);
3692}
3693
Joey Gouly5788b782016-11-18 14:10:54 +00003694QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003695 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003696}
3697
John McCalle78aac42010-03-10 03:28:59 +00003698#ifndef NDEBUG
3699static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3700 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003701 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003702 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3703 return true;
3704 if (RD->getDescribedClassTemplate() &&
3705 !isa<ClassTemplateSpecializationDecl>(RD))
3706 return true;
3707 return false;
3708}
3709#endif
3710
3711/// getInjectedClassNameType - Return the unique reference to the
3712/// injected class name type for the specified templated declaration.
3713QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003714 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003715 assert(NeedsInjectedClassNameType(Decl));
3716 if (Decl->TypeForDecl) {
3717 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003718 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003719 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3720 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3721 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3722 } else {
John McCall424cec92011-01-19 06:33:43 +00003723 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003724 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003725 Decl->TypeForDecl = newType;
3726 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003727 }
3728 return QualType(Decl->TypeForDecl, 0);
3729}
3730
Douglas Gregor83a586e2008-04-13 21:07:44 +00003731/// getTypeDeclType - Return the unique reference to the type for the
3732/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003733QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003734 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003735 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003736
Eugene Zelenko7855e772018-04-03 00:11:50 +00003737 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003738 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003739
John McCall96f0b5f2010-03-10 06:48:02 +00003740 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3741 "Template type parameter types are always available.");
3742
Eugene Zelenko7855e772018-04-03 00:11:50 +00003743 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003744 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003745 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003746 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003747 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003748 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003749 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003750 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003751 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3752 Decl->TypeForDecl = newType;
3753 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003754 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003755 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003756
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003757 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003758}
3759
Chris Lattner32d920b2007-01-26 02:01:53 +00003760/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003761/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003762QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003763ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3764 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003765 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003766
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003767 if (Canonical.isNull())
3768 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00003769 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003770 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003771 Decl->TypeForDecl = newType;
3772 Types.push_back(newType);
3773 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003774}
3775
Jay Foad39c79802011-01-12 09:06:06 +00003776QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003777 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3778
Douglas Gregorec9fd132012-01-14 16:38:05 +00003779 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003780 if (PrevDecl->TypeForDecl)
3781 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3782
Eugene Zelenko7855e772018-04-03 00:11:50 +00003783 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003784 Decl->TypeForDecl = newType;
3785 Types.push_back(newType);
3786 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003787}
3788
Jay Foad39c79802011-01-12 09:06:06 +00003789QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003790 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3791
Douglas Gregorec9fd132012-01-14 16:38:05 +00003792 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003793 if (PrevDecl->TypeForDecl)
3794 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3795
Eugene Zelenko7855e772018-04-03 00:11:50 +00003796 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003797 Decl->TypeForDecl = newType;
3798 Types.push_back(newType);
3799 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003800}
3801
John McCall81904512011-01-06 01:58:22 +00003802QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3803 QualType modifiedType,
3804 QualType equivalentType) {
3805 llvm::FoldingSetNodeID id;
3806 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3807
Craig Topper36250ad2014-05-12 05:36:57 +00003808 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003809 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3810 if (type) return QualType(type, 0);
3811
3812 QualType canon = getCanonicalType(equivalentType);
3813 type = new (*this, TypeAlignment)
3814 AttributedType(canon, attrKind, modifiedType, equivalentType);
3815
3816 Types.push_back(type);
3817 AttributedTypes.InsertNode(type, insertPos);
3818
3819 return QualType(type, 0);
3820}
3821
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003822/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00003823QualType
3824ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003825 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003826 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003827 && "replacement types must always be canonical");
3828
3829 llvm::FoldingSetNodeID ID;
3830 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003831 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003832 SubstTemplateTypeParmType *SubstParm
3833 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3834
3835 if (!SubstParm) {
3836 SubstParm = new (*this, TypeAlignment)
3837 SubstTemplateTypeParmType(Parm, Replacement);
3838 Types.push_back(SubstParm);
3839 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3840 }
3841
3842 return QualType(SubstParm, 0);
3843}
3844
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003845/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00003846QualType ASTContext::getSubstTemplateTypeParmPackType(
3847 const TemplateTypeParmType *Parm,
3848 const TemplateArgument &ArgPack) {
3849#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003850 for (const auto &P : ArgPack.pack_elements()) {
3851 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3852 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003853 }
3854#endif
3855
3856 llvm::FoldingSetNodeID ID;
3857 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003858 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003859 if (SubstTemplateTypeParmPackType *SubstParm
3860 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3861 return QualType(SubstParm, 0);
3862
3863 QualType Canon;
3864 if (!Parm->isCanonicalUnqualified()) {
3865 Canon = getCanonicalType(QualType(Parm, 0));
3866 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3867 ArgPack);
3868 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3869 }
3870
Eugene Zelenko7855e772018-04-03 00:11:50 +00003871 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00003872 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3873 ArgPack);
3874 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00003875 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Douglas Gregorada4b792011-01-14 02:55:32 +00003876 return QualType(SubstParm, 0);
3877}
3878
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003879/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003880/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003881/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003882QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003883 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003884 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003885 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003886 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003887 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003888 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003889 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3890
3891 if (TypeParm)
3892 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003893
Chandler Carruth08836322011-05-01 00:51:33 +00003894 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003895 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003896 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003897
3898 TemplateTypeParmType *TypeCheck
3899 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3900 assert(!TypeCheck && "Template type parameter canonical type broken");
3901 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003902 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003903 TypeParm = new (*this, TypeAlignment)
3904 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003905
3906 Types.push_back(TypeParm);
3907 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3908
3909 return QualType(TypeParm, 0);
3910}
3911
John McCalle78aac42010-03-10 03:28:59 +00003912TypeSourceInfo *
3913ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3914 SourceLocation NameLoc,
3915 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003916 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003917 assert(!Name.getAsDependentTemplateName() &&
3918 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003919 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003920
3921 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003922 TemplateSpecializationTypeLoc TL =
3923 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003924 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003925 TL.setTemplateNameLoc(NameLoc);
3926 TL.setLAngleLoc(Args.getLAngleLoc());
3927 TL.setRAngleLoc(Args.getRAngleLoc());
3928 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3929 TL.setArgLocInfo(i, Args[i].getLocInfo());
3930 return DI;
3931}
3932
Mike Stump11289f42009-09-09 15:08:12 +00003933QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003934ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003935 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003936 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003937 assert(!Template.getAsDependentTemplateName() &&
3938 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003939
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003940 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003941 ArgVec.reserve(Args.size());
3942 for (const TemplateArgumentLoc &Arg : Args.arguments())
3943 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003944
David Majnemer6fbeee32016-07-07 04:43:07 +00003945 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003946}
3947
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003948#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003949static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3950 for (const TemplateArgument &Arg : Args)
3951 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003952 return true;
3953
3954 return true;
3955}
3956#endif
3957
John McCall0ad16662009-10-29 08:12:44 +00003958QualType
3959ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003960 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003961 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003962 assert(!Template.getAsDependentTemplateName() &&
3963 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003964 // Look through qualified template names.
3965 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3966 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003967
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003968 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003969 Template.getAsTemplateDecl() &&
3970 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003971 QualType CanonType;
3972 if (!Underlying.isNull())
3973 CanonType = getCanonicalType(Underlying);
3974 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003975 // We can get here with an alias template when the specialization contains
3976 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003977 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003978 "Caller must compute aliased type");
3979 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003980 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003981 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003982
Douglas Gregora8e02e72009-07-28 23:00:59 +00003983 // Allocate the (non-canonical) template specialization type, but don't
3984 // try to unique it: these types typically have location information that
3985 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003986 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003987 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003988 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003989 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003990 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003991 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003992 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003993
Douglas Gregor8bf42052009-02-09 18:46:07 +00003994 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003995 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003996}
3997
David Majnemer6fbeee32016-07-07 04:43:07 +00003998QualType ASTContext::getCanonicalTemplateSpecializationType(
3999 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00004000 assert(!Template.getAsDependentTemplateName() &&
4001 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004002
Douglas Gregore29139c2011-03-03 17:04:51 +00004003 // Look through qualified template names.
4004 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4005 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00004006
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004007 // Build the canonical template specialization type.
4008 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004009 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004010 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004011 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004012 for (const TemplateArgument &Arg : Args)
4013 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004014
4015 // Determine whether this canonical template specialization type already
4016 // exists.
4017 llvm::FoldingSetNodeID ID;
4018 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004019 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004020
Craig Topper36250ad2014-05-12 05:36:57 +00004021 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004022 TemplateSpecializationType *Spec
4023 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4024
4025 if (!Spec) {
4026 // Allocate a new canonical template specialization type.
4027 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4028 sizeof(TemplateArgument) * NumArgs),
4029 TypeAlignment);
4030 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004031 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004032 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004033 Types.push_back(Spec);
4034 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4035 }
4036
4037 assert(Spec->isDependentType() &&
4038 "Non-dependent template-id type must have a canonical type");
4039 return QualType(Spec, 0);
4040}
4041
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004042QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4043 NestedNameSpecifier *NNS,
4044 QualType NamedType,
4045 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004046 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004047 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004048
Craig Topper36250ad2014-05-12 05:36:57 +00004049 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004050 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004051 if (T)
4052 return QualType(T, 0);
4053
Douglas Gregorc42075a2010-02-04 18:10:26 +00004054 QualType Canon = NamedType;
4055 if (!Canon.isCanonical()) {
4056 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004057 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4058 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004059 (void)CheckT;
4060 }
4061
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004062 T = new (*this, TypeAlignment)
4063 ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004064 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004065 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004066 return QualType(T, 0);
4067}
4068
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004069QualType
Jay Foad39c79802011-01-12 09:06:06 +00004070ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004071 llvm::FoldingSetNodeID ID;
4072 ParenType::Profile(ID, InnerType);
4073
Craig Topper36250ad2014-05-12 05:36:57 +00004074 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004075 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4076 if (T)
4077 return QualType(T, 0);
4078
4079 QualType Canon = InnerType;
4080 if (!Canon.isCanonical()) {
4081 Canon = getCanonicalType(InnerType);
4082 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4083 assert(!CheckT && "Paren canonical type broken");
4084 (void)CheckT;
4085 }
4086
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004087 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004088 Types.push_back(T);
4089 ParenTypes.InsertNode(T, InsertPos);
4090 return QualType(T, 0);
4091}
4092
Douglas Gregor02085352010-03-31 20:19:30 +00004093QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4094 NestedNameSpecifier *NNS,
4095 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004096 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004097 if (Canon.isNull()) {
4098 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004099 if (CanonNNS != NNS)
4100 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004101 }
4102
4103 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004104 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004105
Craig Topper36250ad2014-05-12 05:36:57 +00004106 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004107 DependentNameType *T
4108 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004109 if (T)
4110 return QualType(T, 0);
4111
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004112 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004113 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004114 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004115 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004116}
4117
Mike Stump11289f42009-09-09 15:08:12 +00004118QualType
John McCallc392f372010-06-11 00:33:02 +00004119ASTContext::getDependentTemplateSpecializationType(
4120 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004121 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004122 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004123 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004124 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004125 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004126 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4127 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004128 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004129}
4130
4131QualType
4132ASTContext::getDependentTemplateSpecializationType(
4133 ElaboratedTypeKeyword Keyword,
4134 NestedNameSpecifier *NNS,
4135 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004136 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00004137 assert((!NNS || NNS->isDependent()) &&
4138 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004139
Douglas Gregorc42075a2010-02-04 18:10:26 +00004140 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004141 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004142 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004143
Craig Topper36250ad2014-05-12 05:36:57 +00004144 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004145 DependentTemplateSpecializationType *T
4146 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004147 if (T)
4148 return QualType(T, 0);
4149
John McCallc392f372010-06-11 00:33:02 +00004150 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004151
John McCallc392f372010-06-11 00:33:02 +00004152 ElaboratedTypeKeyword CanonKeyword = Keyword;
4153 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4154
4155 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004156 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004157 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004158 for (unsigned I = 0; I != NumArgs; ++I) {
4159 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4160 if (!CanonArgs[I].structurallyEquals(Args[I]))
4161 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004162 }
4163
John McCallc392f372010-06-11 00:33:02 +00004164 QualType Canon;
4165 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4166 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004167 Name,
4168 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004169
4170 // Find the insert position again.
4171 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4172 }
4173
4174 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4175 sizeof(TemplateArgument) * NumArgs),
4176 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004177 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004178 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004179 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004180 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004181 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004182}
4183
Richard Smith32918772017-02-14 00:25:28 +00004184TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4185 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004186 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004187 QualType ArgType = getTypeDeclType(TTP);
4188 if (TTP->isParameterPack())
4189 ArgType = getPackExpansionType(ArgType, None);
4190
4191 Arg = TemplateArgument(ArgType);
4192 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4193 Expr *E = new (*this) DeclRefExpr(
4194 NTTP, /*enclosing*/false,
4195 NTTP->getType().getNonLValueExprType(*this),
4196 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4197
4198 if (NTTP->isParameterPack())
4199 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4200 None);
4201 Arg = TemplateArgument(E);
4202 } else {
4203 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4204 if (TTP->isParameterPack())
4205 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4206 else
4207 Arg = TemplateArgument(TemplateName(TTP));
4208 }
4209
4210 if (Param->isTemplateParameterPack())
4211 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4212
4213 return Arg;
4214}
4215
Richard Smith43e14d22016-12-23 02:10:11 +00004216void
4217ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4218 SmallVectorImpl<TemplateArgument> &Args) {
4219 Args.reserve(Args.size() + Params->size());
4220
Richard Smith32918772017-02-14 00:25:28 +00004221 for (NamedDecl *Param : *Params)
4222 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004223}
4224
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004225QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004226 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004227 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004228 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004229
4230 assert(Pattern->containsUnexpandedParameterPack() &&
4231 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004232 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004233 PackExpansionType *T
4234 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4235 if (T)
4236 return QualType(T, 0);
4237
4238 QualType Canon;
4239 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004240 Canon = getCanonicalType(Pattern);
4241 // The canonical type might not contain an unexpanded parameter pack, if it
4242 // contains an alias template specialization which ignores one of its
4243 // parameters.
4244 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004245 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004246
Richard Smith68eea502012-07-16 00:20:35 +00004247 // Find the insert position again, in case we inserted an element into
4248 // PackExpansionTypes and invalidated our insert position.
4249 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4250 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004251 }
4252
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004253 T = new (*this, TypeAlignment)
4254 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004255 Types.push_back(T);
4256 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004257 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004258}
4259
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004260/// CmpProtocolNames - Comparison predicate for sorting protocols
4261/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004262static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4263 ObjCProtocolDecl *const *RHS) {
4264 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004265}
4266
Craig Topper1f26d5b2016-01-03 19:43:23 +00004267static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4268 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004269
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004270 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4271 return false;
4272
Craig Topper1f26d5b2016-01-03 19:43:23 +00004273 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004274 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004275 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004276 return false;
4277 return true;
4278}
4279
Craig Topper6a8c1512015-10-22 01:56:18 +00004280static void
4281SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004282 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004283 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004284
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004285 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004286 for (ObjCProtocolDecl *&P : Protocols)
4287 P = P->getCanonicalDecl();
4288
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004289 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004290 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4291 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004292}
4293
John McCall8b07ec22010-05-15 11:32:37 +00004294QualType ASTContext::getObjCObjectType(QualType BaseType,
4295 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004296 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004297 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004298 llvm::makeArrayRef(Protocols, NumProtocols),
4299 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004300}
4301
4302QualType ASTContext::getObjCObjectType(
4303 QualType baseType,
4304 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004305 ArrayRef<ObjCProtocolDecl *> protocols,
4306 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004307 // If the base type is an interface and there aren't any protocols or
4308 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004309 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4310 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004311 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004312
4313 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004314 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004315 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004316 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004317 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4318 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004319
Douglas Gregore9d95f12015-07-07 03:57:35 +00004320 // Determine the type arguments to be used for canonicalization,
4321 // which may be explicitly specified here or written on the base
4322 // type.
4323 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4324 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004325 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004326 effectiveTypeArgs = baseObject->getTypeArgs();
4327 }
John McCallfc93cf92009-10-22 22:37:11 +00004328
Douglas Gregore9d95f12015-07-07 03:57:35 +00004329 // Build the canonical type, which has the canonical base type and a
4330 // sorted-and-uniqued list of protocols and the type arguments
4331 // canonicalized.
4332 QualType canonical;
4333 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4334 effectiveTypeArgs.end(),
4335 [&](QualType type) {
4336 return type.isCanonical();
4337 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004338 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004339 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4340 // Determine the canonical type arguments.
4341 ArrayRef<QualType> canonTypeArgs;
4342 SmallVector<QualType, 4> canonTypeArgsVec;
4343 if (!typeArgsAreCanonical) {
4344 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4345 for (auto typeArg : effectiveTypeArgs)
4346 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4347 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004348 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004349 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004350 }
4351
Douglas Gregore9d95f12015-07-07 03:57:35 +00004352 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4353 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4354 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004355 canonProtocolsVec.append(protocols.begin(), protocols.end());
4356 SortAndUniqueProtocols(canonProtocolsVec);
4357 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004358 } else {
4359 canonProtocols = protocols;
4360 }
4361
4362 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004363 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004364
John McCallfc93cf92009-10-22 22:37:11 +00004365 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004366 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4367 }
4368
Douglas Gregore9d95f12015-07-07 03:57:35 +00004369 unsigned size = sizeof(ObjCObjectTypeImpl);
4370 size += typeArgs.size() * sizeof(QualType);
4371 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4372 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004373 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004374 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4375 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004376
4377 Types.push_back(T);
4378 ObjCObjectTypes.InsertNode(T, InsertPos);
4379 return QualType(T, 0);
4380}
4381
Manman Ren3569eb52016-09-13 17:03:12 +00004382/// Apply Objective-C protocol qualifiers to the given type.
4383/// If this is for the canonical type of a type parameter, we can apply
4384/// protocol qualifiers on the ObjCObjectPointerType.
4385QualType
4386ASTContext::applyObjCProtocolQualifiers(QualType type,
4387 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4388 bool allowOnPointerType) const {
4389 hasError = false;
4390
Eugene Zelenko7855e772018-04-03 00:11:50 +00004391 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004392 return getObjCTypeParamType(objT->getDecl(), protocols);
4393 }
4394
Manman Ren3569eb52016-09-13 17:03:12 +00004395 // Apply protocol qualifiers to ObjCObjectPointerType.
4396 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004397 if (const auto *objPtr =
4398 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004399 const ObjCObjectType *objT = objPtr->getObjectType();
4400 // Merge protocol lists and construct ObjCObjectType.
4401 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4402 protocolsVec.append(objT->qual_begin(),
4403 objT->qual_end());
4404 protocolsVec.append(protocols.begin(), protocols.end());
4405 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4406 type = getObjCObjectType(
4407 objT->getBaseType(),
4408 objT->getTypeArgsAsWritten(),
4409 protocols,
4410 objT->isKindOfTypeAsWritten());
4411 return getObjCObjectPointerType(type);
4412 }
4413 }
4414
4415 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004416 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004417 // FIXME: Check for protocols to which the class type is already
4418 // known to conform.
4419
4420 return getObjCObjectType(objT->getBaseType(),
4421 objT->getTypeArgsAsWritten(),
4422 protocols,
4423 objT->isKindOfTypeAsWritten());
4424 }
4425
4426 // If the canonical type is ObjCObjectType, ...
4427 if (type->isObjCObjectType()) {
4428 // Silently overwrite any existing protocol qualifiers.
4429 // TODO: determine whether that's the right thing to do.
4430
4431 // FIXME: Check for protocols to which the class type is already
4432 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004433 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004434 }
4435
4436 // id<protocol-list>
4437 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004438 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004439 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004440 objPtr->isKindOfType());
4441 return getObjCObjectPointerType(type);
4442 }
4443
4444 // Class<protocol-list>
4445 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004446 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004447 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004448 objPtr->isKindOfType());
4449 return getObjCObjectPointerType(type);
4450 }
4451
4452 hasError = true;
4453 return type;
4454}
4455
Manman Rene6be26c2016-09-13 17:25:08 +00004456QualType
4457ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4458 ArrayRef<ObjCProtocolDecl *> protocols,
4459 QualType Canonical) const {
4460 // Look in the folding set for an existing type.
4461 llvm::FoldingSetNodeID ID;
4462 ObjCTypeParamType::Profile(ID, Decl, protocols);
4463 void *InsertPos = nullptr;
4464 if (ObjCTypeParamType *TypeParam =
4465 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4466 return QualType(TypeParam, 0);
4467
4468 if (Canonical.isNull()) {
4469 // We canonicalize to the underlying type.
4470 Canonical = getCanonicalType(Decl->getUnderlyingType());
4471 if (!protocols.empty()) {
4472 // Apply the protocol qualifers.
4473 bool hasError;
4474 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4475 true/*allowOnPointerType*/);
4476 assert(!hasError && "Error when apply protocol qualifier to bound type");
4477 }
4478 }
4479
4480 unsigned size = sizeof(ObjCTypeParamType);
4481 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4482 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004483 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004484
4485 Types.push_back(newType);
4486 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4487 return QualType(newType, 0);
4488}
4489
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004490/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4491/// protocol list adopt all protocols in QT's qualified-id protocol
4492/// list.
4493bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4494 ObjCInterfaceDecl *IC) {
4495 if (!QT->isObjCQualifiedIdType())
4496 return false;
4497
Eugene Zelenko7855e772018-04-03 00:11:50 +00004498 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004499 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004500 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004501 if (!IC->ClassImplementsProtocol(Proto, false))
4502 return false;
4503 }
4504 return true;
4505 }
4506 return false;
4507}
4508
4509/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4510/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4511/// of protocols.
4512bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4513 ObjCInterfaceDecl *IDecl) {
4514 if (!QT->isObjCQualifiedIdType())
4515 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004516 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004517 if (!OPT)
4518 return false;
4519 if (!IDecl->hasDefinition())
4520 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004521 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4522 CollectInheritedProtocols(IDecl, InheritedProtocols);
4523 if (InheritedProtocols.empty())
4524 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004525 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004526 // of IDecl's, then bridge casting is ok.
4527 bool Conforms = false;
4528 for (auto *Proto : OPT->quals()) {
4529 Conforms = false;
4530 for (auto *PI : InheritedProtocols) {
4531 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4532 Conforms = true;
4533 break;
4534 }
4535 }
4536 if (!Conforms)
4537 break;
4538 }
4539 if (Conforms)
4540 return true;
4541
Aaron Ballman83731462014-03-17 16:14:00 +00004542 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004543 // If both the right and left sides have qualifiers.
4544 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004545 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004546 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004547 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004548 break;
4549 }
4550 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004551 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004552 }
4553 return true;
4554}
4555
John McCall8b07ec22010-05-15 11:32:37 +00004556/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4557/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004558QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004559 llvm::FoldingSetNodeID ID;
4560 ObjCObjectPointerType::Profile(ID, ObjectT);
4561
Craig Topper36250ad2014-05-12 05:36:57 +00004562 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004563 if (ObjCObjectPointerType *QT =
4564 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4565 return QualType(QT, 0);
4566
4567 // Find the canonical object type.
4568 QualType Canonical;
4569 if (!ObjectT.isCanonical()) {
4570 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4571
4572 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004573 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4574 }
4575
Douglas Gregorf85bee62010-02-08 22:59:26 +00004576 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004577 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004578 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004579 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004580
Steve Narofffb4330f2009-06-17 22:40:22 +00004581 Types.push_back(QType);
4582 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004583 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004584}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004585
Douglas Gregor1c283312010-08-11 12:19:30 +00004586/// getObjCInterfaceType - Return the unique reference to the type for the
4587/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004588QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4589 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004590 if (Decl->TypeForDecl)
4591 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004592
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004593 if (PrevDecl) {
4594 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4595 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4596 return QualType(PrevDecl->TypeForDecl, 0);
4597 }
4598
Douglas Gregor7671e532011-12-16 16:34:57 +00004599 // Prefer the definition, if there is one.
4600 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4601 Decl = Def;
4602
Douglas Gregor1c283312010-08-11 12:19:30 +00004603 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004604 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004605 Decl->TypeForDecl = T;
4606 Types.push_back(T);
4607 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004608}
4609
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004610/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4611/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004612/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004613/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004614/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004615QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004616 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004617 if (tofExpr->isTypeDependent()) {
4618 llvm::FoldingSetNodeID ID;
4619 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004620
Craig Topper36250ad2014-05-12 05:36:57 +00004621 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004622 DependentTypeOfExprType *Canon
4623 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4624 if (Canon) {
4625 // We already have a "canonical" version of an identical, dependent
4626 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004627 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004628 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004629 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004630 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004631 Canon
4632 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004633 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4634 toe = Canon;
4635 }
4636 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004637 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004638 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004639 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004640 Types.push_back(toe);
4641 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004642}
4643
Steve Naroffa773cd52007-08-01 18:02:17 +00004644/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004645/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004646/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004647/// an issue. This doesn't affect the type checker, since it operates
4648/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004649QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004650 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004651 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004652 Types.push_back(tot);
4653 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004654}
4655
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004656/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004657/// nodes. This would never be helpful, since each such type has its own
4658/// expression, and would not give a significant memory saving, since there
4659/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004660QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004661 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004662
4663 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004664 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004665 // unique dependent type. Two such decltype-specifiers refer to the same
4666 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004667 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004668 llvm::FoldingSetNodeID ID;
4669 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004670
Craig Topper36250ad2014-05-12 05:36:57 +00004671 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004672 DependentDecltypeType *Canon
4673 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004674 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004675 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004676 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004677 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004678 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004679 dt = new (*this, TypeAlignment)
4680 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004681 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004682 dt = new (*this, TypeAlignment)
4683 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004684 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004685 Types.push_back(dt);
4686 return QualType(dt, 0);
4687}
4688
Alexis Hunte852b102011-05-24 22:41:36 +00004689/// getUnaryTransformationType - We don't unique these, since the memory
4690/// savings are minimal and these are rare.
4691QualType ASTContext::getUnaryTransformType(QualType BaseType,
4692 QualType UnderlyingType,
4693 UnaryTransformType::UTTKind Kind)
4694 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004695 UnaryTransformType *ut = nullptr;
4696
4697 if (BaseType->isDependentType()) {
4698 // Look in the folding set for an existing type.
4699 llvm::FoldingSetNodeID ID;
4700 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4701
4702 void *InsertPos = nullptr;
4703 DependentUnaryTransformType *Canon
4704 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4705
4706 if (!Canon) {
4707 // Build a new, canonical __underlying_type(type) type.
4708 Canon = new (*this, TypeAlignment)
4709 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4710 Kind);
4711 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4712 }
4713 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4714 QualType(), Kind,
4715 QualType(Canon, 0));
4716 } else {
4717 QualType CanonType = getCanonicalType(UnderlyingType);
4718 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4719 UnderlyingType, Kind,
4720 CanonType);
4721 }
4722 Types.push_back(ut);
4723 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004724}
4725
Richard Smith2a7d4812013-05-04 07:00:32 +00004726/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4727/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4728/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004729QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004730 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004731 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004732 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004733
Richard Smith2a7d4812013-05-04 07:00:32 +00004734 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004735 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004736 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004737 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004738 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4739 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004740
Eugene Zelenko7855e772018-04-03 00:11:50 +00004741 auto *AT = new (*this, TypeAlignment)
4742 AutoType(DeducedType, Keyword, IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004743 Types.push_back(AT);
4744 if (InsertPos)
4745 AutoTypes.InsertNode(AT, InsertPos);
4746 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004747}
4748
Richard Smith600b5262017-01-26 20:40:47 +00004749/// Return the uniqued reference to the deduced template specialization type
4750/// which has been deduced to the given type, or to the canonical undeduced
4751/// such type, or the canonical deduced-but-dependent such type.
4752QualType ASTContext::getDeducedTemplateSpecializationType(
4753 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4754 // Look in the folding set for an existing type.
4755 void *InsertPos = nullptr;
4756 llvm::FoldingSetNodeID ID;
4757 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4758 IsDependent);
4759 if (DeducedTemplateSpecializationType *DTST =
4760 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4761 return QualType(DTST, 0);
4762
Eugene Zelenko7855e772018-04-03 00:11:50 +00004763 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00004764 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4765 Types.push_back(DTST);
4766 if (InsertPos)
4767 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4768 return QualType(DTST, 0);
4769}
4770
Eli Friedman0dfb8892011-10-06 23:00:33 +00004771/// getAtomicType - Return the uniqued reference to the atomic type for
4772/// the given value type.
4773QualType ASTContext::getAtomicType(QualType T) const {
4774 // Unique pointers, to guarantee there is only one pointer of a particular
4775 // structure.
4776 llvm::FoldingSetNodeID ID;
4777 AtomicType::Profile(ID, T);
4778
Craig Topper36250ad2014-05-12 05:36:57 +00004779 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004780 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4781 return QualType(AT, 0);
4782
4783 // If the atomic value type isn't canonical, this won't be a canonical type
4784 // either, so fill in the canonical type field.
4785 QualType Canonical;
4786 if (!T.isCanonical()) {
4787 Canonical = getAtomicType(getCanonicalType(T));
4788
4789 // Get the new insert position for the node we care about.
4790 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004791 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004792 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00004793 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00004794 Types.push_back(New);
4795 AtomicTypes.InsertNode(New, InsertPos);
4796 return QualType(New, 0);
4797}
4798
Richard Smith02e85f32011-04-14 22:09:26 +00004799/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4800QualType ASTContext::getAutoDeductType() const {
4801 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004802 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004803 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004804 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004805 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004806 return AutoDeductTy;
4807}
4808
4809/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4810QualType ASTContext::getAutoRRefDeductType() const {
4811 if (AutoRRefDeductTy.isNull())
4812 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4813 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4814 return AutoRRefDeductTy;
4815}
4816
Chris Lattnerfb072462007-01-23 05:45:31 +00004817/// getTagDeclType - Return the unique reference to the type for the
4818/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004819QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004820 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004821 // FIXME: What is the design on getTagDeclType when it requires casting
4822 // away const? mutable?
4823 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004824}
4825
Mike Stump11289f42009-09-09 15:08:12 +00004826/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4827/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4828/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004829CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004830 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004831}
Chris Lattnerfb072462007-01-23 05:45:31 +00004832
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004833/// Return the unique signed counterpart of the integer type
4834/// corresponding to size_t.
4835CanQualType ASTContext::getSignedSizeType() const {
4836 return getFromTargetType(Target->getSignedSizeType());
4837}
4838
Hans Wennborg27541db2011-10-27 08:29:09 +00004839/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4840CanQualType ASTContext::getIntMaxType() const {
4841 return getFromTargetType(Target->getIntMaxType());
4842}
4843
4844/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4845CanQualType ASTContext::getUIntMaxType() const {
4846 return getFromTargetType(Target->getUIntMaxType());
4847}
4848
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004849/// getSignedWCharType - Return the type of "signed wchar_t".
4850/// Used when in C++, as a GCC extension.
4851QualType ASTContext::getSignedWCharType() const {
4852 // FIXME: derive from "Target" ?
4853 return WCharTy;
4854}
4855
4856/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4857/// Used when in C++, as a GCC extension.
4858QualType ASTContext::getUnsignedWCharType() const {
4859 // FIXME: derive from "Target" ?
4860 return UnsignedIntTy;
4861}
4862
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004863QualType ASTContext::getIntPtrType() const {
4864 return getFromTargetType(Target->getIntPtrType());
4865}
4866
4867QualType ASTContext::getUIntPtrType() const {
4868 return getCorrespondingUnsignedType(getIntPtrType());
4869}
4870
Hans Wennborg27541db2011-10-27 08:29:09 +00004871/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004872/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4873QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004874 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004875}
4876
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004877/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00004878/// integer type. The standard (C11 7.21.6.1p7) refers to this type
4879/// in the definition of %tu format specifier.
4880QualType ASTContext::getUnsignedPointerDiffType() const {
4881 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
4882}
4883
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004884/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00004885/// <sys/types.h>. We need this to compute the correct type for vfork().
4886QualType ASTContext::getProcessIDType() const {
4887 return getFromTargetType(Target->getProcessIDType());
4888}
4889
Chris Lattnera21ad802008-04-02 05:18:44 +00004890//===----------------------------------------------------------------------===//
4891// Type Operators
4892//===----------------------------------------------------------------------===//
4893
Jay Foad39c79802011-01-12 09:06:06 +00004894CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004895 // Push qualifiers into arrays, and then discard any remaining
4896 // qualifiers.
4897 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004898 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004899 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004900 QualType Result;
4901 if (isa<ArrayType>(Ty)) {
4902 Result = getArrayDecayedType(QualType(Ty,0));
4903 } else if (isa<FunctionType>(Ty)) {
4904 Result = getPointerType(QualType(Ty, 0));
4905 } else {
4906 Result = QualType(Ty, 0);
4907 }
4908
4909 return CanQualType::CreateUnsafe(Result);
4910}
4911
John McCall6c9dd522011-01-18 07:41:22 +00004912QualType ASTContext::getUnqualifiedArrayType(QualType type,
4913 Qualifiers &quals) {
4914 SplitQualType splitType = type.getSplitUnqualifiedType();
4915
4916 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4917 // the unqualified desugared type and then drops it on the floor.
4918 // We then have to strip that sugar back off with
4919 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004920 const auto *AT =
4921 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004922
4923 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004924 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004925 quals = splitType.Quals;
4926 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004927 }
4928
John McCall6c9dd522011-01-18 07:41:22 +00004929 // Otherwise, recurse on the array's element type.
4930 QualType elementType = AT->getElementType();
4931 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4932
4933 // If that didn't change the element type, AT has no qualifiers, so we
4934 // can just use the results in splitType.
4935 if (elementType == unqualElementType) {
4936 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004937 quals = splitType.Quals;
4938 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004939 }
4940
4941 // Otherwise, add in the qualifiers from the outermost type, then
4942 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004943 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004944
Eugene Zelenko7855e772018-04-03 00:11:50 +00004945 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004946 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004947 CAT->getSizeModifier(), 0);
4948 }
4949
Eugene Zelenko7855e772018-04-03 00:11:50 +00004950 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004951 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004952 }
4953
Eugene Zelenko7855e772018-04-03 00:11:50 +00004954 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004955 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004956 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004957 VAT->getSizeModifier(),
4958 VAT->getIndexTypeCVRQualifiers(),
4959 VAT->getBracketsRange());
4960 }
4961
Eugene Zelenko7855e772018-04-03 00:11:50 +00004962 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004963 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004964 DSAT->getSizeModifier(), 0,
4965 SourceRange());
4966}
4967
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004968/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4969/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4970/// they point to and return true. If T1 and T2 aren't pointer types
4971/// or pointer-to-member types, or if they are not similar at this
4972/// level, returns false and leaves T1 and T2 unchanged. Top-level
4973/// qualifiers on T1 and T2 are ignored. This function will typically
4974/// be called in a loop that successively "unwraps" pointer and
4975/// pointer-to-member types to compare them at each level.
4976bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004977 const auto *T1PtrType = T1->getAs<PointerType>();
4978 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004979 if (T1PtrType && T2PtrType) {
4980 T1 = T1PtrType->getPointeeType();
4981 T2 = T2PtrType->getPointeeType();
4982 return true;
4983 }
4984
Eugene Zelenko7855e772018-04-03 00:11:50 +00004985 const auto *T1MPType = T1->getAs<MemberPointerType>();
4986 const auto *T2MPType = T2->getAs<MemberPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004987 if (T1MPType && T2MPType &&
4988 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4989 QualType(T2MPType->getClass(), 0))) {
4990 T1 = T1MPType->getPointeeType();
4991 T2 = T2MPType->getPointeeType();
4992 return true;
4993 }
4994
David Blaikiebbafb8a2012-03-11 07:00:24 +00004995 if (getLangOpts().ObjC1) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004996 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
4997 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004998 if (T1OPType && T2OPType) {
4999 T1 = T1OPType->getPointeeType();
5000 T2 = T2OPType->getPointeeType();
5001 return true;
5002 }
5003 }
5004
5005 // FIXME: Block pointers, too?
5006
5007 return false;
5008}
5009
Jay Foad39c79802011-01-12 09:06:06 +00005010DeclarationNameInfo
5011ASTContext::getNameForTemplate(TemplateName Name,
5012 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005013 switch (Name.getKind()) {
5014 case TemplateName::QualifiedTemplate:
5015 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005016 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005017 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5018 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005019
John McCalld9dfe3a2011-06-30 08:33:18 +00005020 case TemplateName::OverloadedTemplate: {
5021 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5022 // DNInfo work in progress: CHECKME: what about DNLoc?
5023 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5024 }
5025
5026 case TemplateName::DependentTemplate: {
5027 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005028 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005029 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005030 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5031 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005032 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005033 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5034 // DNInfo work in progress: FIXME: source locations?
5035 DeclarationNameLoc DNLoc;
5036 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5037 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5038 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005039 }
5040 }
5041
John McCalld9dfe3a2011-06-30 08:33:18 +00005042 case TemplateName::SubstTemplateTemplateParm: {
5043 SubstTemplateTemplateParmStorage *subst
5044 = Name.getAsSubstTemplateTemplateParm();
5045 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5046 NameLoc);
5047 }
5048
5049 case TemplateName::SubstTemplateTemplateParmPack: {
5050 SubstTemplateTemplateParmPackStorage *subst
5051 = Name.getAsSubstTemplateTemplateParmPack();
5052 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5053 NameLoc);
5054 }
5055 }
5056
5057 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005058}
5059
Jay Foad39c79802011-01-12 09:06:06 +00005060TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005061 switch (Name.getKind()) {
5062 case TemplateName::QualifiedTemplate:
5063 case TemplateName::Template: {
5064 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005065 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005066 Template = getCanonicalTemplateTemplateParmDecl(TTP);
5067
5068 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005069 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005070 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005071
John McCalld9dfe3a2011-06-30 08:33:18 +00005072 case TemplateName::OverloadedTemplate:
5073 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00005074
John McCalld9dfe3a2011-06-30 08:33:18 +00005075 case TemplateName::DependentTemplate: {
5076 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5077 assert(DTN && "Non-dependent template names must refer to template decls.");
5078 return DTN->CanonicalTemplateName;
5079 }
5080
5081 case TemplateName::SubstTemplateTemplateParm: {
5082 SubstTemplateTemplateParmStorage *subst
5083 = Name.getAsSubstTemplateTemplateParm();
5084 return getCanonicalTemplateName(subst->getReplacement());
5085 }
5086
5087 case TemplateName::SubstTemplateTemplateParmPack: {
5088 SubstTemplateTemplateParmPackStorage *subst
5089 = Name.getAsSubstTemplateTemplateParmPack();
5090 TemplateTemplateParmDecl *canonParameter
5091 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5092 TemplateArgument canonArgPack
5093 = getCanonicalTemplateArgument(subst->getArgumentPack());
5094 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5095 }
5096 }
5097
5098 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005099}
5100
Douglas Gregoradee3e32009-11-11 23:06:43 +00005101bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5102 X = getCanonicalTemplateName(X);
5103 Y = getCanonicalTemplateName(Y);
5104 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5105}
5106
Mike Stump11289f42009-09-09 15:08:12 +00005107TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005108ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005109 switch (Arg.getKind()) {
5110 case TemplateArgument::Null:
5111 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005112
Douglas Gregora8e02e72009-07-28 23:00:59 +00005113 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005114 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005115
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005116 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005117 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005118 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005119 }
Mike Stump11289f42009-09-09 15:08:12 +00005120
Eli Friedmanb826a002012-09-26 02:36:12 +00005121 case TemplateArgument::NullPtr:
5122 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5123 /*isNullPtr*/true);
5124
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005125 case TemplateArgument::Template:
5126 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005127
5128 case TemplateArgument::TemplateExpansion:
5129 return TemplateArgument(getCanonicalTemplateName(
5130 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005131 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005132
Douglas Gregora8e02e72009-07-28 23:00:59 +00005133 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005134 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005135
Douglas Gregora8e02e72009-07-28 23:00:59 +00005136 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005137 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005138
Douglas Gregora8e02e72009-07-28 23:00:59 +00005139 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005140 if (Arg.pack_size() == 0)
5141 return Arg;
5142
Eugene Zelenko7855e772018-04-03 00:11:50 +00005143 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005144 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005145 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005146 AEnd = Arg.pack_end();
5147 A != AEnd; (void)++A, ++Idx)
5148 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005149
Benjamin Kramercce63472015-08-05 09:40:22 +00005150 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005151 }
5152 }
5153
5154 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005155 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005156}
5157
Douglas Gregor333489b2009-03-27 23:10:48 +00005158NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005159ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005160 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005161 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005162
5163 switch (NNS->getKind()) {
5164 case NestedNameSpecifier::Identifier:
5165 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005166 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005167 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5168 NNS->getAsIdentifier());
5169
5170 case NestedNameSpecifier::Namespace:
5171 // A namespace is canonical; build a nested-name-specifier with
5172 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005173 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005174 NNS->getAsNamespace()->getOriginalNamespace());
5175
5176 case NestedNameSpecifier::NamespaceAlias:
5177 // A namespace is canonical; build a nested-name-specifier with
5178 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005179 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005180 NNS->getAsNamespaceAlias()->getNamespace()
5181 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005182
5183 case NestedNameSpecifier::TypeSpec:
5184 case NestedNameSpecifier::TypeSpecWithTemplate: {
5185 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005186
5187 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5188 // break it apart into its prefix and identifier, then reconsititute those
5189 // as the canonical nested-name-specifier. This is required to canonicalize
5190 // a dependent nested-name-specifier involving typedefs of dependent-name
5191 // types, e.g.,
5192 // typedef typename T::type T1;
5193 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005194 if (const auto *DNT = T->getAs<DependentNameType>())
Eli Friedman5358a0a2012-03-03 04:09:56 +00005195 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005196 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005197
Eli Friedman5358a0a2012-03-03 04:09:56 +00005198 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5199 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5200 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005201 return NestedNameSpecifier::Create(*this, nullptr, false,
5202 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005203 }
5204
5205 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005206 case NestedNameSpecifier::Super:
5207 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005208 return NNS;
5209 }
5210
David Blaikie8a40f702012-01-17 06:56:22 +00005211 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005212}
5213
Jay Foad39c79802011-01-12 09:06:06 +00005214const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005215 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005216 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005217 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005218 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005219 return AT;
5220 }
Mike Stump11289f42009-09-09 15:08:12 +00005221
John McCall8ccfcb52009-09-24 19:53:00 +00005222 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005223 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005224 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005225
John McCall8ccfcb52009-09-24 19:53:00 +00005226 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005227 // implements C99 6.7.3p8: "If the specification of an array type includes
5228 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005229
Chris Lattner7adf0762008-08-04 07:31:14 +00005230 // If we get here, we either have type qualifiers on the type, or we have
5231 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005232 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005233
John McCall33ddac02011-01-19 10:06:00 +00005234 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005235 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005236
Chris Lattner7adf0762008-08-04 07:31:14 +00005237 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005238 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005239 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005240 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005241
Chris Lattner7adf0762008-08-04 07:31:14 +00005242 // Otherwise, we have an array and we have qualifiers on it. Push the
5243 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005244 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005245
Eugene Zelenko7855e772018-04-03 00:11:50 +00005246 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005247 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5248 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005249 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005250 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005251 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5252 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005253 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005254
Eugene Zelenko7855e772018-04-03 00:11:50 +00005255 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005256 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005257 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005258 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005259 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005260 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005261 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005262
Eugene Zelenko7855e772018-04-03 00:11:50 +00005263 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005264 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005265 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005266 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005267 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005268 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005269}
5270
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005271QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005272 if (T->isArrayType() || T->isFunctionType())
5273 return getDecayedType(T);
5274 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005275}
5276
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005277QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005278 T = getVariableArrayDecayedType(T);
5279 T = getAdjustedParameterType(T);
5280 return T.getUnqualifiedType();
5281}
5282
David Majnemerd09a51c2015-03-03 01:50:05 +00005283QualType ASTContext::getExceptionObjectType(QualType T) const {
5284 // C++ [except.throw]p3:
5285 // A throw-expression initializes a temporary object, called the exception
5286 // object, the type of which is determined by removing any top-level
5287 // cv-qualifiers from the static type of the operand of throw and adjusting
5288 // the type from "array of T" or "function returning T" to "pointer to T"
5289 // or "pointer to function returning T", [...]
5290 T = getVariableArrayDecayedType(T);
5291 if (T->isArrayType() || T->isFunctionType())
5292 T = getDecayedType(T);
5293 return T.getUnqualifiedType();
5294}
5295
Chris Lattnera21ad802008-04-02 05:18:44 +00005296/// getArrayDecayedType - Return the properly qualified result of decaying the
5297/// specified array type to a pointer. This operation is non-trivial when
5298/// handling typedefs etc. The canonical type of "T" must be an array type,
5299/// this returns a pointer to a properly qualified element of the array.
5300///
5301/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005302QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005303 // Get the element type with 'getAsArrayType' so that we don't lose any
5304 // typedefs in the element type of the array. This also handles propagation
5305 // of type qualifiers from the array type into the element type if present
5306 // (C99 6.7.3p8).
5307 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5308 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005309
Chris Lattner7adf0762008-08-04 07:31:14 +00005310 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005311
5312 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005313 QualType Result = getQualifiedType(PtrTy,
5314 PrettyArrayType->getIndexTypeQualifiers());
5315
5316 // int x[_Nullable] -> int * _Nullable
5317 if (auto Nullability = Ty->getNullability(*this)) {
5318 Result = const_cast<ASTContext *>(this)->getAttributedType(
5319 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5320 }
5321 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005322}
5323
John McCall33ddac02011-01-19 10:06:00 +00005324QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5325 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005326}
5327
John McCall33ddac02011-01-19 10:06:00 +00005328QualType ASTContext::getBaseElementType(QualType type) const {
5329 Qualifiers qs;
5330 while (true) {
5331 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005332 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005333 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005334
John McCall33ddac02011-01-19 10:06:00 +00005335 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005336 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005337 }
Mike Stump11289f42009-09-09 15:08:12 +00005338
John McCall33ddac02011-01-19 10:06:00 +00005339 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005340}
5341
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005342/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005343uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005344ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5345 uint64_t ElementCount = 1;
5346 do {
5347 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005348 CA = dyn_cast_or_null<ConstantArrayType>(
5349 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005350 } while (CA);
5351 return ElementCount;
5352}
5353
Steve Naroff0af91202007-04-27 21:51:21 +00005354/// getFloatingRank - Return a relative rank for floating point types.
5355/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005356static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005357 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005358 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005359
John McCall9dd450b2009-09-21 23:43:11 +00005360 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5361 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005362 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005363 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005364 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005365 case BuiltinType::Float: return FloatRank;
5366 case BuiltinType::Double: return DoubleRank;
5367 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005368 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005369 }
5370}
5371
Mike Stump11289f42009-09-09 15:08:12 +00005372/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5373/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005374/// 'typeDomain' is a real floating point or complex type.
5375/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005376QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5377 QualType Domain) const {
5378 FloatingRank EltRank = getFloatingRank(Size);
5379 if (Domain->isComplexType()) {
5380 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005381 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005382 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005383 case FloatRank: return FloatComplexTy;
5384 case DoubleRank: return DoubleComplexTy;
5385 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005386 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005387 }
Steve Naroff0af91202007-04-27 21:51:21 +00005388 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005389
5390 assert(Domain->isRealFloatingType() && "Unknown domain!");
5391 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005392 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005393 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005394 case FloatRank: return FloatTy;
5395 case DoubleRank: return DoubleTy;
5396 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005397 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005398 }
David Blaikief47fa302012-01-17 02:30:50 +00005399 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005400}
5401
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005402/// getFloatingTypeOrder - Compare the rank of the two specified floating
5403/// point types, ignoring the domain of the type (i.e. 'double' ==
5404/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005405/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005406int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005407 FloatingRank LHSR = getFloatingRank(LHS);
5408 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005409
Chris Lattnerb90739d2008-04-06 23:38:49 +00005410 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005411 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005412 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005413 return 1;
5414 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005415}
5416
Chris Lattner76a00cf2008-04-06 22:59:24 +00005417/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5418/// routine will assert if passed a built-in type that isn't an integer or enum,
5419/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005420unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005421 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005422
Chris Lattner76a00cf2008-04-06 22:59:24 +00005423 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005424 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005425 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005426 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005427 case BuiltinType::Char_S:
5428 case BuiltinType::Char_U:
5429 case BuiltinType::SChar:
5430 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005431 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005432 case BuiltinType::Short:
5433 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005434 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005435 case BuiltinType::Int:
5436 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005437 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005438 case BuiltinType::Long:
5439 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005440 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005441 case BuiltinType::LongLong:
5442 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005443 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005444 case BuiltinType::Int128:
5445 case BuiltinType::UInt128:
5446 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005447 }
5448}
5449
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005450/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005451/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5452///
5453/// \returns the type this bit-field will promote to, or NULL if no
5454/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005455QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005456 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005457 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005458
Richard Smithaadb2542018-06-28 21:17:55 +00005459 // C++ [conv.prom]p5:
5460 // If the bit-field has an enumerated type, it is treated as any other
5461 // value of that type for promotion purposes.
5462 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5463 return {};
5464
Richard Smith5b571672014-09-24 23:55:00 +00005465 // FIXME: We should not do this unless E->refersToBitField() is true. This
5466 // matters in C where getSourceBitField() will find bit-fields for various
5467 // cases where the source expression is not a bit-field designator.
5468
John McCalld25db7e2013-05-06 21:39:12 +00005469 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005470 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005471 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005472
5473 QualType FT = Field->getType();
5474
Richard Smithcaf33902011-10-10 18:28:20 +00005475 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005476 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005477 // C++ [conv.prom]p5:
5478 // A prvalue for an integral bit-field can be converted to a prvalue of type
5479 // int if int can represent all the values of the bit-field; otherwise, it
5480 // can be converted to unsigned int if unsigned int can represent all the
5481 // values of the bit-field. If the bit-field is larger yet, no integral
5482 // promotion applies to it.
5483 // C11 6.3.1.1/2:
5484 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5485 // If an int can represent all values of the original type (as restricted by
5486 // the width, for a bit-field), the value is converted to an int; otherwise,
5487 // it is converted to an unsigned int.
5488 //
5489 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5490 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005491 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5492 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005493 if (BitWidth < IntSize)
5494 return IntTy;
5495
5496 if (BitWidth == IntSize)
5497 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5498
Richard Smithaadb2542018-06-28 21:17:55 +00005499 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005500 // like the base type. GCC has some weird bugs in this area that we
5501 // deliberately do not follow (GCC follows a pre-standard resolution to
5502 // C's DR315 which treats bit-width as being part of the type, and this leaks
5503 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005504 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005505}
5506
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005507/// getPromotedIntegerType - Returns the type that Promotable will
5508/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5509/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005510QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005511 assert(!Promotable.isNull());
5512 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005513 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005514 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005515
Eugene Zelenko7855e772018-04-03 00:11:50 +00005516 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005517 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5518 // (3.9.1) can be converted to a prvalue of the first of the following
5519 // types that can represent all the values of its underlying type:
5520 // int, unsigned int, long int, unsigned long int, long long int, or
5521 // unsigned long long int [...]
5522 // FIXME: Is there some better way to compute this?
5523 if (BT->getKind() == BuiltinType::WChar_S ||
5524 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005525 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005526 BT->getKind() == BuiltinType::Char16 ||
5527 BT->getKind() == BuiltinType::Char32) {
5528 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5529 uint64_t FromSize = getTypeSize(BT);
5530 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5531 LongLongTy, UnsignedLongLongTy };
5532 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5533 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5534 if (FromSize < ToSize ||
5535 (FromSize == ToSize &&
5536 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5537 return PromoteTypes[Idx];
5538 }
5539 llvm_unreachable("char type should fit into long long");
5540 }
5541 }
5542
5543 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005544 if (Promotable->isSignedIntegerType())
5545 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005546 uint64_t PromotableSize = getIntWidth(Promotable);
5547 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005548 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5549 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5550}
5551
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005552/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005553/// type and returns its ownership.
5554Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5555 while (!T.isNull()) {
5556 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5557 return T.getObjCLifetime();
5558 if (T->isArrayType())
5559 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005560 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005561 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005562 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005563 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005564 else
5565 break;
5566 }
5567
5568 return Qualifiers::OCL_None;
5569}
5570
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005571static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5572 // Incomplete enum types are not treated as integer types.
5573 // FIXME: In C++, enum types are never integer types.
5574 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5575 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005576 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005577}
5578
Mike Stump11289f42009-09-09 15:08:12 +00005579/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005580/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005581/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005582int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005583 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5584 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005585
5586 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005587 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005588 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005589 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005590 RHSC = getIntegerTypeForEnum(ET);
5591
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005592 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005593
Chris Lattner76a00cf2008-04-06 22:59:24 +00005594 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5595 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005596
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005597 unsigned LHSRank = getIntegerRank(LHSC);
5598 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005599
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005600 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5601 if (LHSRank == RHSRank) return 0;
5602 return LHSRank > RHSRank ? 1 : -1;
5603 }
Mike Stump11289f42009-09-09 15:08:12 +00005604
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005605 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5606 if (LHSUnsigned) {
5607 // If the unsigned [LHS] type is larger, return it.
5608 if (LHSRank >= RHSRank)
5609 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005610
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005611 // If the signed type can represent all values of the unsigned type, it
5612 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005613 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005614 return -1;
5615 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005616
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005617 // If the unsigned [RHS] type is larger, return it.
5618 if (RHSRank >= LHSRank)
5619 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005620
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005621 // If the signed type can represent all values of the unsigned type, it
5622 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005623 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005624 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005625}
Anders Carlsson98f07902007-08-17 05:31:46 +00005626
Ben Langmuirf5416742016-02-04 00:55:24 +00005627TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005628 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005629 assert(!CFConstantStringTagDecl &&
5630 "tag and typedef should be initialized together");
5631 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5632 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005633
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005634 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005635 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005636
Anders Carlsson98f07902007-08-17 05:31:46 +00005637 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005638 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005639 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005640 // int flags;
5641 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005642 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005643 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005644 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005645 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005646 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005647 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005648 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005649
Anders Carlsson98f07902007-08-17 05:31:46 +00005650 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005651 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005652 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005653 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005654 SourceLocation(),
5655 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005656 FieldTypes[i], /*TInfo=*/nullptr,
5657 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005658 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005659 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005660 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005661 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005662 }
5663
Ben Langmuirf5416742016-02-04 00:55:24 +00005664 CFConstantStringTagDecl->completeDefinition();
5665 // This type is designed to be compatible with NSConstantString, but cannot
5666 // use the same name, since NSConstantString is an interface.
5667 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5668 CFConstantStringTypeDecl =
5669 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005670 }
Mike Stump11289f42009-09-09 15:08:12 +00005671
Quentin Colombet043406b2016-02-03 22:41:00 +00005672 return CFConstantStringTypeDecl;
5673}
5674
Ben Langmuirf5416742016-02-04 00:55:24 +00005675RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5676 if (!CFConstantStringTagDecl)
5677 getCFConstantStringDecl(); // Build the tag and the typedef.
5678 return CFConstantStringTagDecl;
5679}
5680
Quentin Colombet043406b2016-02-03 22:41:00 +00005681// getCFConstantStringType - Return the type used for constant CFStrings.
5682QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005683 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005684}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005685
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005686QualType ASTContext::getObjCSuperType() const {
5687 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005688 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005689 TUDecl->addDecl(ObjCSuperTypeDecl);
5690 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5691 }
5692 return ObjCSuperType;
5693}
5694
Douglas Gregor512b0772009-04-23 22:29:11 +00005695void ASTContext::setCFConstantStringType(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005696 const auto *TD = T->getAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00005697 assert(TD && "Invalid CFConstantStringType");
5698 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005699 const auto *TagType =
Ben Langmuirf5416742016-02-04 00:55:24 +00005700 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5701 assert(TagType && "Invalid CFConstantStringType");
5702 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005703}
5704
Jay Foad39c79802011-01-12 09:06:06 +00005705QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005706 if (BlockDescriptorType)
5707 return getTagDeclType(BlockDescriptorType);
5708
Alp Toker2dea15b2013-12-17 01:22:38 +00005709 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005710 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005711 RD = buildImplicitRecord("__block_descriptor");
5712 RD->startDefinition();
5713
Mike Stumpd0153282009-10-20 02:12:22 +00005714 QualType FieldTypes[] = {
5715 UnsignedLongTy,
5716 UnsignedLongTy,
5717 };
5718
Craig Topperd6d31ac2013-07-15 08:24:27 +00005719 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005720 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005721 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005722 };
5723
5724 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005725 FieldDecl *Field = FieldDecl::Create(
5726 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005727 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5728 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005729 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005730 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005731 }
5732
Alp Toker2dea15b2013-12-17 01:22:38 +00005733 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005734
Alp Toker2dea15b2013-12-17 01:22:38 +00005735 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005736
5737 return getTagDeclType(BlockDescriptorType);
5738}
5739
Jay Foad39c79802011-01-12 09:06:06 +00005740QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005741 if (BlockDescriptorExtendedType)
5742 return getTagDeclType(BlockDescriptorExtendedType);
5743
Alp Toker2dea15b2013-12-17 01:22:38 +00005744 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005745 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005746 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5747 RD->startDefinition();
5748
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005749 QualType FieldTypes[] = {
5750 UnsignedLongTy,
5751 UnsignedLongTy,
5752 getPointerType(VoidPtrTy),
5753 getPointerType(VoidPtrTy)
5754 };
5755
Craig Topperd6d31ac2013-07-15 08:24:27 +00005756 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005757 "reserved",
5758 "Size",
5759 "CopyFuncPtr",
5760 "DestroyFuncPtr"
5761 };
5762
5763 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005764 FieldDecl *Field = FieldDecl::Create(
5765 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005766 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5767 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005768 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005769 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005770 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005771 }
5772
Alp Toker2dea15b2013-12-17 01:22:38 +00005773 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005774
Alp Toker2dea15b2013-12-17 01:22:38 +00005775 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005776 return getTagDeclType(BlockDescriptorExtendedType);
5777}
5778
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00005779TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005780 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00005781
5782 if (!BT) {
5783 if (isa<PipeType>(T))
5784 return TargetInfo::OCLTK_Pipe;
5785
5786 return TargetInfo::OCLTK_Default;
5787 }
5788
5789 switch (BT->getKind()) {
5790#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5791 case BuiltinType::Id: \
5792 return TargetInfo::OCLTK_Image;
5793#include "clang/Basic/OpenCLImageTypes.def"
5794
5795 case BuiltinType::OCLClkEvent:
5796 return TargetInfo::OCLTK_ClkEvent;
5797
5798 case BuiltinType::OCLEvent:
5799 return TargetInfo::OCLTK_Event;
5800
5801 case BuiltinType::OCLQueue:
5802 return TargetInfo::OCLTK_Queue;
5803
5804 case BuiltinType::OCLReserveID:
5805 return TargetInfo::OCLTK_ReserveID;
5806
5807 case BuiltinType::OCLSampler:
5808 return TargetInfo::OCLTK_Sampler;
5809
5810 default:
5811 return TargetInfo::OCLTK_Default;
5812 }
5813}
5814
5815LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
5816 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
5817}
5818
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005819/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5820/// requires copy/dispose. Note that this must match the logic
5821/// in buildByrefHelpers.
5822bool ASTContext::BlockRequiresCopying(QualType Ty,
5823 const VarDecl *D) {
5824 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5825 const Expr *copyExpr = getBlockVarCopyInits(D);
5826 if (!copyExpr && record->hasTrivialDestructor()) return false;
5827
Mike Stump94967902009-10-21 18:16:27 +00005828 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005829 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005830
Akira Hatanaka7275da02018-02-28 07:15:55 +00005831 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
5832 // move or destroy.
5833 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
5834 return true;
5835
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005836 if (!Ty->isObjCRetainableType()) return false;
5837
5838 Qualifiers qs = Ty.getQualifiers();
5839
5840 // If we have lifetime, that dominates.
5841 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005842 switch (lifetime) {
5843 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5844
5845 // These are just bits as far as the runtime is concerned.
5846 case Qualifiers::OCL_ExplicitNone:
5847 case Qualifiers::OCL_Autoreleasing:
5848 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00005849
5850 // These cases should have been taken care of when checking the type's
5851 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005852 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005853 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00005854 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005855 }
5856 llvm_unreachable("fell out of lifetime switch!");
5857 }
5858 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5859 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005860}
5861
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005862bool ASTContext::getByrefLifetime(QualType Ty,
5863 Qualifiers::ObjCLifetime &LifeTime,
5864 bool &HasByrefExtendedLayout) const {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005865 if (!getLangOpts().ObjC1 ||
5866 getLangOpts().getGC() != LangOptions::NonGC)
5867 return false;
5868
5869 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005870 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005871 HasByrefExtendedLayout = true;
5872 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005873 } else if ((LifeTime = Ty.getObjCLifetime())) {
5874 // Honor the ARC qualifiers.
5875 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5876 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005877 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005878 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005879 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005880 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005881 return true;
5882}
5883
Douglas Gregorbab8a962011-09-08 01:46:34 +00005884TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5885 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005886 ObjCInstanceTypeDecl =
5887 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005888 return ObjCInstanceTypeDecl;
5889}
5890
Anders Carlsson18acd442007-10-29 06:33:42 +00005891// This returns true if a type has been typedefed to BOOL:
5892// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005893static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005894 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005895 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5896 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005897
Anders Carlssond8499822007-10-29 05:01:08 +00005898 return false;
5899}
5900
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005901/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005902/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005903CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005904 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5905 return CharUnits::Zero();
5906
Ken Dyck40775002010-01-11 17:06:35 +00005907 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005908
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005909 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005910 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005911 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005912 // Treat arrays as pointers, since that's how they're passed in.
5913 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005914 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005915 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005916}
5917
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005918bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005919 return getTargetInfo().getCXXABI().isMicrosoft() &&
5920 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00005921 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00005922 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005923}
5924
Richard Smithd9b90092016-07-02 01:32:16 +00005925ASTContext::InlineVariableDefinitionKind
5926ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5927 if (!VD->isInline())
5928 return InlineVariableDefinitionKind::None;
5929
5930 // In almost all cases, it's a weak definition.
5931 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00005932 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00005933 return InlineVariableDefinitionKind::Weak;
5934
5935 // If there's a file-context declaration in this translation unit, it's a
5936 // non-discardable definition.
5937 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00005938 if (D->getLexicalDeclContext()->isFileContext() &&
5939 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00005940 return InlineVariableDefinitionKind::Strong;
5941
5942 // If we've not seen one yet, we don't know.
5943 return InlineVariableDefinitionKind::WeakUnknown;
5944}
5945
Eugene Zelenko7855e772018-04-03 00:11:50 +00005946static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00005947 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005948}
5949
John McCall351762c2011-02-07 10:33:21 +00005950/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005951/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005952std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5953 std::string S;
5954
David Chisnall950a9512009-11-17 19:33:30 +00005955 const BlockDecl *Decl = Expr->getBlockDecl();
5956 QualType BlockTy =
5957 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5958 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005959 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005960 getObjCEncodingForMethodParameter(
5961 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5962 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005963 else
Alp Toker314cc812014-01-25 16:55:45 +00005964 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005965 // Compute size of all parameters.
5966 // Start with computing size of a pointer in number of bytes.
5967 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00005968 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5969 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005970 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005971 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005972 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005973 if (sz.isZero())
5974 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00005975 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005976 ParmOffset += sz;
5977 }
5978 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005979 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005980 // Block pointer and offset.
5981 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005982
5983 // Argument types.
5984 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005985 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005986 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005987 if (const auto *AT =
5988 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00005989 // Use array's original type only if it has known number of
5990 // elements.
5991 if (!isa<ConstantArrayType>(AT))
5992 PType = PVDecl->getType();
5993 } else if (PType->isFunctionType())
5994 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005995 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005996 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5997 S, true /*Extended*/);
5998 else
5999 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006000 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006001 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006002 }
John McCall351762c2011-02-07 10:33:21 +00006003
6004 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006005}
6006
John McCall843dfcc2016-11-29 21:57:00 +00006007std::string
6008ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6009 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006010 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006011 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006012 CharUnits ParmOffset;
6013 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006014 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006015 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006016 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006017 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006018 continue;
6019
John McCall843dfcc2016-11-29 21:57:00 +00006020 assert(sz.isPositive() &&
6021 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006022 ParmOffset += sz;
6023 }
6024 S += charUnitsToString(ParmOffset);
6025 ParmOffset = CharUnits::Zero();
6026
6027 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006028 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006029 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006030 if (const auto *AT =
6031 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006032 // Use array's original type only if it has known number of
6033 // elements.
6034 if (!isa<ConstantArrayType>(AT))
6035 PType = PVDecl->getType();
6036 } else if (PType->isFunctionType())
6037 PType = PVDecl->getType();
6038 getObjCEncodingForType(PType, S);
6039 S += charUnitsToString(ParmOffset);
6040 ParmOffset += getObjCEncodingTypeSize(PType);
6041 }
Douglas Gregora9d84932011-05-27 01:19:52 +00006042
John McCall843dfcc2016-11-29 21:57:00 +00006043 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006044}
6045
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006046/// getObjCEncodingForMethodParameter - Return the encoded type for a single
6047/// method parameter or return type. If Extended, include class names and
6048/// block object types.
6049void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6050 QualType T, std::string& S,
6051 bool Extended) const {
6052 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6053 getObjCEncodingForTypeQualifier(QT, S);
6054 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00006055 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006056 true /*OutermostType*/,
6057 false /*EncodingProperty*/,
6058 false /*StructField*/,
6059 Extended /*EncodeBlockParameters*/,
6060 Extended /*EncodeClassNames*/);
6061}
6062
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006063/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006064/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006065std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6066 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006067 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006068 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006069 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006070 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6071 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006072 // Compute size of all parameters.
6073 // Start with computing size of a pointer in number of bytes.
6074 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006075 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006076 // The first two arguments (self and _cmd) are pointers; account for
6077 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006078 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006079 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006080 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006081 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006082 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006083 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006084 continue;
6085
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006086 assert(sz.isPositive() &&
6087 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006088 ParmOffset += sz;
6089 }
Ken Dyck40775002010-01-11 17:06:35 +00006090 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006091 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006092 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006093
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006094 // Argument types.
6095 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006096 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006097 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006098 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006099 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006100 if (const auto *AT =
6101 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006102 // Use array's original type only if it has known number of
6103 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006104 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006105 PType = PVDecl->getType();
6106 } else if (PType->isFunctionType())
6107 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006108 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
6109 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006110 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006111 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006112 }
Douglas Gregora9d84932011-05-27 01:19:52 +00006113
John McCall843dfcc2016-11-29 21:57:00 +00006114 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006115}
6116
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006117ObjCPropertyImplDecl *
6118ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6119 const ObjCPropertyDecl *PD,
6120 const Decl *Container) const {
6121 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006122 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006123 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006124 for (auto *PID : CID->property_impls())
6125 if (PID->getPropertyDecl() == PD)
6126 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006127 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006128 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006129 for (auto *PID : OID->property_impls())
6130 if (PID->getPropertyDecl() == PD)
6131 return PID;
6132 }
6133 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006134}
6135
Daniel Dunbar4932b362008-08-28 04:38:10 +00006136/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006137/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006138/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6139/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006140/// Property attributes are stored as a comma-delimited C string. The simple
6141/// attributes readonly and bycopy are encoded as single characters. The
6142/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6143/// encoded as single characters, followed by an identifier. Property types
6144/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006145/// these attributes are defined by the following enumeration:
6146/// @code
6147/// enum PropertyAttributes {
6148/// kPropertyReadOnly = 'R', // property is read-only.
6149/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6150/// kPropertyByref = '&', // property is a reference to the value last assigned
6151/// kPropertyDynamic = 'D', // property is dynamic
6152/// kPropertyGetter = 'G', // followed by getter selector name
6153/// kPropertySetter = 'S', // followed by setter selector name
6154/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006155/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006156/// kPropertyWeak = 'W' // 'weak' property
6157/// kPropertyStrong = 'P' // property GC'able
6158/// kPropertyNonAtomic = 'N' // property non-atomic
6159/// };
6160/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006161std::string
6162ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6163 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006164 // Collect information from the property implementation decl(s).
6165 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006166 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006167
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006168 if (ObjCPropertyImplDecl *PropertyImpDecl =
6169 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6170 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6171 Dynamic = true;
6172 else
6173 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006174 }
6175
6176 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006177 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006178
6179 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006180 // GCC has some special rules regarding encoding of properties which
6181 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006182 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006183
6184 if (PD->isReadOnly()) {
6185 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006186 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6187 S += ",C";
6188 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6189 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006190 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6191 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006192 } else {
6193 switch (PD->getSetterKind()) {
6194 case ObjCPropertyDecl::Assign: break;
6195 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006196 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006197 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006198 }
6199 }
6200
6201 // It really isn't clear at all what this means, since properties
6202 // are "dynamic by default".
6203 if (Dynamic)
6204 S += ",D";
6205
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006206 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6207 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006208
Daniel Dunbar4932b362008-08-28 04:38:10 +00006209 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6210 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006211 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006212 }
6213
6214 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6215 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006216 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006217 }
6218
6219 if (SynthesizePID) {
6220 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6221 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006222 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006223 }
6224
6225 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006226 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006227}
6228
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006229/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006230/// Another legacy compatibility encoding: 32-bit longs are encoded as
6231/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006232/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006233void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006234 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006235 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006236 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006237 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006238 else
Jay Foad39c79802011-01-12 09:06:06 +00006239 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006240 PointeeTy = IntTy;
6241 }
6242 }
6243}
6244
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006245void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006246 const FieldDecl *Field,
6247 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006248 // We follow the behavior of gcc, expanding structures which are
6249 // directly pointed to, and expanding embedded structures. Note that
6250 // these rules are sufficient to prevent recursive encoding of the
6251 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00006252 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006253 true /* outermost type */, false, false,
6254 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006255}
6256
Joe Groff98ac7d22014-07-07 22:25:15 +00006257void ASTContext::getObjCEncodingForPropertyType(QualType T,
6258 std::string& S) const {
6259 // Encode result type.
6260 // GCC has some special rules regarding encoding of properties which
6261 // closely resembles encoding of ivars.
6262 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
6263 true /* outermost type */,
6264 true /* encoding property */);
6265}
6266
John McCall393a78d2012-12-20 02:45:14 +00006267static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6268 BuiltinType::Kind kind) {
6269 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006270 case BuiltinType::Void: return 'v';
6271 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006272 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006273 case BuiltinType::Char_U:
6274 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006275 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006276 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006277 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006278 case BuiltinType::UInt: return 'I';
6279 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006280 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006281 case BuiltinType::UInt128: return 'T';
6282 case BuiltinType::ULongLong: return 'Q';
6283 case BuiltinType::Char_S:
6284 case BuiltinType::SChar: return 'c';
6285 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006286 case BuiltinType::WChar_S:
6287 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006288 case BuiltinType::Int: return 'i';
6289 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006290 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006291 case BuiltinType::LongLong: return 'q';
6292 case BuiltinType::Int128: return 't';
6293 case BuiltinType::Float: return 'f';
6294 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006295 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006296 case BuiltinType::NullPtr: return '*'; // like char*
6297
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006298 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006299 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006300 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006301 case BuiltinType::ShortAccum:
6302 case BuiltinType::Accum:
6303 case BuiltinType::LongAccum:
6304 case BuiltinType::UShortAccum:
6305 case BuiltinType::UAccum:
6306 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006307 case BuiltinType::ShortFract:
6308 case BuiltinType::Fract:
6309 case BuiltinType::LongFract:
6310 case BuiltinType::UShortFract:
6311 case BuiltinType::UFract:
6312 case BuiltinType::ULongFract:
6313 case BuiltinType::SatShortAccum:
6314 case BuiltinType::SatAccum:
6315 case BuiltinType::SatLongAccum:
6316 case BuiltinType::SatUShortAccum:
6317 case BuiltinType::SatUAccum:
6318 case BuiltinType::SatULongAccum:
6319 case BuiltinType::SatShortFract:
6320 case BuiltinType::SatFract:
6321 case BuiltinType::SatLongFract:
6322 case BuiltinType::SatUShortFract:
6323 case BuiltinType::SatUFract:
6324 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006325 // FIXME: potentially need @encodes for these!
6326 return ' ';
6327
6328 case BuiltinType::ObjCId:
6329 case BuiltinType::ObjCClass:
6330 case BuiltinType::ObjCSel:
6331 llvm_unreachable("@encoding ObjC primitive type");
6332
6333 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006334#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6335 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006336#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006337 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006338 case BuiltinType::OCLClkEvent:
6339 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006340 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006341 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006342 case BuiltinType::Dependent:
6343#define BUILTIN_TYPE(KIND, ID)
6344#define PLACEHOLDER_TYPE(KIND, ID) \
6345 case BuiltinType::KIND:
6346#include "clang/AST/BuiltinTypes.def"
6347 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006348 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006349 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006350}
6351
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006352static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6353 EnumDecl *Enum = ET->getDecl();
6354
6355 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6356 if (!Enum->isFixed())
6357 return 'i';
6358
6359 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006360 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006361 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006362}
6363
Jay Foad39c79802011-01-12 09:06:06 +00006364static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006365 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006366 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006367 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006368 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6369 // The GNU runtime requires more information; bitfields are encoded as b,
6370 // then the offset (in bits) of the first element, then the type of the
6371 // bitfield, then the size in bits. For example, in this structure:
6372 //
6373 // struct
6374 // {
6375 // int integer;
6376 // int flags:2;
6377 // };
6378 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6379 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6380 // information is not especially sensible, but we're stuck with it for
6381 // compatibility with GCC, although providing it breaks anything that
6382 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006383 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006384 uint64_t Offset;
6385
6386 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6387 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6388 IVD);
6389 } else {
6390 const RecordDecl *RD = FD->getParent();
6391 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6392 Offset = RL.getFieldOffset(FD->getFieldIndex());
6393 }
6394
6395 S += llvm::utostr(Offset);
6396
Eugene Zelenko7855e772018-04-03 00:11:50 +00006397 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006398 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006399 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006400 const auto *BT = T->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006401 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6402 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006403 }
Richard Smithcaf33902011-10-10 18:28:20 +00006404 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006405}
6406
Daniel Dunbar07d07852009-10-18 21:17:35 +00006407// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006408void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6409 bool ExpandPointedToStructures,
6410 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006411 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006412 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006413 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006414 bool StructField,
6415 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006416 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006417 bool EncodePointerToObjCTypedef,
6418 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006419 CanQualType CT = getCanonicalType(T);
6420 switch (CT->getTypeClass()) {
6421 case Type::Builtin:
6422 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006423 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006424 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006425 if (const auto *BT = dyn_cast<BuiltinType>(CT))
John McCall393a78d2012-12-20 02:45:14 +00006426 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6427 else
6428 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006429 return;
Mike Stump11289f42009-09-09 15:08:12 +00006430
John McCall393a78d2012-12-20 02:45:14 +00006431 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006432 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006433 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006434 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006435 return;
6436 }
John McCall393a78d2012-12-20 02:45:14 +00006437
6438 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006439 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006440 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006441 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006442 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006443 }
John McCall393a78d2012-12-20 02:45:14 +00006444
6445 // encoding for pointer or reference types.
6446 case Type::Pointer:
6447 case Type::LValueReference:
6448 case Type::RValueReference: {
6449 QualType PointeeTy;
6450 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006451 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006452 if (PT->isObjCSelType()) {
6453 S += ':';
6454 return;
6455 }
6456 PointeeTy = PT->getPointeeType();
6457 } else {
6458 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6459 }
6460
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006461 bool isReadOnly = false;
6462 // For historical/compatibility reasons, the read-only qualifier of the
6463 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6464 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006465 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006466 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006467 if (OutermostType && T.isConstQualified()) {
6468 isReadOnly = true;
6469 S += 'r';
6470 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006471 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006472 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006473 while (P->getAs<PointerType>())
6474 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006475 if (P.isConstQualified()) {
6476 isReadOnly = true;
6477 S += 'r';
6478 }
6479 }
6480 if (isReadOnly) {
6481 // Another legacy compatibility encoding. Some ObjC qualifier and type
6482 // combinations need to be rearranged.
6483 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006484 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006485 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006486 }
Mike Stump11289f42009-09-09 15:08:12 +00006487
Anders Carlssond8499822007-10-29 05:01:08 +00006488 if (PointeeTy->isCharType()) {
6489 // char pointer types should be encoded as '*' unless it is a
6490 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006491 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006492 S += '*';
6493 return;
6494 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006495 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006496 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6497 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6498 S += '#';
6499 return;
6500 }
6501 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6502 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6503 S += '@';
6504 return;
6505 }
6506 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006507 }
Anders Carlssond8499822007-10-29 05:01:08 +00006508 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006509 getLegacyIntegralTypeEncoding(PointeeTy);
6510
Mike Stump11289f42009-09-09 15:08:12 +00006511 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006512 nullptr, false, false, false, false, false, false,
6513 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006514 return;
6515 }
John McCall393a78d2012-12-20 02:45:14 +00006516
6517 case Type::ConstantArray:
6518 case Type::IncompleteArray:
6519 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006520 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006521
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006522 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006523 // Incomplete arrays are encoded as a pointer to the array element.
6524 S += '^';
6525
Mike Stump11289f42009-09-09 15:08:12 +00006526 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006527 false, ExpandStructures, FD);
6528 } else {
6529 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006530
Eugene Zelenko7855e772018-04-03 00:11:50 +00006531 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006532 S += llvm::utostr(CAT->getSize().getZExtValue());
6533 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006534 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006535 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6536 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006537 S += '0';
6538 }
Mike Stump11289f42009-09-09 15:08:12 +00006539
6540 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006541 false, ExpandStructures, FD,
6542 false, false, false, false, false, false,
6543 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006544 S += ']';
6545 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006546 return;
6547 }
Mike Stump11289f42009-09-09 15:08:12 +00006548
John McCall393a78d2012-12-20 02:45:14 +00006549 case Type::FunctionNoProto:
6550 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006551 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006552 return;
Mike Stump11289f42009-09-09 15:08:12 +00006553
John McCall393a78d2012-12-20 02:45:14 +00006554 case Type::Record: {
6555 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006556 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006557 // Anonymous structures print as '?'
6558 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6559 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006560 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006561 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006562 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006563 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6564 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006565 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006566 } else {
6567 S += '?';
6568 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006569 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006570 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006571 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006572 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006573 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006574 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006575 if (FD) {
6576 S += '"';
6577 S += Field->getNameAsString();
6578 S += '"';
6579 }
Mike Stump11289f42009-09-09 15:08:12 +00006580
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006581 // Special case bit-fields.
6582 if (Field->isBitField()) {
6583 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006584 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006585 } else {
6586 QualType qt = Field->getType();
6587 getLegacyIntegralTypeEncoding(qt);
6588 getObjCEncodingForTypeImpl(qt, S, false, true,
6589 FD, /*OutermostType*/false,
6590 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006591 /*StructField*/true,
6592 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006593 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006594 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006595 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006596 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006597 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006598 return;
6599 }
Mike Stump11289f42009-09-09 15:08:12 +00006600
John McCall393a78d2012-12-20 02:45:14 +00006601 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006602 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006603 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006604 if (EncodeBlockParameters) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006605 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006606
6607 S += '<';
6608 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006609 getObjCEncodingForTypeImpl(
6610 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6611 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006612 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6613 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006614 // Block self
6615 S += "@?";
6616 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00006617 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006618 for (const auto &I : FPT->param_types())
6619 getObjCEncodingForTypeImpl(
6620 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6621 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006622 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6623 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006624 }
6625 S += '>';
6626 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006627 return;
6628 }
Mike Stump11289f42009-09-09 15:08:12 +00006629
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006630 case Type::ObjCObject: {
6631 // hack to match legacy encoding of *id and *Class
6632 QualType Ty = getObjCObjectPointerType(CT);
6633 if (Ty->isObjCIdType()) {
6634 S += "{objc_object=}";
6635 return;
6636 }
6637 else if (Ty->isObjCClassType()) {
6638 S += "{objc_class=}";
6639 return;
6640 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006641 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006642 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006643 }
6644
John McCall393a78d2012-12-20 02:45:14 +00006645 case Type::ObjCInterface: {
6646 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006647 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006648 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006649 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006650 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006651 if (ExpandStructures) {
6652 S += '=';
6653 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6654 DeepCollectObjCIvars(OI, true, Ivars);
6655 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006656 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006657 if (Field->isBitField())
6658 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6659 else
6660 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6661 false, false, false, false, false,
6662 EncodePointerToObjCTypedef,
6663 NotEncodedT);
6664 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006665 }
6666 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006667 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006668 }
Mike Stump11289f42009-09-09 15:08:12 +00006669
John McCall393a78d2012-12-20 02:45:14 +00006670 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006671 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006672 if (OPT->isObjCIdType()) {
6673 S += '@';
6674 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006675 }
Mike Stump11289f42009-09-09 15:08:12 +00006676
Steve Narofff0c86112009-10-28 22:03:49 +00006677 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6678 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6679 // Since this is a binary compatibility issue, need to consult with runtime
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006680 // folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006681 S += '#';
6682 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006683 }
Mike Stump11289f42009-09-09 15:08:12 +00006684
Chris Lattnere7cabb92009-07-13 00:10:46 +00006685 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006686 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006687 ExpandPointedToStructures,
6688 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006689 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006690 // Note that we do extended encoding of protocol qualifer list
6691 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006692 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006693 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006694 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006695 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006696 S += '>';
6697 }
6698 S += '"';
6699 }
6700 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006701 }
Mike Stump11289f42009-09-09 15:08:12 +00006702
Chris Lattnere7cabb92009-07-13 00:10:46 +00006703 QualType PointeeTy = OPT->getPointeeType();
6704 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006705 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6706 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006707 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006708 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006709 // {...};
6710 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006711 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006712 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006713 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6714 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6715 DeepCollectObjCIvars(OI, true, Ivars);
6716 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006717 if (Ivars[i] == FD) {
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006718 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006719 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006720 S += '}';
6721 return;
6722 }
6723 }
6724 }
Mike Stump11289f42009-09-09 15:08:12 +00006725 getObjCEncodingForTypeImpl(PointeeTy, S,
6726 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006727 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006728 false, false, false, false, false,
6729 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006730 return;
6731 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006732
6733 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006734 if (OPT->getInterfaceDecl() &&
6735 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006736 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006737 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006738 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006739 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006740 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006741 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006742 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006743 S += '"';
6744 }
6745 return;
6746 }
Mike Stump11289f42009-09-09 15:08:12 +00006747
John McCalla9e6e8d2010-05-17 23:56:34 +00006748 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006749 // FIXME: we shoul do better than that. 'M' is available.
6750 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006751 // This matches gcc's encoding, even though technically it is insufficient.
6752 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006753 case Type::Vector:
6754 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006755 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006756 if (NotEncodedT)
6757 *NotEncodedT = T;
6758 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006759
6760 // We could see an undeduced auto type here during error recovery.
6761 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006762 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006763 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006764 return;
6765
Xiuli Pan9c14e282016-01-09 12:53:17 +00006766 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006767#define ABSTRACT_TYPE(KIND, BASE)
6768#define TYPE(KIND, BASE)
6769#define DEPENDENT_TYPE(KIND, BASE) \
6770 case Type::KIND:
6771#define NON_CANONICAL_TYPE(KIND, BASE) \
6772 case Type::KIND:
6773#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6774 case Type::KIND:
6775#include "clang/AST/TypeNodes.def"
6776 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006777 }
John McCall393a78d2012-12-20 02:45:14 +00006778 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006779}
6780
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006781void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6782 std::string &S,
6783 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006784 bool includeVBases,
6785 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006786 assert(RDecl && "Expected non-null RecordDecl");
6787 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006788 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006789 return;
6790
Eugene Zelenko7855e772018-04-03 00:11:50 +00006791 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006792 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6793 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6794
6795 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006796 for (const auto &BI : CXXRec->bases()) {
6797 if (!BI.isVirtual()) {
6798 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006799 if (base->isEmpty())
6800 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006801 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006802 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6803 std::make_pair(offs, base));
6804 }
6805 }
6806 }
6807
6808 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006809 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006810 uint64_t offs = layout.getFieldOffset(i);
6811 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006812 std::make_pair(offs, Field));
6813 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006814 }
6815
6816 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006817 for (const auto &BI : CXXRec->vbases()) {
6818 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006819 if (base->isEmpty())
6820 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006821 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006822 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6823 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006824 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6825 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006826 }
6827 }
6828
6829 CharUnits size;
6830 if (CXXRec) {
6831 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6832 } else {
6833 size = layout.getSize();
6834 }
6835
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006836#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006837 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006838#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006839 std::multimap<uint64_t, NamedDecl *>::iterator
6840 CurLayObj = FieldOrBaseOffsets.begin();
6841
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006842 if (CXXRec && CXXRec->isDynamicClass() &&
6843 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006844 if (FD) {
6845 S += "\"_vptr$";
6846 std::string recname = CXXRec->getNameAsString();
6847 if (recname.empty()) recname = "?";
6848 S += recname;
6849 S += '"';
6850 }
6851 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006852#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006853 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006854#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006855 }
6856
6857 if (!RDecl->hasFlexibleArrayMember()) {
6858 // Mark the end of the structure.
6859 uint64_t offs = toBits(size);
6860 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006861 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006862 }
6863
6864 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006865#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006866 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006867 if (CurOffs < CurLayObj->first) {
6868 uint64_t padding = CurLayObj->first - CurOffs;
6869 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6870 // packing/alignment of members is different that normal, in which case
6871 // the encoding will be out-of-sync with the real layout.
6872 // If the runtime switches to just consider the size of types without
6873 // taking into account alignment, we could make padding explicit in the
6874 // encoding (e.g. using arrays of chars). The encoding strings would be
6875 // longer then though.
6876 CurOffs += padding;
6877 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006878#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006879
6880 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006881 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006882 break; // reached end of structure.
6883
Eugene Zelenko7855e772018-04-03 00:11:50 +00006884 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006885 // We expand the bases without their virtual bases since those are going
6886 // in the initial structure. Note that this differs from gcc which
6887 // expands virtual bases each time one is encountered in the hierarchy,
6888 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006889 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6890 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006891 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006892#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006893 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006894#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006895 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006896 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006897 if (FD) {
6898 S += '"';
6899 S += field->getNameAsString();
6900 S += '"';
6901 }
6902
6903 if (field->isBitField()) {
6904 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006905#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006906 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006907#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006908 } else {
6909 QualType qt = field->getType();
6910 getLegacyIntegralTypeEncoding(qt);
6911 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6912 /*OutermostType*/false,
6913 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006914 /*StructField*/true,
6915 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006916#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006917 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006918#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006919 }
6920 }
6921 }
6922}
6923
Mike Stump11289f42009-09-09 15:08:12 +00006924void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006925 std::string& S) const {
6926 if (QT & Decl::OBJC_TQ_In)
6927 S += 'n';
6928 if (QT & Decl::OBJC_TQ_Inout)
6929 S += 'N';
6930 if (QT & Decl::OBJC_TQ_Out)
6931 S += 'o';
6932 if (QT & Decl::OBJC_TQ_Bycopy)
6933 S += 'O';
6934 if (QT & Decl::OBJC_TQ_Byref)
6935 S += 'R';
6936 if (QT & Decl::OBJC_TQ_Oneway)
6937 S += 'V';
6938}
6939
Douglas Gregor3ea72692011-08-12 05:46:01 +00006940TypedefDecl *ASTContext::getObjCIdDecl() const {
6941 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006942 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00006943 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006944 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006945 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006946 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006947}
6948
Douglas Gregor52e02802011-08-12 06:17:30 +00006949TypedefDecl *ASTContext::getObjCSelDecl() const {
6950 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006951 QualType T = getPointerType(ObjCBuiltinSelTy);
6952 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006953 }
6954 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006955}
6956
Douglas Gregor0a586182011-08-12 05:59:41 +00006957TypedefDecl *ASTContext::getObjCClassDecl() const {
6958 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006959 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00006960 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006961 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006962 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006963 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006964}
6965
Douglas Gregord53ae832012-01-17 18:09:05 +00006966ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6967 if (!ObjCProtocolClassDecl) {
6968 ObjCProtocolClassDecl
6969 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6970 SourceLocation(),
6971 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006972 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006973 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006974 SourceLocation(), true);
6975 }
6976
6977 return ObjCProtocolClassDecl;
6978}
6979
Meador Inge5d3fb222012-06-16 03:34:49 +00006980//===----------------------------------------------------------------------===//
6981// __builtin_va_list Construction Functions
6982//===----------------------------------------------------------------------===//
6983
Charles Davisc7d5c942015-09-17 20:55:33 +00006984static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6985 StringRef Name) {
6986 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006987 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006988 return Context->buildImplicitTypedef(T, Name);
6989}
6990
6991static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6992 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6993}
6994
6995static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6996 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006997}
6998
6999static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7000 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007001 QualType T = Context->getPointerType(Context->VoidTy);
7002 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007003}
7004
Tim Northover9bb857a2013-01-31 12:13:10 +00007005static TypedefDecl *
7006CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007007 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007008 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007009 if (Context->getLangOpts().CPlusPlus) {
7010 // namespace std { struct __va_list {
7011 NamespaceDecl *NS;
7012 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7013 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007014 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007015 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007016 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007017 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007018 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007019 }
7020
7021 VaListTagDecl->startDefinition();
7022
7023 const size_t NumFields = 5;
7024 QualType FieldTypes[NumFields];
7025 const char *FieldNames[NumFields];
7026
7027 // void *__stack;
7028 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7029 FieldNames[0] = "__stack";
7030
7031 // void *__gr_top;
7032 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7033 FieldNames[1] = "__gr_top";
7034
7035 // void *__vr_top;
7036 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7037 FieldNames[2] = "__vr_top";
7038
7039 // int __gr_offs;
7040 FieldTypes[3] = Context->IntTy;
7041 FieldNames[3] = "__gr_offs";
7042
7043 // int __vr_offs;
7044 FieldTypes[4] = Context->IntTy;
7045 FieldNames[4] = "__vr_offs";
7046
7047 // Create fields
7048 for (unsigned i = 0; i < NumFields; ++i) {
7049 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7050 VaListTagDecl,
7051 SourceLocation(),
7052 SourceLocation(),
7053 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007054 FieldTypes[i], /*TInfo=*/nullptr,
7055 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007056 /*Mutable=*/false,
7057 ICIS_NoInit);
7058 Field->setAccess(AS_public);
7059 VaListTagDecl->addDecl(Field);
7060 }
7061 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007062 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007063 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007064
7065 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007066 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007067}
7068
Meador Inge5d3fb222012-06-16 03:34:49 +00007069static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7070 // typedef struct __va_list_tag {
7071 RecordDecl *VaListTagDecl;
7072
Alp Toker2dea15b2013-12-17 01:22:38 +00007073 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007074 VaListTagDecl->startDefinition();
7075
7076 const size_t NumFields = 5;
7077 QualType FieldTypes[NumFields];
7078 const char *FieldNames[NumFields];
7079
7080 // unsigned char gpr;
7081 FieldTypes[0] = Context->UnsignedCharTy;
7082 FieldNames[0] = "gpr";
7083
7084 // unsigned char fpr;
7085 FieldTypes[1] = Context->UnsignedCharTy;
7086 FieldNames[1] = "fpr";
7087
7088 // unsigned short reserved;
7089 FieldTypes[2] = Context->UnsignedShortTy;
7090 FieldNames[2] = "reserved";
7091
7092 // void* overflow_arg_area;
7093 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7094 FieldNames[3] = "overflow_arg_area";
7095
7096 // void* reg_save_area;
7097 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7098 FieldNames[4] = "reg_save_area";
7099
7100 // Create fields
7101 for (unsigned i = 0; i < NumFields; ++i) {
7102 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7103 SourceLocation(),
7104 SourceLocation(),
7105 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007106 FieldTypes[i], /*TInfo=*/nullptr,
7107 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007108 /*Mutable=*/false,
7109 ICIS_NoInit);
7110 Field->setAccess(AS_public);
7111 VaListTagDecl->addDecl(Field);
7112 }
7113 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007114 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007115 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7116
7117 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007118 TypedefDecl *VaListTagTypedefDecl =
7119 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7120
Meador Inge5d3fb222012-06-16 03:34:49 +00007121 QualType VaListTagTypedefType =
7122 Context->getTypedefType(VaListTagTypedefDecl);
7123
7124 // typedef __va_list_tag __builtin_va_list[1];
7125 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7126 QualType VaListTagArrayType
7127 = Context->getConstantArrayType(VaListTagTypedefType,
7128 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007129 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007130}
7131
7132static TypedefDecl *
7133CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007134 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007135 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007136 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007137 VaListTagDecl->startDefinition();
7138
7139 const size_t NumFields = 4;
7140 QualType FieldTypes[NumFields];
7141 const char *FieldNames[NumFields];
7142
7143 // unsigned gp_offset;
7144 FieldTypes[0] = Context->UnsignedIntTy;
7145 FieldNames[0] = "gp_offset";
7146
7147 // unsigned fp_offset;
7148 FieldTypes[1] = Context->UnsignedIntTy;
7149 FieldNames[1] = "fp_offset";
7150
7151 // void* overflow_arg_area;
7152 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7153 FieldNames[2] = "overflow_arg_area";
7154
7155 // void* reg_save_area;
7156 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7157 FieldNames[3] = "reg_save_area";
7158
7159 // Create fields
7160 for (unsigned i = 0; i < NumFields; ++i) {
7161 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7162 VaListTagDecl,
7163 SourceLocation(),
7164 SourceLocation(),
7165 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007166 FieldTypes[i], /*TInfo=*/nullptr,
7167 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007168 /*Mutable=*/false,
7169 ICIS_NoInit);
7170 Field->setAccess(AS_public);
7171 VaListTagDecl->addDecl(Field);
7172 }
7173 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007174 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007175 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7176
Richard Smith9b88a4c2015-07-27 05:40:23 +00007177 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007178
Richard Smith9b88a4c2015-07-27 05:40:23 +00007179 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007180 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007181 QualType VaListTagArrayType =
7182 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007183 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007184}
7185
7186static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7187 // typedef int __builtin_va_list[4];
7188 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007189 QualType IntArrayType =
7190 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007191 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007192}
7193
Logan Chien57086ce2012-10-10 06:56:20 +00007194static TypedefDecl *
7195CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007196 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007197 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007198 if (Context->getLangOpts().CPlusPlus) {
7199 // namespace std { struct __va_list {
7200 NamespaceDecl *NS;
7201 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7202 Context->getTranslationUnitDecl(),
7203 /*Inline*/false, SourceLocation(),
7204 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007205 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007206 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007207 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007208 }
7209
7210 VaListDecl->startDefinition();
7211
7212 // void * __ap;
7213 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7214 VaListDecl,
7215 SourceLocation(),
7216 SourceLocation(),
7217 &Context->Idents.get("__ap"),
7218 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007219 /*TInfo=*/nullptr,
7220 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007221 /*Mutable=*/false,
7222 ICIS_NoInit);
7223 Field->setAccess(AS_public);
7224 VaListDecl->addDecl(Field);
7225
7226 // };
7227 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007228 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007229
7230 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007231 QualType T = Context->getRecordType(VaListDecl);
7232 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007233}
7234
Ulrich Weigand47445072013-05-06 16:26:41 +00007235static TypedefDecl *
7236CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007237 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007238 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007239 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007240 VaListTagDecl->startDefinition();
7241
7242 const size_t NumFields = 4;
7243 QualType FieldTypes[NumFields];
7244 const char *FieldNames[NumFields];
7245
7246 // long __gpr;
7247 FieldTypes[0] = Context->LongTy;
7248 FieldNames[0] = "__gpr";
7249
7250 // long __fpr;
7251 FieldTypes[1] = Context->LongTy;
7252 FieldNames[1] = "__fpr";
7253
7254 // void *__overflow_arg_area;
7255 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7256 FieldNames[2] = "__overflow_arg_area";
7257
7258 // void *__reg_save_area;
7259 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7260 FieldNames[3] = "__reg_save_area";
7261
7262 // Create fields
7263 for (unsigned i = 0; i < NumFields; ++i) {
7264 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7265 VaListTagDecl,
7266 SourceLocation(),
7267 SourceLocation(),
7268 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007269 FieldTypes[i], /*TInfo=*/nullptr,
7270 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007271 /*Mutable=*/false,
7272 ICIS_NoInit);
7273 Field->setAccess(AS_public);
7274 VaListTagDecl->addDecl(Field);
7275 }
7276 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007277 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007278 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007279
Richard Smith9b88a4c2015-07-27 05:40:23 +00007280 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007281
7282 // typedef __va_list_tag __builtin_va_list[1];
7283 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007284 QualType VaListTagArrayType =
7285 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007286
Alp Toker56b5cc92013-12-15 10:36:26 +00007287 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007288}
7289
Meador Inge5d3fb222012-06-16 03:34:49 +00007290static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7291 TargetInfo::BuiltinVaListKind Kind) {
7292 switch (Kind) {
7293 case TargetInfo::CharPtrBuiltinVaList:
7294 return CreateCharPtrBuiltinVaListDecl(Context);
7295 case TargetInfo::VoidPtrBuiltinVaList:
7296 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007297 case TargetInfo::AArch64ABIBuiltinVaList:
7298 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007299 case TargetInfo::PowerABIBuiltinVaList:
7300 return CreatePowerABIBuiltinVaListDecl(Context);
7301 case TargetInfo::X86_64ABIBuiltinVaList:
7302 return CreateX86_64ABIBuiltinVaListDecl(Context);
7303 case TargetInfo::PNaClABIBuiltinVaList:
7304 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007305 case TargetInfo::AAPCSABIBuiltinVaList:
7306 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007307 case TargetInfo::SystemZBuiltinVaList:
7308 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007309 }
7310
7311 llvm_unreachable("Unhandled __builtin_va_list type kind");
7312}
7313
7314TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007315 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007316 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007317 assert(BuiltinVaListDecl->isImplicit());
7318 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007319
7320 return BuiltinVaListDecl;
7321}
7322
Richard Smith9b88a4c2015-07-27 05:40:23 +00007323Decl *ASTContext::getVaListTagDecl() const {
7324 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007325 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007326 if (!VaListTagDecl)
7327 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007328
Richard Smith9b88a4c2015-07-27 05:40:23 +00007329 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007330}
7331
Charles Davisc7d5c942015-09-17 20:55:33 +00007332TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7333 if (!BuiltinMSVaListDecl)
7334 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7335
7336 return BuiltinMSVaListDecl;
7337}
7338
Erich Keane41af9712018-04-16 21:30:08 +00007339bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7340 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7341}
7342
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007343void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007344 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007345 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007346
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007347 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007348}
7349
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007350/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007351/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007352TemplateName
7353ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7354 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007355 unsigned size = End - Begin;
7356 assert(size > 1 && "set is not overloaded!");
7357
7358 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7359 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007360 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007361
7362 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007363 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007364 NamedDecl *D = *I;
7365 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007366 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007367 (isa<UsingShadowDecl>(D) &&
7368 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7369 *Storage++ = D;
7370 }
7371
7372 return TemplateName(OT);
7373}
7374
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007375/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007376/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007377TemplateName
7378ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7379 bool TemplateKeyword,
7380 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007381 assert(NNS && "Missing nested-name-specifier in qualified template name");
7382
Douglas Gregorc42075a2010-02-04 18:10:26 +00007383 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007384 llvm::FoldingSetNodeID ID;
7385 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7386
Craig Topper36250ad2014-05-12 05:36:57 +00007387 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007388 QualifiedTemplateName *QTN =
7389 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7390 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007391 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007392 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007393 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7394 }
7395
7396 return TemplateName(QTN);
7397}
7398
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007399/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007400/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007401TemplateName
7402ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7403 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007404 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007405 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007406
7407 llvm::FoldingSetNodeID ID;
7408 DependentTemplateName::Profile(ID, NNS, Name);
7409
Craig Topper36250ad2014-05-12 05:36:57 +00007410 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007411 DependentTemplateName *QTN =
7412 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7413
7414 if (QTN)
7415 return TemplateName(QTN);
7416
7417 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7418 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007419 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007420 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007421 } else {
7422 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007423 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007424 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007425 DependentTemplateName *CheckQTN =
7426 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7427 assert(!CheckQTN && "Dependent type name canonicalization broken");
7428 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007429 }
7430
7431 DependentTemplateNames.InsertNode(QTN, InsertPos);
7432 return TemplateName(QTN);
7433}
7434
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007435/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007436/// template name such as \c MetaFun::template operator+.
7437TemplateName
7438ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007439 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007440 assert((!NNS || NNS->isDependent()) &&
7441 "Nested name specifier must be dependent");
7442
7443 llvm::FoldingSetNodeID ID;
7444 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007445
7446 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007447 DependentTemplateName *QTN
7448 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007449
7450 if (QTN)
7451 return TemplateName(QTN);
7452
7453 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7454 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007455 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007456 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007457 } else {
7458 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007459 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007460 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007461
Douglas Gregorc42075a2010-02-04 18:10:26 +00007462 DependentTemplateName *CheckQTN
7463 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7464 assert(!CheckQTN && "Dependent template name canonicalization broken");
7465 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007466 }
7467
7468 DependentTemplateNames.InsertNode(QTN, InsertPos);
7469 return TemplateName(QTN);
7470}
7471
Douglas Gregor5590be02011-01-15 06:45:20 +00007472TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007473ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7474 TemplateName replacement) const {
7475 llvm::FoldingSetNodeID ID;
7476 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007477
7478 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007479 SubstTemplateTemplateParmStorage *subst
7480 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7481
7482 if (!subst) {
7483 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7484 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7485 }
7486
7487 return TemplateName(subst);
7488}
7489
7490TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007491ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7492 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007493 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007494 llvm::FoldingSetNodeID ID;
7495 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007496
7497 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007498 SubstTemplateTemplateParmPackStorage *Subst
7499 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7500
7501 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00007502 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007503 ArgPack.pack_size(),
7504 ArgPack.pack_begin());
7505 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7506 }
7507
7508 return TemplateName(Subst);
7509}
7510
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007511/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007512/// TargetInfo, produce the corresponding type. The unsigned @p Type
7513/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007514CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007515 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007516 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007517 case TargetInfo::SignedChar: return SignedCharTy;
7518 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007519 case TargetInfo::SignedShort: return ShortTy;
7520 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7521 case TargetInfo::SignedInt: return IntTy;
7522 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7523 case TargetInfo::SignedLong: return LongTy;
7524 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7525 case TargetInfo::SignedLongLong: return LongLongTy;
7526 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7527 }
7528
David Blaikie83d382b2011-09-23 05:06:16 +00007529 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007530}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007531
7532//===----------------------------------------------------------------------===//
7533// Type Predicates.
7534//===----------------------------------------------------------------------===//
7535
Fariborz Jahanian96207692009-02-18 21:49:28 +00007536/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7537/// garbage collection attribute.
7538///
John McCall553d45a2011-01-12 00:34:59 +00007539Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007540 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007541 return Qualifiers::GCNone;
7542
David Blaikiebbafb8a2012-03-11 07:00:24 +00007543 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007544 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7545
7546 // Default behaviour under objective-C's gc is for ObjC pointers
7547 // (or pointers to them) be treated as though they were declared
7548 // as __strong.
7549 if (GCAttrs == Qualifiers::GCNone) {
7550 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7551 return Qualifiers::Strong;
7552 else if (Ty->isPointerType())
7553 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7554 } else {
7555 // It's not valid to set GC attributes on anything that isn't a
7556 // pointer.
7557#ifndef NDEBUG
7558 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007559 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007560 CT = AT->getElementType();
7561 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7562#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007563 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007564 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007565}
7566
Chris Lattner49af6a42008-04-07 06:51:04 +00007567//===----------------------------------------------------------------------===//
7568// Type Compatibility Testing
7569//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007570
Mike Stump11289f42009-09-09 15:08:12 +00007571/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007572/// compatible.
7573static bool areCompatVectorTypes(const VectorType *LHS,
7574 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007575 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007576 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007577 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007578}
7579
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007580bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7581 QualType SecondVec) {
7582 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7583 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7584
7585 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7586 return true;
7587
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007588 // Treat Neon vector types and most AltiVec vector types as if they are the
7589 // equivalent GCC vector types.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007590 const auto *First = FirstVec->getAs<VectorType>();
7591 const auto *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007592 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007593 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007594 First->getVectorKind() != VectorType::AltiVecPixel &&
7595 First->getVectorKind() != VectorType::AltiVecBool &&
7596 Second->getVectorKind() != VectorType::AltiVecPixel &&
7597 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007598 return true;
7599
7600 return false;
7601}
7602
Steve Naroff8e6aee52009-07-23 01:01:38 +00007603//===----------------------------------------------------------------------===//
7604// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7605//===----------------------------------------------------------------------===//
7606
7607/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7608/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007609bool
7610ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7611 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007612 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007613 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007614 for (auto *PI : rProto->protocols())
7615 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007616 return true;
7617 return false;
7618}
7619
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007620/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7621/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007622bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7623 QualType rhs) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007624 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7625 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007626 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007627
Aaron Ballman83731462014-03-17 16:14:00 +00007628 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007629 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007630 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007631 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7632 match = true;
7633 break;
7634 }
7635 }
7636 if (!match)
7637 return false;
7638 }
7639 return true;
7640}
7641
Steve Naroff8e6aee52009-07-23 01:01:38 +00007642/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7643/// ObjCQualifiedIDType.
7644bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7645 bool compare) {
7646 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007647 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007648 lhs->isObjCIdType() || lhs->isObjCClassType())
7649 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007650 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007651 rhs->isObjCIdType() || rhs->isObjCClassType())
7652 return true;
7653
7654 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007655 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007656
Steve Naroff8e6aee52009-07-23 01:01:38 +00007657 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007658
Steve Naroff8e6aee52009-07-23 01:01:38 +00007659 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007660 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007661 // make sure we check the class hierarchy.
7662 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007663 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007664 // when comparing an id<P> on lhs with a static type on rhs,
7665 // see if static class implements all of id's protocols, directly or
7666 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007667 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007668 return false;
7669 }
7670 }
7671 // If there are no qualifiers and no interface, we have an 'id'.
7672 return true;
7673 }
Mike Stump11289f42009-09-09 15:08:12 +00007674 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007675 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007676 bool match = false;
7677
7678 // when comparing an id<P> on lhs with a static type on rhs,
7679 // see if static class implements all of id's protocols, directly or
7680 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007681 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007682 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7683 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7684 match = true;
7685 break;
7686 }
7687 }
Mike Stump11289f42009-09-09 15:08:12 +00007688 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007689 // make sure we check the class hierarchy.
7690 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007691 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007692 // when comparing an id<P> on lhs with a static type on rhs,
7693 // see if static class implements all of id's protocols, directly or
7694 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007695 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007696 match = true;
7697 break;
7698 }
7699 }
7700 }
7701 if (!match)
7702 return false;
7703 }
Mike Stump11289f42009-09-09 15:08:12 +00007704
Steve Naroff8e6aee52009-07-23 01:01:38 +00007705 return true;
7706 }
Mike Stump11289f42009-09-09 15:08:12 +00007707
Steve Naroff8e6aee52009-07-23 01:01:38 +00007708 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7709 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7710
Mike Stump11289f42009-09-09 15:08:12 +00007711 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007712 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007713 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007714 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007715 bool match = false;
7716
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007717 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007718 // see if static class implements all of id's protocols, directly or
7719 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007720 // First, lhs protocols in the qualifier list must be found, direct
7721 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007722 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007723 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7724 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7725 match = true;
7726 break;
7727 }
7728 }
7729 if (!match)
7730 return false;
7731 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007732
7733 // Static class's protocols, or its super class or category protocols
7734 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7735 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7736 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7737 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7738 // This is rather dubious but matches gcc's behavior. If lhs has
7739 // no type qualifier and its class has no static protocol(s)
7740 // assume that it is mismatch.
7741 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7742 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007743 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007744 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007745 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007746 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7747 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7748 match = true;
7749 break;
7750 }
7751 }
7752 if (!match)
7753 return false;
7754 }
7755 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007756 return true;
7757 }
7758 return false;
7759}
7760
Eli Friedman47f77112008-08-22 00:56:42 +00007761/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007762/// compatible for assignment from RHS to LHS. This handles validation of any
7763/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007764bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7765 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007766 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7767 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7768
Steve Naroff1329fa02009-07-15 18:40:39 +00007769 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007770 if (LHS->isObjCUnqualifiedIdOrClass() ||
7771 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007772 return true;
7773
Douglas Gregorab209d82015-07-07 03:58:42 +00007774 // Function object that propagates a successful result or handles
7775 // __kindof types.
7776 auto finish = [&](bool succeeded) -> bool {
7777 if (succeeded)
7778 return true;
7779
7780 if (!RHS->isKindOfType())
7781 return false;
7782
7783 // Strip off __kindof and protocol qualifiers, then check whether
7784 // we can assign the other way.
7785 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7786 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7787 };
7788
7789 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7790 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7791 QualType(RHSOPT,0),
7792 false));
7793 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007794
Douglas Gregorab209d82015-07-07 03:58:42 +00007795 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7796 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7797 QualType(RHSOPT,0)));
7798 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007799
John McCall8b07ec22010-05-15 11:32:37 +00007800 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007801 if (LHS->getInterface() && RHS->getInterface()) {
7802 return finish(canAssignObjCInterfaces(LHS, RHS));
7803 }
Mike Stump11289f42009-09-09 15:08:12 +00007804
Steve Naroff8e6aee52009-07-23 01:01:38 +00007805 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007806}
7807
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007808/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007809/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007810/// arguments in block literals. When passed as arguments, passing 'A*' where
7811/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7812/// not OK. For the return type, the opposite is not OK.
7813bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7814 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007815 const ObjCObjectPointerType *RHSOPT,
7816 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007817
7818 // Function object that propagates a successful result or handles
7819 // __kindof types.
7820 auto finish = [&](bool succeeded) -> bool {
7821 if (succeeded)
7822 return true;
7823
7824 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7825 if (!Expected->isKindOfType())
7826 return false;
7827
7828 // Strip off __kindof and protocol qualifiers, then check whether
7829 // we can assign the other way.
7830 return canAssignObjCInterfacesInBlockPointer(
7831 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7832 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7833 BlockReturnType);
7834 };
7835
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007836 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007837 return true;
7838
7839 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007840 return finish(RHSOPT->isObjCBuiltinType() ||
7841 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007842 }
7843
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007844 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007845 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7846 QualType(RHSOPT,0),
7847 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007848
7849 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7850 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7851 if (LHS && RHS) { // We have 2 user-defined types.
7852 if (LHS != RHS) {
7853 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007854 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007855 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007856 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007857 }
7858 else
7859 return true;
7860 }
7861 return false;
7862}
7863
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007864/// Comparison routine for Objective-C protocols to be used with
7865/// llvm::array_pod_sort.
7866static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7867 ObjCProtocolDecl * const *rhs) {
7868 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007869}
7870
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007871/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007872/// of protocols inherited from two distinct objective-c pointer objects with
7873/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007874/// It is used to build composite qualifier list of the composite type of
7875/// the conditional expression involving two objective-c pointer objects.
7876static
7877void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007878 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007879 const ObjCObjectPointerType *LHSOPT,
7880 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007881 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007882
John McCall8b07ec22010-05-15 11:32:37 +00007883 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7884 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7885 assert(LHS->getInterface() && "LHS must have an interface base");
7886 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007887
7888 // Add all of the protocols for the LHS.
7889 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7890
7891 // Start with the protocol qualifiers.
7892 for (auto proto : LHS->quals()) {
7893 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007894 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007895
7896 // Also add the protocols associated with the LHS interface.
7897 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7898
7899 // Add all of the protocls for the RHS.
7900 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7901
7902 // Start with the protocol qualifiers.
7903 for (auto proto : RHS->quals()) {
7904 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007905 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007906
7907 // Also add the protocols associated with the RHS interface.
7908 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7909
7910 // Compute the intersection of the collected protocol sets.
7911 for (auto proto : LHSProtocolSet) {
7912 if (RHSProtocolSet.count(proto))
7913 IntersectionSet.push_back(proto);
7914 }
7915
7916 // Compute the set of protocols that is implied by either the common type or
7917 // the protocols within the intersection.
7918 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7919 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7920
7921 // Remove any implied protocols from the list of inherited protocols.
7922 if (!ImpliedProtocols.empty()) {
7923 IntersectionSet.erase(
7924 std::remove_if(IntersectionSet.begin(),
7925 IntersectionSet.end(),
7926 [&](ObjCProtocolDecl *proto) -> bool {
7927 return ImpliedProtocols.count(proto) > 0;
7928 }),
7929 IntersectionSet.end());
7930 }
7931
7932 // Sort the remaining protocols by name.
7933 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7934 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007935}
7936
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007937/// Determine whether the first type is a subtype of the second.
7938static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7939 QualType rhs) {
7940 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007941 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7942 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007943 if (lhsOPT && rhsOPT)
7944 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7945
7946 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007947 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
7948 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007949 if (lhsBlock && rhsBlock)
7950 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7951
7952 // If either is an unqualified 'id' and the other is a block, it's
7953 // acceptable.
7954 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7955 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7956 return true;
7957
7958 return false;
7959}
7960
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007961// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007962static bool sameObjCTypeArgs(ASTContext &ctx,
7963 const ObjCInterfaceDecl *iface,
7964 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007965 ArrayRef<QualType> rhsArgs,
7966 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007967 if (lhsArgs.size() != rhsArgs.size())
7968 return false;
7969
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007970 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007971 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007972 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7973 continue;
7974
7975 switch (typeParams->begin()[i]->getVariance()) {
7976 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007977 if (!stripKindOf ||
7978 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7979 rhsArgs[i].stripObjCKindOfType(ctx))) {
7980 return false;
7981 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007982 break;
7983
7984 case ObjCTypeParamVariance::Covariant:
7985 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7986 return false;
7987 break;
7988
7989 case ObjCTypeParamVariance::Contravariant:
7990 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7991 return false;
7992 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007993 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007994 }
7995
7996 return true;
7997}
7998
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007999QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008000 const ObjCObjectPointerType *Lptr,
8001 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008002 const ObjCObjectType *LHS = Lptr->getObjectType();
8003 const ObjCObjectType *RHS = Rptr->getObjectType();
8004 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8005 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008006
8007 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008008 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008009
Manman Renc46f7d12016-05-06 19:35:02 +00008010 // When either LHS or RHS is a kindof type, we should return a kindof type.
8011 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8012 // kindof(A).
8013 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8014
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008015 // Follow the left-hand side up the class hierarchy until we either hit a
8016 // root or find the RHS. Record the ancestors in case we don't find it.
8017 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8018 LHSAncestors;
8019 while (true) {
8020 // Record this ancestor. We'll need this if the common type isn't in the
8021 // path from the LHS to the root.
8022 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008023
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008024 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8025 // Get the type arguments.
8026 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8027 bool anyChanges = false;
8028 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8029 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008030 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8031 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008032 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008033 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008034 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8035 // If only one has type arguments, the result will not have type
8036 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008037 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008038 anyChanges = true;
8039 }
8040
8041 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008042 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008043 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8044 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008045 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008046 anyChanges = true;
8047
8048 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008049 // If we need to return a kindof type but LHS is not a kindof type, we
8050 // build a new result type.
8051 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008052 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008053 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008054 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008055 return getObjCObjectPointerType(Result);
8056 }
8057
8058 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008059 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008060
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008061 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008062 QualType LHSSuperType = LHS->getSuperClassType();
8063 if (LHSSuperType.isNull())
8064 break;
8065
8066 LHS = LHSSuperType->castAs<ObjCObjectType>();
8067 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008068
8069 // We didn't find anything by following the LHS to its root; now check
8070 // the RHS against the cached set of ancestors.
8071 while (true) {
8072 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8073 if (KnownLHS != LHSAncestors.end()) {
8074 LHS = KnownLHS->second;
8075
8076 // Get the type arguments.
8077 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8078 bool anyChanges = false;
8079 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8080 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008081 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8082 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008083 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008084 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008085 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8086 // If only one has type arguments, the result will not have type
8087 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008088 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008089 anyChanges = true;
8090 }
8091
8092 // Compute the intersection of protocols.
8093 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8094 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8095 Protocols);
8096 if (!Protocols.empty())
8097 anyChanges = true;
8098
Manman Renc46f7d12016-05-06 19:35:02 +00008099 // If we need to return a kindof type but RHS is not a kindof type, we
8100 // build a new result type.
8101 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008102 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008103 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008104 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008105 return getObjCObjectPointerType(Result);
8106 }
8107
8108 return getObjCObjectPointerType(QualType(RHS, 0));
8109 }
8110
8111 // Find the superclass of the RHS.
8112 QualType RHSSuperType = RHS->getSuperClassType();
8113 if (RHSSuperType.isNull())
8114 break;
8115
8116 RHS = RHSSuperType->castAs<ObjCObjectType>();
8117 }
8118
Eugene Zelenko7855e772018-04-03 00:11:50 +00008119 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008120}
8121
John McCall8b07ec22010-05-15 11:32:37 +00008122bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8123 const ObjCObjectType *RHS) {
8124 assert(LHS->getInterface() && "LHS is not an interface type");
8125 assert(RHS->getInterface() && "RHS is not an interface type");
8126
Chris Lattner49af6a42008-04-07 06:51:04 +00008127 // Verify that the base decls are compatible: the RHS must be a subclass of
8128 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008129 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8130 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8131 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008132 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008133
Douglas Gregore83b9562015-07-07 03:57:53 +00008134 // If the LHS has protocol qualifiers, determine whether all of them are
8135 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8136 // LHS).
8137 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008138 // OK if conversion of LHS to SuperClass results in narrowing of types
8139 // ; i.e., SuperClass may implement at least one of the protocols
8140 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8141 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8142 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8143 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8144 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8145 // qualifiers.
8146 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008147 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008148 // If there is no protocols associated with RHS, it is not a match.
8149 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008150 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008151
8152 for (const auto *LHSProto : LHS->quals()) {
8153 bool SuperImplementsProtocol = false;
8154 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8155 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8156 SuperImplementsProtocol = true;
8157 break;
8158 }
8159 if (!SuperImplementsProtocol)
8160 return false;
8161 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008162 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008163
8164 // If the LHS is specialized, we may need to check type arguments.
8165 if (LHS->isSpecialized()) {
8166 // Follow the superclass chain until we've matched the LHS class in the
8167 // hierarchy. This substitutes type arguments through.
8168 const ObjCObjectType *RHSSuper = RHS;
8169 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8170 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8171
8172 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008173 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008174 !sameObjCTypeArgs(*this, LHS->getInterface(),
8175 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008176 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008177 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008178 }
8179 }
8180
8181 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008182}
8183
Steve Naroffb7605152009-02-12 17:52:19 +00008184bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8185 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008186 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8187 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008188
Steve Naroff7cae42b2009-07-10 23:34:53 +00008189 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008190 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008191
8192 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8193 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008194}
8195
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008196bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8197 return canAssignObjCInterfaces(
8198 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8199 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8200}
8201
Mike Stump11289f42009-09-09 15:08:12 +00008202/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008203/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008204/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008205/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008206bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8207 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008208 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008209 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008210
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008211 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008212}
8213
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008214bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008215 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008216}
8217
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008218bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8219 return !mergeTypes(LHS, RHS, true).isNull();
8220}
8221
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008222/// mergeTransparentUnionType - if T is a transparent union type and a member
8223/// of T is compatible with SubType, return the merged type, else return
8224/// QualType()
8225QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8226 bool OfBlockPointer,
8227 bool Unqualified) {
8228 if (const RecordType *UT = T->getAsUnionType()) {
8229 RecordDecl *UD = UT->getDecl();
8230 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008231 for (const auto *I : UD->fields()) {
8232 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008233 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8234 if (!MT.isNull())
8235 return MT;
8236 }
8237 }
8238 }
8239
Eugene Zelenko7855e772018-04-03 00:11:50 +00008240 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008241}
8242
Alp Toker9cacbab2014-01-20 20:26:09 +00008243/// mergeFunctionParameterTypes - merge two types which appear as function
8244/// parameter types
8245QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8246 bool OfBlockPointer,
8247 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008248 // GNU extension: two types are compatible if they appear as a function
8249 // argument, one of the types is a transparent union type and the other
8250 // type is compatible with a union member
8251 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8252 Unqualified);
8253 if (!lmerge.isNull())
8254 return lmerge;
8255
8256 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8257 Unqualified);
8258 if (!rmerge.isNull())
8259 return rmerge;
8260
8261 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8262}
8263
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008264QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008265 bool OfBlockPointer,
8266 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008267 const auto *lbase = lhs->getAs<FunctionType>();
8268 const auto *rbase = rhs->getAs<FunctionType>();
8269 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8270 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008271 bool allLTypes = true;
8272 bool allRTypes = true;
8273
8274 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008275 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008276 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008277 QualType RHS = rbase->getReturnType();
8278 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008279 bool UnqualifiedResult = Unqualified;
8280 if (!UnqualifiedResult)
8281 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008282 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008283 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008284 else
Alp Toker314cc812014-01-25 16:55:45 +00008285 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008286 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008287 if (retType.isNull())
8288 return {};
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008289
8290 if (Unqualified)
8291 retType = retType.getUnqualifiedType();
8292
Alp Toker314cc812014-01-25 16:55:45 +00008293 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8294 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008295 if (Unqualified) {
8296 LRetType = LRetType.getUnqualifiedType();
8297 RRetType = RRetType.getUnqualifiedType();
8298 }
8299
8300 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008301 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008302 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008303 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008304
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008305 // FIXME: double check this
8306 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8307 // rbase->getRegParmAttr() != 0 &&
8308 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008309 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8310 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008311
Douglas Gregor8c940862010-01-18 17:14:39 +00008312 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008313 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008314 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008315
John McCall8c6b56f2010-12-15 01:06:38 +00008316 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008317 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008318 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008319 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008320 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008321
John McCall31168b02011-06-15 23:02:42 +00008322 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008323 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008324 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008325 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008326 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008327 return {};
John McCall31168b02011-06-15 23:02:42 +00008328
John McCall8c6b56f2010-12-15 01:06:38 +00008329 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8330 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008331
Rafael Espindola8778c282012-11-29 16:09:03 +00008332 if (lbaseInfo.getNoReturn() != NoReturn)
8333 allLTypes = false;
8334 if (rbaseInfo.getNoReturn() != NoReturn)
8335 allRTypes = false;
8336
John McCall31168b02011-06-15 23:02:42 +00008337 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008338
Eli Friedman47f77112008-08-22 00:56:42 +00008339 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008340 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8341 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008342 // Compatible functions must have the same number of parameters
8343 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008344 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008345
8346 // Variadic and non-variadic functions aren't compatible
8347 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008348 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008349
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008350 if (lproto->getTypeQuals() != rproto->getTypeQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008351 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008352
Akira Hatanaka98a49332017-09-22 00:41:05 +00008353 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8354 bool canUseLeft, canUseRight;
8355 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8356 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008357 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008358
Akira Hatanaka98a49332017-09-22 00:41:05 +00008359 if (!canUseLeft)
8360 allLTypes = false;
8361 if (!canUseRight)
8362 allRTypes = false;
8363
Alp Toker601b22c2014-01-21 23:35:24 +00008364 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008365 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008366 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8367 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8368 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8369 QualType paramType = mergeFunctionParameterTypes(
8370 lParamType, rParamType, OfBlockPointer, Unqualified);
8371 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008372 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008373
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008374 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008375 paramType = paramType.getUnqualifiedType();
8376
8377 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008378 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008379 lParamType = lParamType.getUnqualifiedType();
8380 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008381 }
Alp Toker601b22c2014-01-21 23:35:24 +00008382
8383 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008384 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008385 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008386 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008387 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008388
Eli Friedman47f77112008-08-22 00:56:42 +00008389 if (allLTypes) return lhs;
8390 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008391
8392 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8393 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008394 EPI.ExtParameterInfos =
8395 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008396 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008397 }
8398
8399 if (lproto) allRTypes = false;
8400 if (rproto) allLTypes = false;
8401
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008402 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008403 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008404 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008405 if (proto->isVariadic())
8406 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008407 // Check that the types are compatible with the types that
8408 // would result from default argument promotions (C99 6.7.5.3p15).
8409 // The only types actually affected are promotable integer
8410 // types and floats, which would be passed as a different
8411 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008412 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8413 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008414
Eli Friedman448ce402012-08-30 00:44:15 +00008415 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008416 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008417 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008418 paramTy = Enum->getDecl()->getIntegerType();
8419 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008420 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008421 }
Alp Toker601b22c2014-01-21 23:35:24 +00008422
8423 if (paramTy->isPromotableIntegerType() ||
8424 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008425 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008426 }
8427
8428 if (allLTypes) return lhs;
8429 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008430
8431 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8432 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008433 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008434 }
8435
8436 if (allLTypes) return lhs;
8437 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008438 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008439}
8440
John McCall433c2e62013-03-21 00:10:07 +00008441/// Given that we have an enum type and a non-enum type, try to merge them.
8442static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8443 QualType other, bool isBlockReturnType) {
8444 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8445 // a signed integer type, or an unsigned integer type.
8446 // Compatibility is based on the underlying type, not the promotion
8447 // type.
8448 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008449 if (underlyingType.isNull())
8450 return {};
John McCall433c2e62013-03-21 00:10:07 +00008451 if (Context.hasSameType(underlyingType, other))
8452 return other;
8453
8454 // In block return types, we're more permissive and accept any
8455 // integral type of the same size.
8456 if (isBlockReturnType && other->isIntegerType() &&
8457 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8458 return other;
8459
Eugene Zelenko7855e772018-04-03 00:11:50 +00008460 return {};
John McCall433c2e62013-03-21 00:10:07 +00008461}
8462
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008463QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008464 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008465 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008466 // C++ [expr]: If an expression initially has the type "reference to T", the
8467 // type is adjusted to "T" prior to any further analysis, the expression
8468 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008469 // expression is an lvalue unless the reference is an rvalue reference and
8470 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008471 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8472 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008473
8474 if (Unqualified) {
8475 LHS = LHS.getUnqualifiedType();
8476 RHS = RHS.getUnqualifiedType();
8477 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00008478
Eli Friedman47f77112008-08-22 00:56:42 +00008479 QualType LHSCan = getCanonicalType(LHS),
8480 RHSCan = getCanonicalType(RHS);
8481
8482 // If two types are identical, they are compatible.
8483 if (LHSCan == RHSCan)
8484 return LHS;
8485
John McCall8ccfcb52009-09-24 19:53:00 +00008486 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008487 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8488 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008489 if (LQuals != RQuals) {
8490 // If any of these qualifiers are different, we have a type
8491 // mismatch.
8492 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008493 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008494 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8495 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008496 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008497
8498 // Exactly one GC qualifier difference is allowed: __strong is
8499 // okay if the other type has no GC qualifier but is an Objective
8500 // C object pointer (i.e. implicitly strong by default). We fix
8501 // this by pretending that the unqualified type was actually
8502 // qualified __strong.
8503 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8504 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8505 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8506
8507 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008508 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008509
8510 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8511 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8512 }
8513 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8514 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8515 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008516 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008517 }
8518
8519 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008520
Eli Friedmandcca6332009-06-01 01:22:52 +00008521 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8522 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008523
Chris Lattnerfd652912008-01-14 05:45:46 +00008524 // We want to consider the two function types to be the same for these
8525 // comparisons, just force one to the other.
8526 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8527 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008528
8529 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008530 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8531 LHSClass = Type::ConstantArray;
8532 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8533 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008534
John McCall8b07ec22010-05-15 11:32:37 +00008535 // ObjCInterfaces are just specialized ObjCObjects.
8536 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8537 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8538
Nate Begemance4d7fc2008-04-18 23:10:10 +00008539 // Canonicalize ExtVector -> Vector.
8540 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8541 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008542
Chris Lattner95554662008-04-07 05:43:21 +00008543 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008544 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008545 // Note that we only have special rules for turning block enum
8546 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008547 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008548 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008549 }
John McCall9dd450b2009-09-21 23:43:11 +00008550 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008551 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008552 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008553 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008554 if (OfBlockPointer && !BlockReturnType) {
8555 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8556 return LHS;
8557 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8558 return RHS;
8559 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008560
Eugene Zelenko7855e772018-04-03 00:11:50 +00008561 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008562 }
Eli Friedman47f77112008-08-22 00:56:42 +00008563
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008564 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008565 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008566#define TYPE(Class, Base)
8567#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008568#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008569#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8570#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8571#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008572 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008573
Richard Smith27d807c2013-04-30 13:56:41 +00008574 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008575 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008576 case Type::LValueReference:
8577 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008578 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008579 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008580
John McCall8b07ec22010-05-15 11:32:37 +00008581 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008582 case Type::IncompleteArray:
8583 case Type::VariableArray:
8584 case Type::FunctionProto:
8585 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008586 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008587
Chris Lattnerfd652912008-01-14 05:45:46 +00008588 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008589 {
8590 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008591 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8592 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008593 if (Unqualified) {
8594 LHSPointee = LHSPointee.getUnqualifiedType();
8595 RHSPointee = RHSPointee.getUnqualifiedType();
8596 }
8597 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8598 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008599 if (ResultType.isNull())
8600 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008601 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008602 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008603 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008604 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008605 return getPointerType(ResultType);
8606 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008607 case Type::BlockPointer:
8608 {
8609 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008610 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8611 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008612 if (Unqualified) {
8613 LHSPointee = LHSPointee.getUnqualifiedType();
8614 RHSPointee = RHSPointee.getUnqualifiedType();
8615 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008616 if (getLangOpts().OpenCL) {
8617 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8618 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8619 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8620 // 6.12.5) thus the following check is asymmetric.
8621 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008622 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008623 LHSPteeQual.removeAddressSpace();
8624 RHSPteeQual.removeAddressSpace();
8625 LHSPointee =
8626 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8627 RHSPointee =
8628 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8629 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008630 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8631 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008632 if (ResultType.isNull())
8633 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00008634 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8635 return LHS;
8636 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8637 return RHS;
8638 return getBlockPointerType(ResultType);
8639 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008640 case Type::Atomic:
8641 {
8642 // Merge two pointer types, while trying to preserve typedef info
8643 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8644 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8645 if (Unqualified) {
8646 LHSValue = LHSValue.getUnqualifiedType();
8647 RHSValue = RHSValue.getUnqualifiedType();
8648 }
8649 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8650 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008651 if (ResultType.isNull())
8652 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00008653 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8654 return LHS;
8655 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8656 return RHS;
8657 return getAtomicType(ResultType);
8658 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008659 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008660 {
8661 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8662 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8663 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008664 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008665
8666 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8667 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008668 if (Unqualified) {
8669 LHSElem = LHSElem.getUnqualifiedType();
8670 RHSElem = RHSElem.getUnqualifiedType();
8671 }
8672
8673 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008674 if (ResultType.isNull())
8675 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00008676
8677 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8678 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8679
8680 // If either side is a variable array, and both are complete, check whether
8681 // the current dimension is definite.
8682 if (LVAT || RVAT) {
8683 auto SizeFetch = [this](const VariableArrayType* VAT,
8684 const ConstantArrayType* CAT)
8685 -> std::pair<bool,llvm::APInt> {
8686 if (VAT) {
8687 llvm::APSInt TheInt;
8688 Expr *E = VAT->getSizeExpr();
8689 if (E && E->isIntegerConstantExpr(TheInt, *this))
8690 return std::make_pair(true, TheInt);
8691 else
8692 return std::make_pair(false, TheInt);
8693 } else if (CAT) {
8694 return std::make_pair(true, CAT->getSize());
8695 } else {
8696 return std::make_pair(false, llvm::APInt());
8697 }
8698 };
8699
8700 bool HaveLSize, HaveRSize;
8701 llvm::APInt LSize, RSize;
8702 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
8703 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
8704 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
8705 return {}; // Definite, but unequal, array dimension
8706 }
8707
Chris Lattner465fa322008-10-05 17:34:18 +00008708 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8709 return LHS;
8710 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8711 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008712 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8713 ArrayType::ArraySizeModifier(), 0);
8714 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8715 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00008716 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8717 return LHS;
8718 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8719 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008720 if (LVAT) {
8721 // FIXME: This isn't correct! But tricky to implement because
8722 // the array's size has to be the size of LHS, but the type
8723 // has to be different.
8724 return LHS;
8725 }
8726 if (RVAT) {
8727 // FIXME: This isn't correct! But tricky to implement because
8728 // the array's size has to be the size of RHS, but the type
8729 // has to be different.
8730 return RHS;
8731 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008732 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8733 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008734 return getIncompleteArrayType(ResultType,
8735 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008736 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008737 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008738 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008739 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008740 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00008741 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00008742 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008743 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008744 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00008745 case Type::Complex:
8746 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008747 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008748 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008749 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008750 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8751 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008752 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008753 return {};
John McCall8b07ec22010-05-15 11:32:37 +00008754 case Type::ObjCObject: {
8755 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008756 // FIXME: This should be type compatibility, e.g. whether
8757 // "LHS x; RHS x;" at global scope is legal.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008758 const auto *LHSIface = LHS->getAs<ObjCObjectType>();
8759 const auto *RHSIface = RHS->getAs<ObjCObjectType>();
John McCall8b07ec22010-05-15 11:32:37 +00008760 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008761 return LHS;
8762
Eugene Zelenko7855e772018-04-03 00:11:50 +00008763 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00008764 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008765 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008766 if (OfBlockPointer) {
8767 if (canAssignObjCInterfacesInBlockPointer(
8768 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008769 RHS->getAs<ObjCObjectPointerType>(),
8770 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008771 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008772 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008773 }
John McCall9dd450b2009-09-21 23:43:11 +00008774 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8775 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008776 return LHS;
8777
Eugene Zelenko7855e772018-04-03 00:11:50 +00008778 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00008779 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00008780 assert(LHS != RHS &&
8781 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008782 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00008783 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008784
David Blaikie8a40f702012-01-17 06:56:22 +00008785 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008786}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008787
Akira Hatanaka98a49332017-09-22 00:41:05 +00008788bool ASTContext::mergeExtParameterInfo(
8789 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
8790 bool &CanUseFirst, bool &CanUseSecond,
8791 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
8792 assert(NewParamInfos.empty() && "param info list not empty");
8793 CanUseFirst = CanUseSecond = true;
8794 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
8795 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
8796
John McCall18afab72016-03-01 00:49:02 +00008797 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00008798 // we match if and only if the second type also doesn't have them.
8799 if (!FirstHasInfo && !SecondHasInfo)
8800 return true;
John McCall18afab72016-03-01 00:49:02 +00008801
Akira Hatanaka98a49332017-09-22 00:41:05 +00008802 bool NeedParamInfo = false;
8803 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
8804 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00008805
Akira Hatanaka98a49332017-09-22 00:41:05 +00008806 for (size_t I = 0; I < E; ++I) {
8807 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
8808 if (FirstHasInfo)
8809 FirstParam = FirstFnType->getExtParameterInfo(I);
8810 if (SecondHasInfo)
8811 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00008812
Akira Hatanaka98a49332017-09-22 00:41:05 +00008813 // Cannot merge unless everything except the noescape flag matches.
8814 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00008815 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008816
8817 bool FirstNoEscape = FirstParam.isNoEscape();
8818 bool SecondNoEscape = SecondParam.isNoEscape();
8819 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
8820 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
8821 if (NewParamInfos.back().getOpaqueValue())
8822 NeedParamInfo = true;
8823 if (FirstNoEscape != IsNoEscape)
8824 CanUseFirst = false;
8825 if (SecondNoEscape != IsNoEscape)
8826 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00008827 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00008828
8829 if (!NeedParamInfo)
8830 NewParamInfos.clear();
8831
Fariborz Jahanian97676972011-09-28 21:52:05 +00008832 return true;
8833}
8834
Chandler Carruth21c90602015-12-30 03:24:14 +00008835void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8836 ObjCLayouts[CD] = nullptr;
8837}
8838
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008839/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8840/// 'RHS' attributes and returns the merged version; including for function
8841/// return types.
8842QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8843 QualType LHSCan = getCanonicalType(LHS),
8844 RHSCan = getCanonicalType(RHS);
8845 // If two types are identical, they are compatible.
8846 if (LHSCan == RHSCan)
8847 return LHS;
8848 if (RHSCan->isFunctionType()) {
8849 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008850 return {};
Alp Toker314cc812014-01-25 16:55:45 +00008851 QualType OldReturnType =
8852 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008853 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008854 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008855 QualType ResReturnType =
8856 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8857 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008858 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008859 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8860 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8861 // In either case, use OldReturnType to build the new function type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008862 const auto *F = LHS->getAs<FunctionType>();
8863 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008864 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8865 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008866 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008867 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008868 return ResultType;
8869 }
8870 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008871 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008872 }
8873
8874 // If the qualifiers are different, the types can still be merged.
8875 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8876 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8877 if (LQuals != RQuals) {
8878 // If any of these qualifiers are different, we have a type mismatch.
8879 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8880 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008881 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008882
8883 // Exactly one GC qualifier difference is allowed: __strong is
8884 // okay if the other type has no GC qualifier but is an Objective
8885 // C object pointer (i.e. implicitly strong by default). We fix
8886 // this by pretending that the unqualified type was actually
8887 // qualified __strong.
8888 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8889 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8890 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8891
8892 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008893 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008894
8895 if (GC_L == Qualifiers::Strong)
8896 return LHS;
8897 if (GC_R == Qualifiers::Strong)
8898 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008899 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008900 }
8901
8902 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8903 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8904 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8905 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8906 if (ResQT == LHSBaseQT)
8907 return LHS;
8908 if (ResQT == RHSBaseQT)
8909 return RHS;
8910 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008911 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008912}
8913
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008914//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008915// Integer Predicates
8916//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008917
Jay Foad39c79802011-01-12 09:06:06 +00008918unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008919 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008920 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008921 if (T->isBooleanType())
8922 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008923 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008924 return (unsigned)getTypeSize(T);
8925}
8926
Abramo Bagnara13640492012-09-09 10:21:24 +00008927QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00008928 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
8929 "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008930
8931 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00008932 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00008933 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008934 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008935
8936 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008937 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008938 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008939
Eugene Zelenko7855e772018-04-03 00:11:50 +00008940 const auto *BTy = T->getAs<BuiltinType>();
Leonard Chanab80f3c2018-06-14 14:53:51 +00008941 assert(BTy && "Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008942 switch (BTy->getKind()) {
8943 case BuiltinType::Char_S:
8944 case BuiltinType::SChar:
8945 return UnsignedCharTy;
8946 case BuiltinType::Short:
8947 return UnsignedShortTy;
8948 case BuiltinType::Int:
8949 return UnsignedIntTy;
8950 case BuiltinType::Long:
8951 return UnsignedLongTy;
8952 case BuiltinType::LongLong:
8953 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008954 case BuiltinType::Int128:
8955 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00008956
8957 case BuiltinType::ShortAccum:
8958 return UnsignedShortAccumTy;
8959 case BuiltinType::Accum:
8960 return UnsignedAccumTy;
8961 case BuiltinType::LongAccum:
8962 return UnsignedLongAccumTy;
8963 case BuiltinType::SatShortAccum:
8964 return SatUnsignedShortAccumTy;
8965 case BuiltinType::SatAccum:
8966 return SatUnsignedAccumTy;
8967 case BuiltinType::SatLongAccum:
8968 return SatUnsignedLongAccumTy;
8969 case BuiltinType::ShortFract:
8970 return UnsignedShortFractTy;
8971 case BuiltinType::Fract:
8972 return UnsignedFractTy;
8973 case BuiltinType::LongFract:
8974 return UnsignedLongFractTy;
8975 case BuiltinType::SatShortFract:
8976 return SatUnsignedShortFractTy;
8977 case BuiltinType::SatFract:
8978 return SatUnsignedFractTy;
8979 case BuiltinType::SatLongFract:
8980 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008981 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00008982 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008983 }
8984}
8985
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008986ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008987
Richard Smith1fa5d642013-05-11 05:45:24 +00008988void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8989 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008990
8991//===----------------------------------------------------------------------===//
8992// Builtin Type Computation
8993//===----------------------------------------------------------------------===//
8994
8995/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008996/// pointer over the consumed characters. This returns the resultant type. If
8997/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8998/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8999/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009000///
9001/// RequiresICE is filled in on return to indicate whether the value is required
9002/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009003static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009004 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009005 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009006 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009007 // Modifiers.
9008 int HowLong = 0;
9009 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009010 RequiresICE = false;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009011
Chris Lattnerdc226c22010-10-01 22:42:38 +00009012 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009013 bool Done = false;
9014 #ifndef NDEBUG
9015 bool IsSpecialLong = false;
9016 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009017 while (!Done) {
9018 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009019 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009020 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009021 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009022 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009023 case 'S':
9024 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9025 assert(!Signed && "Can't use 'S' modifier multiple times!");
9026 Signed = true;
9027 break;
9028 case 'U':
9029 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009030 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009031 Unsigned = true;
9032 break;
9033 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009034 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009035 assert(HowLong <= 2 && "Can't have LLLL modifier");
9036 ++HowLong;
9037 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009038 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009039 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
9040 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
9041 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009042 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009043 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009044 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009045 if (Context.getTargetInfo().getLongWidth() == 32)
9046 ++HowLong;
9047 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009048 case 'W':
9049 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009050 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009051 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009052 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009053 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009054 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009055 switch (Context.getTargetInfo().getInt64Type()) {
9056 default:
9057 llvm_unreachable("Unexpected integer type");
9058 case TargetInfo::SignedLong:
9059 HowLong = 1;
9060 break;
9061 case TargetInfo::SignedLongLong:
9062 HowLong = 2;
9063 break;
9064 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009065 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009066 }
9067 }
9068
9069 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009070
Chris Lattnerecd79c62009-06-14 00:45:47 +00009071 // Read the base type.
9072 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009073 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009074 case 'v':
9075 assert(HowLong == 0 && !Signed && !Unsigned &&
9076 "Bad modifiers used with 'v'!");
9077 Type = Context.VoidTy;
9078 break;
Jack Carter24bef982013-08-15 15:16:57 +00009079 case 'h':
9080 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009081 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009082 Type = Context.HalfTy;
9083 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009084 case 'f':
9085 assert(HowLong == 0 && !Signed && !Unsigned &&
9086 "Bad modifiers used with 'f'!");
9087 Type = Context.FloatTy;
9088 break;
9089 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009090 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009091 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009092 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009093 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009094 else if (HowLong == 2)
9095 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009096 else
9097 Type = Context.DoubleTy;
9098 break;
9099 case 's':
9100 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9101 if (Unsigned)
9102 Type = Context.UnsignedShortTy;
9103 else
9104 Type = Context.ShortTy;
9105 break;
9106 case 'i':
9107 if (HowLong == 3)
9108 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9109 else if (HowLong == 2)
9110 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9111 else if (HowLong == 1)
9112 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9113 else
9114 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9115 break;
9116 case 'c':
9117 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9118 if (Signed)
9119 Type = Context.SignedCharTy;
9120 else if (Unsigned)
9121 Type = Context.UnsignedCharTy;
9122 else
9123 Type = Context.CharTy;
9124 break;
9125 case 'b': // boolean
9126 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9127 Type = Context.BoolTy;
9128 break;
9129 case 'z': // size_t.
9130 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9131 Type = Context.getSizeType();
9132 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009133 case 'w': // wchar_t.
9134 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9135 Type = Context.getWideCharType();
9136 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009137 case 'F':
9138 Type = Context.getCFConstantStringType();
9139 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009140 case 'G':
9141 Type = Context.getObjCIdType();
9142 break;
9143 case 'H':
9144 Type = Context.getObjCSelType();
9145 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009146 case 'M':
9147 Type = Context.getObjCSuperType();
9148 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009149 case 'a':
9150 Type = Context.getBuiltinVaListType();
9151 assert(!Type.isNull() && "builtin va list type not initialized!");
9152 break;
9153 case 'A':
9154 // This is a "reference" to a va_list; however, what exactly
9155 // this means depends on how va_list is defined. There are two
9156 // different kinds of va_list: ones passed by value, and ones
9157 // passed by reference. An example of a by-value va_list is
9158 // x86, where va_list is a char*. An example of by-ref va_list
9159 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9160 // we want this argument to be a char*&; for x86-64, we want
9161 // it to be a __va_list_tag*.
9162 Type = Context.getBuiltinVaListType();
9163 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009164 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009165 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009166 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009167 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009168 break;
9169 case 'V': {
9170 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009171 unsigned NumElements = strtoul(Str, &End, 10);
9172 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009173 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009174
Chandler Carruth45bbe012017-03-24 09:11:57 +00009175 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
9176 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009177 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00009178
9179 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009180 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009181 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009182 break;
9183 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009184 case 'E': {
9185 char *End;
9186
9187 unsigned NumElements = strtoul(Str, &End, 10);
9188 assert(End != Str && "Missing vector size");
9189
9190 Str = End;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009191
Douglas Gregorfed66992012-06-07 18:08:25 +00009192 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009193 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009194 Type = Context.getExtVectorType(ElementType, NumElements);
9195 break;
9196 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009197 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009198 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009199 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009200 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009201 Type = Context.getComplexType(ElementType);
9202 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009203 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009204 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009205 Type = Context.getPointerDiffType();
9206 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009207 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009208 Type = Context.getFILEType();
9209 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009210 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009211 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009212 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009213 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009214 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009215 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009216 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009217 else
9218 Type = Context.getjmp_bufType();
9219
Mike Stump2adb4da2009-07-28 23:47:15 +00009220 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009221 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009222 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009223 }
9224 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009225 case 'K':
9226 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9227 Type = Context.getucontext_tType();
9228
9229 if (Type.isNull()) {
9230 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009231 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009232 }
9233 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009234 case 'p':
9235 Type = Context.getProcessIDType();
9236 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009237 }
Mike Stump11289f42009-09-09 15:08:12 +00009238
Chris Lattnerdc226c22010-10-01 22:42:38 +00009239 // If there are modifiers and if we're allowed to parse them, go for it.
9240 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009241 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009242 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009243 default: Done = true; --Str; break;
9244 case '*':
9245 case '&': {
9246 // Both pointers and references can have their pointee types
9247 // qualified with an address space.
9248 char *End;
9249 unsigned AddrSpace = strtoul(Str, &End, 10);
9250 if (End != Str && AddrSpace != 0) {
Alexander Richardson6d989432017-10-15 18:48:14 +00009251 Type = Context.getAddrSpaceQualType(Type,
9252 getLangASFromTargetAS(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009253 Str = End;
9254 }
9255 if (c == '*')
9256 Type = Context.getPointerType(Type);
9257 else
9258 Type = Context.getLValueReferenceType(Type);
9259 break;
9260 }
9261 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9262 case 'C':
9263 Type = Type.withConst();
9264 break;
9265 case 'D':
9266 Type = Context.getVolatileType(Type);
9267 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009268 case 'R':
9269 Type = Type.withRestrict();
9270 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009271 }
9272 }
Chris Lattner84733392010-10-01 07:13:18 +00009273
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009274 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00009275 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009276
Chris Lattnerecd79c62009-06-14 00:45:47 +00009277 return Type;
9278}
9279
9280/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009281QualType ASTContext::GetBuiltinType(unsigned Id,
9282 GetBuiltinTypeError &Error,
9283 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009284 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00009285
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009286 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009287
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009288 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009289 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009290 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9291 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009292 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009293 return {};
Chandler Carruth45bbe012017-03-24 09:11:57 +00009294
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009295 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Chandler Carruth45bbe012017-03-24 09:11:57 +00009296
Chris Lattnerecd79c62009-06-14 00:45:47 +00009297 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009298 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009299 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009300 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009301
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009302 // If this argument is required to be an IntegerConstantExpression and the
9303 // caller cares, fill in the bitmask we return.
9304 if (RequiresICE && IntegerConstantArgs)
9305 *IntegerConstantArgs |= 1 << ArgTypes.size();
9306
Chris Lattnerecd79c62009-06-14 00:45:47 +00009307 // Do array -> pointer decay. The builtin should use the decayed type.
9308 if (Ty->isArrayType())
9309 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009310
Chris Lattnerecd79c62009-06-14 00:45:47 +00009311 ArgTypes.push_back(Ty);
9312 }
9313
David Majnemerba3e5ec2015-03-13 18:26:17 +00009314 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009315 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009316
Chris Lattnerecd79c62009-06-14 00:45:47 +00009317 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9318 "'.' should only occur at end of builtin type list!");
9319
Reid Kleckner78af0702013-08-27 23:08:25 +00009320 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00009321 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9322
9323 bool Variadic = (TypeStr[0] == '.');
9324
Richard Smith836de6b2016-12-19 23:59:34 +00009325 // We really shouldn't be making a no-proto type here.
9326 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009327 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009328
John McCalldb40c7f2010-12-14 08:05:40 +00009329 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009330 EPI.ExtInfo = EI;
9331 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009332 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9333 EPI.ExceptionSpec.Type =
9334 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009335
Jordan Rose5c382722013-03-08 21:51:21 +00009336 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009337}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009338
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009339static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9340 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009341 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009342 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009343
Richard Smithe2467b72017-11-16 23:54:56 +00009344 // Non-user-provided functions get emitted as weak definitions with every
9345 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009346 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009347 if (!MD->isUserProvided())
9348 return GVA_DiscardableODR;
9349
Yaron Keren4cd211b2017-02-22 14:32:39 +00009350 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009351 switch (FD->getTemplateSpecializationKind()) {
9352 case TSK_Undeclared:
9353 case TSK_ExplicitSpecialization:
9354 External = GVA_StrongExternal;
9355 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009356
Rafael Espindola3ae00052013-05-13 00:12:11 +00009357 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009358 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009359
David Majnemerc3d07332014-05-15 06:25:57 +00009360 // C++11 [temp.explicit]p10:
9361 // [ Note: The intent is that an inline function that is the subject of
9362 // an explicit instantiation declaration will still be implicitly
9363 // instantiated when used so that the body can be considered for
9364 // inlining, but that no out-of-line copy of the inline function would be
9365 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009366 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009367 return GVA_AvailableExternally;
9368
Rafael Espindola3ae00052013-05-13 00:12:11 +00009369 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009370 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009371 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009372 }
9373
9374 if (!FD->isInlined())
9375 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009376
David Majnemer3f021502015-10-08 04:53:31 +00009377 if ((!Context.getLangOpts().CPlusPlus &&
9378 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009379 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009380 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009381 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9382
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009383 // GNU or C99 inline semantics. Determine whether this symbol should be
9384 // externally visible.
9385 if (FD->isInlineDefinitionExternallyVisible())
9386 return External;
9387
9388 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009389 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009390 }
9391
David Majnemer54e3ba52014-04-02 23:17:29 +00009392 // Functions specified with extern and inline in -fms-compatibility mode
9393 // forcibly get emitted. While the body of the function cannot be later
9394 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009395 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009396 return GVA_StrongODR;
9397
David Majnemer27d69db2014-04-28 22:17:59 +00009398 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009399}
9400
Artem Belevichca2b9512016-05-02 20:30:03 +00009401static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009402 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009403 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9404 // dllexport/dllimport on inline functions.
9405 if (D->hasAttr<DLLImportAttr>()) {
9406 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9407 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009408 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009409 if (L == GVA_DiscardableODR)
9410 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009411 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9412 D->hasAttr<CUDAGlobalAttr>()) {
9413 // Device-side functions with __global__ attribute must always be
9414 // visible externally so they can be launched from host.
9415 if (L == GVA_DiscardableODR || L == GVA_Internal)
9416 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009417 }
9418 return L;
9419}
9420
Richard Smitha4653622017-09-06 20:01:14 +00009421/// Adjust the GVALinkage for a declaration based on what an external AST source
9422/// knows about whether there can be other definitions of this declaration.
9423static GVALinkage
9424adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9425 GVALinkage L) {
9426 ExternalASTSource *Source = Ctx.getExternalSource();
9427 if (!Source)
9428 return L;
9429
9430 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009431 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009432 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009433 if (L == GVA_DiscardableODR)
9434 return GVA_StrongODR;
9435 break;
Richard Smitha4653622017-09-06 20:01:14 +00009436
David Blaikie9ffe5a32017-01-30 05:00:26 +00009437 case ExternalASTSource::EK_Always:
9438 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009439
David Blaikie9ffe5a32017-01-30 05:00:26 +00009440 case ExternalASTSource::EK_ReplyHazy:
9441 break;
9442 }
9443 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009444}
9445
Richard Smitha4653622017-09-06 20:01:14 +00009446GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9447 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9448 adjustGVALinkageForAttributes(*this, FD,
9449 basicGVALinkageForFunction(*this, FD)));
9450}
9451
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009452static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9453 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009454 if (!VD->isExternallyVisible())
9455 return GVA_Internal;
9456
David Majnemer27d69db2014-04-28 22:17:59 +00009457 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009458 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9459 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9460 LexicalContext = LexicalContext->getLexicalParent();
9461
David Blaikieeb210012017-01-27 23:11:10 +00009462 // ObjC Blocks can create local variables that don't have a FunctionDecl
9463 // LexicalContext.
9464 if (!LexicalContext)
9465 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009466
David Blaikieeb210012017-01-27 23:11:10 +00009467 // Otherwise, let the static local variable inherit its linkage from the
9468 // nearest enclosing function.
9469 auto StaticLocalLinkage =
9470 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9471
9472 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9473 // be emitted in any object with references to the symbol for the object it
9474 // contains, whether inline or out-of-line."
9475 // Similar behavior is observed with MSVC. An alternative ABI could use
9476 // StrongODR/AvailableExternally to match the function, but none are
9477 // known/supported currently.
9478 if (StaticLocalLinkage == GVA_StrongODR ||
9479 StaticLocalLinkage == GVA_AvailableExternally)
9480 return GVA_DiscardableODR;
9481 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009482 }
9483
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009484 // MSVC treats in-class initialized static data members as definitions.
9485 // By giving them non-strong linkage, out-of-line definitions won't
9486 // cause link errors.
9487 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9488 return GVA_DiscardableODR;
9489
Richard Smithd9b90092016-07-02 01:32:16 +00009490 // Most non-template variables have strong linkage; inline variables are
9491 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9492 GVALinkage StrongLinkage;
9493 switch (Context.getInlineVariableDefinitionKind(VD)) {
9494 case ASTContext::InlineVariableDefinitionKind::None:
9495 StrongLinkage = GVA_StrongExternal;
9496 break;
9497 case ASTContext::InlineVariableDefinitionKind::Weak:
9498 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009499 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009500 break;
9501 case ASTContext::InlineVariableDefinitionKind::Strong:
9502 StrongLinkage = GVA_StrongODR;
9503 break;
9504 }
Richard Smith62f19e72016-06-25 00:15:56 +00009505
Richard Smith8809a0c2013-09-27 20:14:12 +00009506 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009507 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009508 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009509
David Majnemer6d1780c2015-07-17 23:36:49 +00009510 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00009511 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9512 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00009513 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00009514 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009515
Rafael Espindola3ae00052013-05-13 00:12:11 +00009516 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009517 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009518
David Majnemer27d69db2014-04-28 22:17:59 +00009519 case TSK_ExplicitInstantiationDeclaration:
9520 return GVA_AvailableExternally;
9521
Rafael Espindola3ae00052013-05-13 00:12:11 +00009522 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009523 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009524 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009525
9526 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009527}
9528
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009529GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009530 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9531 adjustGVALinkageForAttributes(*this, VD,
9532 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009533}
9534
David Blaikiee6b7c282017-04-11 20:46:34 +00009535bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009536 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009537 if (!VD->isFileVarDecl())
9538 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009539 // Global named register variables (GNU extension) are never emitted.
9540 if (VD->getStorageClass() == SC_Register)
9541 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009542 if (VD->getDescribedVarTemplate() ||
9543 isa<VarTemplatePartialSpecializationDecl>(VD))
9544 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009545 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +00009546 // We never need to emit an uninstantiated function template.
9547 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9548 return false;
Nico Weber66220292016-03-02 17:28:48 +00009549 } else if (isa<PragmaCommentDecl>(D))
9550 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009551 else if (isa<OMPThreadPrivateDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009552 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009553 else if (isa<PragmaDetectMismatchDecl>(D))
9554 return true;
Nico Weber66220292016-03-02 17:28:48 +00009555 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009556 return !D->getDeclContext()->isDependentContext();
9557 else if (isa<OMPDeclareReductionDecl>(D))
9558 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009559 else if (isa<ImportDecl>(D))
9560 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009561 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009562 return false;
9563
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009564 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9565 assert(getExternalSource() && "It's from an AST file; must have a source.");
9566 // On Windows, PCH files are built together with an object file. If this
9567 // declaration comes from such a PCH and DeclMustBeEmitted would return
9568 // true, it would have returned true and the decl would have been emitted
9569 // into that object file, so it doesn't need to be emitted here.
9570 // Note that decls are still emitted if they're referenced, as usual;
9571 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9572 // if it's not referenced.
9573 //
9574 // Explicit template instantiation definitions are tricky. If there was an
9575 // explicit template instantiation decl in the PCH before, it will look like
9576 // the definition comes from there, even if that was just the declaration.
9577 // (Explicit instantiation defs of variable templates always get emitted.)
9578 bool IsExpInstDef =
9579 isa<FunctionDecl>(D) &&
9580 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
9581 TSK_ExplicitInstantiationDefinition;
9582
9583 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
9584 return false;
9585 }
9586
Richard Smith5205a8c2013-04-01 20:22:16 +00009587 // If this is a member of a class template, we do not need to emit it.
9588 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009589 return false;
9590
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009591 // Weak references don't produce any output by themselves.
9592 if (D->hasAttr<WeakRefAttr>())
9593 return false;
9594
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009595 // Aliases and used decls are required.
9596 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9597 return true;
9598
Eugene Zelenko7855e772018-04-03 00:11:50 +00009599 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009600 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009601 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009602 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009603
9604 // Constructors and destructors are required.
9605 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9606 return true;
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009607
John McCall6bd2a892013-01-25 22:31:03 +00009608 // The key function for a class is required. This rule only comes
9609 // into play when inline functions can be key functions, though.
9610 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009611 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +00009612 const CXXRecordDecl *RD = MD->getParent();
9613 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9614 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9615 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9616 return true;
9617 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009618 }
9619 }
9620
David Blaikie9ffe5a32017-01-30 05:00:26 +00009621 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9622
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009623 // static, static inline, always_inline, and extern inline functions can
9624 // always be deferred. Normal inline functions can be deferred in C99/C++.
9625 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009626 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009627 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009628
Eugene Zelenko7855e772018-04-03 00:11:50 +00009629 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009630 assert(VD->isFileVarDecl() && "Expected file scoped var");
9631
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009632 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9633 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009634 return false;
9635
Richard Smitha0e5e542012-11-12 21:38:00 +00009636 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009637 auto Linkage = GetGVALinkageForVariable(VD);
9638 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009639 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009640
Richard Smitha4653622017-09-06 20:01:14 +00009641 // We never need to emit a variable that is available in another TU.
9642 if (Linkage == GVA_AvailableExternally)
9643 return false;
9644
Richard Smitha0e5e542012-11-12 21:38:00 +00009645 // Variables that have destruction with side-effects are required.
9646 if (VD->getType().isDestructedType())
9647 return true;
9648
9649 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009650 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009651 // We can get a value-dependent initializer during error recovery.
9652 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009653 return true;
9654
Richard Smithda383632016-08-15 01:33:41 +00009655 // Likewise, variables with tuple-like bindings are required if their
9656 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009657 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
9658 for (const auto *BD : DD->bindings())
9659 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +00009660 if (DeclMustBeEmitted(BindingVD))
9661 return true;
9662
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009663 // If the decl is marked as `declare target`, it should be emitted.
Alexey Bataev92327c52018-03-26 16:40:55 +00009664 for (const auto *Decl : D->redecls()) {
9665 if (!Decl->hasAttrs())
9666 continue;
9667 if (const auto *Attr = Decl->getAttr<OMPDeclareTargetDeclAttr>())
9668 if (Attr->getMapType() != OMPDeclareTargetDeclAttr::MT_Link)
9669 return true;
9670 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009671
Richard Smitha0e5e542012-11-12 21:38:00 +00009672 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009673}
Charles Davis53c59df2010-08-16 03:33:14 +00009674
Erich Keane281d20b2018-01-08 21:34:17 +00009675void ASTContext::forEachMultiversionedFunctionVersion(
9676 const FunctionDecl *FD,
9677 llvm::function_ref<void(const FunctionDecl *)> Pred) const {
9678 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
9679 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
9680 FD = FD->getCanonicalDecl();
9681 for (auto *CurDecl :
9682 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
9683 FunctionDecl *CurFD = CurDecl->getAsFunction()->getCanonicalDecl();
9684 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
9685 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
9686 SeenDecls.insert(CurFD);
9687 Pred(CurFD);
9688 }
9689 }
9690}
9691
Reid Kleckner78af0702013-08-27 23:08:25 +00009692CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9693 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009694 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009695 if (IsCXXMethod)
9696 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009697
Alexey Bataeva7547182016-05-18 09:06:38 +00009698 switch (LangOpts.getDefaultCallingConv()) {
9699 case LangOptions::DCC_None:
9700 break;
9701 case LangOptions::DCC_CDecl:
9702 return CC_C;
9703 case LangOptions::DCC_FastCall:
Erich Keane5759fa72017-10-24 23:12:01 +00009704 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
Alexey Bataeva7547182016-05-18 09:06:38 +00009705 return CC_X86FastCall;
9706 break;
9707 case LangOptions::DCC_StdCall:
9708 if (!IsVariadic)
9709 return CC_X86StdCall;
9710 break;
9711 case LangOptions::DCC_VectorCall:
9712 // __vectorcall cannot be applied to variadic functions.
9713 if (!IsVariadic)
9714 return CC_X86VectorCall;
9715 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00009716 case LangOptions::DCC_RegCall:
9717 // __regcall cannot be applied to variadic functions.
9718 if (!IsVariadic)
9719 return CC_X86RegCall;
9720 break;
Alexey Bataeva7547182016-05-18 09:06:38 +00009721 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009722 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009723}
9724
Jay Foad39c79802011-01-12 09:06:06 +00009725bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009726 // Pass through to the C++ ABI object
9727 return ABI->isNearlyEmpty(RD);
9728}
9729
Reid Kleckner96f8f932014-02-05 17:27:08 +00009730VTableContextBase *ASTContext::getVTableContext() {
9731 if (!VTContext.get()) {
9732 if (Target->getCXXABI().isMicrosoft())
9733 VTContext.reset(new MicrosoftVTableContext(*this));
9734 else
9735 VTContext.reset(new ItaniumVTableContext(*this));
9736 }
9737 return VTContext.get();
9738}
9739
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009740MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009741 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009742 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009743 case TargetCXXABI::GenericItanium:
9744 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009745 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009746 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009747 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009748 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009749 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009750 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009751 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009752 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009753 }
David Blaikie83d382b2011-09-23 05:06:16 +00009754 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009755}
9756
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009757CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009758
9759size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009760 return ASTRecordLayouts.getMemorySize() +
9761 llvm::capacity_in_bytes(ObjCLayouts) +
9762 llvm::capacity_in_bytes(KeyFunctions) +
9763 llvm::capacity_in_bytes(ObjCImpls) +
9764 llvm::capacity_in_bytes(BlockVarCopyInits) +
9765 llvm::capacity_in_bytes(DeclAttrs) +
9766 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9767 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9768 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9769 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9770 llvm::capacity_in_bytes(OverriddenMethods) +
9771 llvm::capacity_in_bytes(Types) +
9772 llvm::capacity_in_bytes(VariableArrayTypes) +
9773 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009774}
Ted Kremenek540017e2011-10-06 05:00:56 +00009775
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009776/// getIntTypeForBitwidth -
9777/// sets integer QualTy according to specified details:
9778/// bitwidth, signed/unsigned.
9779/// Returns empty type if there is no appropriate target types.
9780QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9781 unsigned Signed) const {
9782 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9783 CanQualType QualTy = getFromTargetType(Ty);
9784 if (!QualTy && DestWidth == 128)
9785 return Signed ? Int128Ty : UnsignedInt128Ty;
9786 return QualTy;
9787}
9788
9789/// getRealTypeForBitwidth -
9790/// sets floating point QualTy according to specified bitwidth.
9791/// Returns empty type if there is no appropriate target types.
9792QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9793 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9794 switch (Ty) {
9795 case TargetInfo::Float:
9796 return FloatTy;
9797 case TargetInfo::Double:
9798 return DoubleTy;
9799 case TargetInfo::LongDouble:
9800 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009801 case TargetInfo::Float128:
9802 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009803 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +00009804 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009805 }
9806
9807 llvm_unreachable("Unhandled TargetInfo::RealType value");
9808}
9809
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009810void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9811 if (Number > 1)
9812 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009813}
9814
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009815unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009816 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009817 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009818}
9819
David Majnemer2206bf52014-03-05 08:57:59 +00009820void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9821 if (Number > 1)
9822 StaticLocalNumbers[VD] = Number;
9823}
9824
9825unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009826 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009827 return I != StaticLocalNumbers.end() ? I->second : 1;
9828}
9829
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009830MangleNumberingContext &
9831ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009832 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009833 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009834 if (!MCtx)
9835 MCtx = createMangleNumberingContext();
9836 return *MCtx;
9837}
9838
Justin Lebar20ebffc2016-10-10 16:26:19 +00009839std::unique_ptr<MangleNumberingContext>
9840ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009841 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009842}
9843
David Majnemere7a818f2015-03-06 18:53:55 +00009844const CXXConstructorDecl *
9845ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9846 return ABI->getCopyConstructorForExceptionObject(
9847 cast<CXXRecordDecl>(RD->getFirstDecl()));
9848}
9849
9850void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9851 CXXConstructorDecl *CD) {
9852 return ABI->addCopyConstructorForExceptionObject(
9853 cast<CXXRecordDecl>(RD->getFirstDecl()),
9854 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9855}
9856
David Majnemer00350522015-08-31 18:48:39 +00009857void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9858 TypedefNameDecl *DD) {
9859 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9860}
9861
9862TypedefNameDecl *
9863ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9864 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9865}
9866
9867void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9868 DeclaratorDecl *DD) {
9869 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9870}
9871
9872DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9873 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9874}
9875
Ted Kremenek540017e2011-10-06 05:00:56 +00009876void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9877 ParamIndices[D] = index;
9878}
9879
9880unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9881 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9882 assert(I != ParamIndices.end() &&
9883 "ParmIndices lacks entry set by ParmVarDecl");
9884 return I->second;
9885}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009886
Richard Smithe6c01442013-06-05 00:46:14 +00009887APValue *
9888ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9889 bool MayCreate) {
9890 assert(E && E->getStorageDuration() == SD_Static &&
9891 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009892 if (MayCreate) {
9893 APValue *&MTVI = MaterializedTemporaryValues[E];
9894 if (!MTVI)
9895 MTVI = new (*this) APValue;
9896 return MTVI;
9897 }
Richard Smithe6c01442013-06-05 00:46:14 +00009898
David Majnemer2dcef9e2015-08-13 23:50:15 +00009899 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009900}
9901
Fariborz Jahanian615de762013-05-28 17:37:39 +00009902bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9903 const llvm::Triple &T = getTargetInfo().getTriple();
9904 if (!T.isOSDarwin())
9905 return false;
9906
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009907 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9908 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9909 return false;
9910
Fariborz Jahanian615de762013-05-28 17:37:39 +00009911 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9912 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9913 uint64_t Size = sizeChars.getQuantity();
9914 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9915 unsigned Align = alignChars.getQuantity();
9916 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9917 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9918}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009919
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009920static ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009921 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009922 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009923 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009924 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009925 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009926 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009927}
9928
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009929namespace {
9930
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009931/// Template specializations to abstract away from pointers and TypeLocs.
9932/// @{
9933template <typename T>
9934ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9935 return ast_type_traits::DynTypedNode::create(*Node);
9936}
9937template <>
9938ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9939 return ast_type_traits::DynTypedNode::create(Node);
9940}
9941template <>
9942ast_type_traits::DynTypedNode
9943createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9944 return ast_type_traits::DynTypedNode::create(Node);
9945}
9946/// @}
9947
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009948 /// A \c RecursiveASTVisitor that builds a map from nodes to their
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009949 /// parents as defined by the \c RecursiveASTVisitor.
9950 ///
9951 /// Note that the relationship described here is purely in terms of AST
9952 /// traversal - there are other relationships (for example declaration context)
9953 /// in the AST that are better modeled by special matchers.
9954 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009955 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009956 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009957 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009958 /// Builds and returns the translation unit's parent map.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009959 ///
9960 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009961 static std::pair<ASTContext::ParentMapPointers *,
9962 ASTContext::ParentMapOtherNodes *>
9963 buildMap(TranslationUnitDecl &TU) {
9964 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9965 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009966 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009967 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009968 }
9969
9970 private:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009971 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9972
9973 using VisitorBase = RecursiveASTVisitor<ParentMapASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009974
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009975 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9976 ASTContext::ParentMapOtherNodes *OtherParents)
9977 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009978
9979 bool shouldVisitTemplateInstantiations() const {
9980 return true;
9981 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009982
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009983 bool shouldVisitImplicitCode() const {
9984 return true;
9985 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009986
Richard Smith85838722015-11-24 03:09:01 +00009987 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9988 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009989 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009990 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009991 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009992 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009993 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009994 // FIXME: Currently we add the same parent multiple times, but only
9995 // when no memoization data is available for the type.
9996 // For example when we visit all subexpressions of template
9997 // instantiations; this is suboptimal, but benign: the only way to
9998 // visit those is with hasAncestor / hasParent, and those do not create
9999 // new matches.
10000 // The plan is to enable DynTypedNode to be storable in a map or hash
10001 // map. The main problem there is to implement hash functions /
10002 // comparison operators for all types that DynTypedNode supports that
10003 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010004 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +000010005 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010006 if (const auto *D = ParentStack.back().get<Decl>())
10007 NodeOrVector = D;
10008 else if (const auto *S = ParentStack.back().get<Stmt>())
10009 NodeOrVector = S;
10010 else
10011 NodeOrVector =
10012 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010013 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010014 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
10015 auto *Vector = new ASTContext::ParentVector(
10016 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Gabor Horvath10a837a2017-04-19 15:11:10 +000010017 delete NodeOrVector
10018 .template dyn_cast<ast_type_traits::DynTypedNode *>();
Benjamin Kramer422b3ff2015-10-23 13:24:18 +000010019 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +000010020 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +000010021
10022 auto *Vector =
10023 NodeOrVector.template get<ASTContext::ParentVector *>();
10024 // Skip duplicates for types that have memoization data.
10025 // We must check that the type has memoization data before calling
10026 // std::find() because DynTypedNode::operator== can't compare all
10027 // types.
10028 bool Found = ParentStack.back().getMemoizationData() &&
10029 std::find(Vector->begin(), Vector->end(),
10030 ParentStack.back()) != Vector->end();
10031 if (!Found)
10032 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010033 }
10034 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010035 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +000010036 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010037 ParentStack.pop_back();
10038 return Result;
10039 }
10040
10041 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +000010042 return TraverseNode(DeclNode, DeclNode,
10043 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010044 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010045 }
10046
10047 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +000010048 return TraverseNode(StmtNode, StmtNode,
10049 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010050 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010051 }
10052
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010053 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +000010054 return TraverseNode(
10055 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10056 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10057 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010058 }
10059
10060 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10061 return TraverseNode(
10062 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +000010063 [&] {
10064 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
10065 },
10066 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010067 }
10068
10069 ASTContext::ParentMapPointers *Parents;
10070 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010071 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010072 };
10073
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010074} // namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010075
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010076template <typename NodeTy, typename MapTy>
10077static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
10078 const MapTy &Map) {
10079 auto I = Map.find(Node);
10080 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010081 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010082 }
Eugene Zelenko7855e772018-04-03 00:11:50 +000010083 if (const auto *V =
10084 I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010085 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +000010086 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010087 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010088}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010089
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010090ASTContext::DynTypedNodeList
10091ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
10092 if (!PointerParents) {
10093 // We always need to run over the whole translation unit, as
10094 // hasAncestor can escape any subtree.
10095 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
10096 PointerParents.reset(Maps.first);
10097 OtherParents.reset(Maps.second);
10098 }
10099 if (Node.getNodeKind().hasPointerIdentity())
10100 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
10101 return getDynNodeFromMap(Node, *OtherParents);
10102}
10103
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010104bool
10105ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10106 const ObjCMethodDecl *MethodImpl) {
10107 // No point trying to match an unavailable/deprecated mothod.
10108 if (MethodDecl->hasAttr<UnavailableAttr>()
10109 || MethodDecl->hasAttr<DeprecatedAttr>())
10110 return false;
10111 if (MethodDecl->getObjCDeclQualifier() !=
10112 MethodImpl->getObjCDeclQualifier())
10113 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010114 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010115 return false;
10116
10117 if (MethodDecl->param_size() != MethodImpl->param_size())
10118 return false;
10119
10120 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10121 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10122 EF = MethodDecl->param_end();
10123 IM != EM && IF != EF; ++IM, ++IF) {
10124 const ParmVarDecl *DeclVar = (*IF);
10125 const ParmVarDecl *ImplVar = (*IM);
10126 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10127 return false;
10128 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10129 return false;
10130 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010131
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010132 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010133}
Richard Smith053f6c62014-05-16 23:01:30 +000010134
Yaxun Liu402804b2016-12-15 08:09:08 +000010135uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010136 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010137 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010138 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010139 else
10140 AS = QT->getPointeeType().getAddressSpace();
10141
10142 return getTargetInfo().getNullPointerValue(AS);
10143}
10144
Alexander Richardson6d989432017-10-15 18:48:14 +000010145unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10146 if (isTargetAddressSpace(AS))
10147 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010148 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010149 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010150}
10151
Leonard Chanab80f3c2018-06-14 14:53:51 +000010152QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10153 assert(Ty->isFixedPointType());
10154
10155 if (Ty->isSaturatedFixedPointType()) return Ty;
10156
10157 const auto &BT = Ty->getAs<BuiltinType>();
10158 switch (BT->getKind()) {
10159 default:
10160 llvm_unreachable("Not a fixed point type!");
10161 case BuiltinType::ShortAccum:
10162 return SatShortAccumTy;
10163 case BuiltinType::Accum:
10164 return SatAccumTy;
10165 case BuiltinType::LongAccum:
10166 return SatLongAccumTy;
10167 case BuiltinType::UShortAccum:
10168 return SatUnsignedShortAccumTy;
10169 case BuiltinType::UAccum:
10170 return SatUnsignedAccumTy;
10171 case BuiltinType::ULongAccum:
10172 return SatUnsignedLongAccumTy;
10173 case BuiltinType::ShortFract:
10174 return SatShortFractTy;
10175 case BuiltinType::Fract:
10176 return SatFractTy;
10177 case BuiltinType::LongFract:
10178 return SatLongFractTy;
10179 case BuiltinType::UShortFract:
10180 return SatUnsignedShortFractTy;
10181 case BuiltinType::UFract:
10182 return SatUnsignedFractTy;
10183 case BuiltinType::ULongFract:
10184 return SatUnsignedLongFractTy;
10185 }
10186}
10187
Richard Smith053f6c62014-05-16 23:01:30 +000010188// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10189// doesn't include ASTContext.h
10190template
10191clang::LazyGenerationalUpdatePtr<
10192 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10193clang::LazyGenerationalUpdatePtr<
10194 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10195 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010196
10197unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10198 assert(Ty->isFixedPointType());
10199
10200 const auto *BT = Ty->getAs<BuiltinType>();
10201 const TargetInfo &Target = getTargetInfo();
10202 switch (BT->getKind()) {
10203 default:
10204 llvm_unreachable("Not a fixed point type!");
10205 case BuiltinType::ShortAccum:
10206 case BuiltinType::SatShortAccum:
10207 return Target.getShortAccumScale();
10208 case BuiltinType::Accum:
10209 case BuiltinType::SatAccum:
10210 return Target.getAccumScale();
10211 case BuiltinType::LongAccum:
10212 case BuiltinType::SatLongAccum:
10213 return Target.getLongAccumScale();
10214 case BuiltinType::UShortAccum:
10215 case BuiltinType::SatUShortAccum:
10216 return Target.getUnsignedShortAccumScale();
10217 case BuiltinType::UAccum:
10218 case BuiltinType::SatUAccum:
10219 return Target.getUnsignedAccumScale();
10220 case BuiltinType::ULongAccum:
10221 case BuiltinType::SatULongAccum:
10222 return Target.getUnsignedLongAccumScale();
10223 case BuiltinType::ShortFract:
10224 case BuiltinType::SatShortFract:
10225 return Target.getShortFractScale();
10226 case BuiltinType::Fract:
10227 case BuiltinType::SatFract:
10228 return Target.getFractScale();
10229 case BuiltinType::LongFract:
10230 case BuiltinType::SatLongFract:
10231 return Target.getLongFractScale();
10232 case BuiltinType::UShortFract:
10233 case BuiltinType::SatUShortFract:
10234 return Target.getUnsignedShortFractScale();
10235 case BuiltinType::UFract:
10236 case BuiltinType::SatUFract:
10237 return Target.getUnsignedFractScale();
10238 case BuiltinType::ULongFract:
10239 case BuiltinType::SatULongFract:
10240 return Target.getUnsignedLongFractScale();
10241 }
10242}
10243
10244unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10245 assert(Ty->isFixedPointType());
10246
10247 const auto *BT = Ty->getAs<BuiltinType>();
10248 const TargetInfo &Target = getTargetInfo();
10249 switch (BT->getKind()) {
10250 default:
10251 llvm_unreachable("Not a fixed point type!");
10252 case BuiltinType::ShortAccum:
10253 case BuiltinType::SatShortAccum:
10254 return Target.getShortAccumIBits();
10255 case BuiltinType::Accum:
10256 case BuiltinType::SatAccum:
10257 return Target.getAccumIBits();
10258 case BuiltinType::LongAccum:
10259 case BuiltinType::SatLongAccum:
10260 return Target.getLongAccumIBits();
10261 case BuiltinType::UShortAccum:
10262 case BuiltinType::SatUShortAccum:
10263 return Target.getUnsignedShortAccumIBits();
10264 case BuiltinType::UAccum:
10265 case BuiltinType::SatUAccum:
10266 return Target.getUnsignedAccumIBits();
10267 case BuiltinType::ULongAccum:
10268 case BuiltinType::SatULongAccum:
10269 return Target.getUnsignedLongAccumIBits();
10270 case BuiltinType::ShortFract:
10271 case BuiltinType::SatShortFract:
10272 case BuiltinType::Fract:
10273 case BuiltinType::SatFract:
10274 case BuiltinType::LongFract:
10275 case BuiltinType::SatLongFract:
10276 case BuiltinType::UShortFract:
10277 case BuiltinType::SatUShortFract:
10278 case BuiltinType::UFract:
10279 case BuiltinType::SatUFract:
10280 case BuiltinType::ULongFract:
10281 case BuiltinType::SatULongFract:
10282 return 0;
10283 }
10284}