Bug Summary

File:tools/clang/lib/Sema/TreeTransform.h
Warning:line 4641, column 22
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplate.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn373517/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn373517=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-02-234743-9763-1 -x c++ /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp

1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
12#include "clang/AST/ASTConsumer.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/DeclFriend.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/RecursiveASTVisitor.h"
19#include "clang/AST/TypeVisitor.h"
20#include "clang/Basic/Builtins.h"
21#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "clang/Basic/Stack.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/ParsedTemplate.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
32#include "llvm/ADT/SmallBitVector.h"
33#include "llvm/ADT/SmallString.h"
34#include "llvm/ADT/StringExtras.h"
35
36#include <iterator>
37using namespace clang;
38using namespace sema;
39
40// Exported for use by Parser.
41SourceRange
42clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
43 unsigned N) {
44 if (!N) return SourceRange();
45 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
46}
47
48namespace clang {
49/// [temp.constr.decl]p2: A template's associated constraints are
50/// defined as a single constraint-expression derived from the introduced
51/// constraint-expressions [ ... ].
52///
53/// \param Params The template parameter list and optional requires-clause.
54///
55/// \param FD The underlying templated function declaration for a function
56/// template.
57static Expr *formAssociatedConstraints(TemplateParameterList *Params,
58 FunctionDecl *FD);
59}
60
61static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
62 FunctionDecl *FD) {
63 // FIXME: Concepts: collect additional introduced constraint-expressions
64 assert(!FD && "Cannot collect constraints from function declaration yet.")((!FD && "Cannot collect constraints from function declaration yet."
) ? static_cast<void> (0) : __assert_fail ("!FD && \"Cannot collect constraints from function declaration yet.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 64, __PRETTY_FUNCTION__))
;
65 return Params->getRequiresClause();
66}
67
68/// Determine whether the declaration found is acceptable as the name
69/// of a template and, if so, return that template declaration. Otherwise,
70/// returns null.
71///
72/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
73/// is true. In all other cases it will return a TemplateDecl (or null).
74NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
75 bool AllowFunctionTemplates,
76 bool AllowDependent) {
77 D = D->getUnderlyingDecl();
78
79 if (isa<TemplateDecl>(D)) {
80 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
81 return nullptr;
82
83 return D;
84 }
85
86 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
87 // C++ [temp.local]p1:
88 // Like normal (non-template) classes, class templates have an
89 // injected-class-name (Clause 9). The injected-class-name
90 // can be used with or without a template-argument-list. When
91 // it is used without a template-argument-list, it is
92 // equivalent to the injected-class-name followed by the
93 // template-parameters of the class template enclosed in
94 // <>. When it is used with a template-argument-list, it
95 // refers to the specified class template specialization,
96 // which could be the current specialization or another
97 // specialization.
98 if (Record->isInjectedClassName()) {
99 Record = cast<CXXRecordDecl>(Record->getDeclContext());
100 if (Record->getDescribedClassTemplate())
101 return Record->getDescribedClassTemplate();
102
103 if (ClassTemplateSpecializationDecl *Spec
104 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
105 return Spec->getSpecializedTemplate();
106 }
107
108 return nullptr;
109 }
110
111 // 'using Dependent::foo;' can resolve to a template name.
112 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
113 // injected-class-name).
114 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
115 return D;
116
117 return nullptr;
118}
119
120void Sema::FilterAcceptableTemplateNames(LookupResult &R,
121 bool AllowFunctionTemplates,
122 bool AllowDependent) {
123 LookupResult::Filter filter = R.makeFilter();
124 while (filter.hasNext()) {
125 NamedDecl *Orig = filter.next();
126 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
127 filter.erase();
128 }
129 filter.done();
130}
131
132bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
133 bool AllowFunctionTemplates,
134 bool AllowDependent,
135 bool AllowNonTemplateFunctions) {
136 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
137 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
138 return true;
139 if (AllowNonTemplateFunctions &&
140 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
141 return true;
142 }
143
144 return false;
145}
146
147TemplateNameKind Sema::isTemplateName(Scope *S,
148 CXXScopeSpec &SS,
149 bool hasTemplateKeyword,
150 const UnqualifiedId &Name,
151 ParsedType ObjectTypePtr,
152 bool EnteringContext,
153 TemplateTy &TemplateResult,
154 bool &MemberOfUnknownSpecialization) {
155 assert(getLangOpts().CPlusPlus && "No template names in C!")((getLangOpts().CPlusPlus && "No template names in C!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No template names in C!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 155, __PRETTY_FUNCTION__))
;
156
157 DeclarationName TName;
158 MemberOfUnknownSpecialization = false;
159
160 switch (Name.getKind()) {
161 case UnqualifiedIdKind::IK_Identifier:
162 TName = DeclarationName(Name.Identifier);
163 break;
164
165 case UnqualifiedIdKind::IK_OperatorFunctionId:
166 TName = Context.DeclarationNames.getCXXOperatorName(
167 Name.OperatorFunctionId.Operator);
168 break;
169
170 case UnqualifiedIdKind::IK_LiteralOperatorId:
171 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
172 break;
173
174 default:
175 return TNK_Non_template;
176 }
177
178 QualType ObjectType = ObjectTypePtr.get();
179
180 AssumedTemplateKind AssumedTemplate;
181 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
182 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
183 MemberOfUnknownSpecialization, SourceLocation(),
184 &AssumedTemplate))
185 return TNK_Non_template;
186
187 if (AssumedTemplate != AssumedTemplateKind::None) {
188 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
189 // Let the parser know whether we found nothing or found functions; if we
190 // found nothing, we want to more carefully check whether this is actually
191 // a function template name versus some other kind of undeclared identifier.
192 return AssumedTemplate == AssumedTemplateKind::FoundNothing
193 ? TNK_Undeclared_template
194 : TNK_Function_template;
195 }
196
197 if (R.empty())
198 return TNK_Non_template;
199
200 NamedDecl *D = nullptr;
201 if (R.isAmbiguous()) {
202 // If we got an ambiguity involving a non-function template, treat this
203 // as a template name, and pick an arbitrary template for error recovery.
204 bool AnyFunctionTemplates = false;
205 for (NamedDecl *FoundD : R) {
206 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
207 if (isa<FunctionTemplateDecl>(FoundTemplate))
208 AnyFunctionTemplates = true;
209 else {
210 D = FoundTemplate;
211 break;
212 }
213 }
214 }
215
216 // If we didn't find any templates at all, this isn't a template name.
217 // Leave the ambiguity for a later lookup to diagnose.
218 if (!D && !AnyFunctionTemplates) {
219 R.suppressDiagnostics();
220 return TNK_Non_template;
221 }
222
223 // If the only templates were function templates, filter out the rest.
224 // We'll diagnose the ambiguity later.
225 if (!D)
226 FilterAcceptableTemplateNames(R);
227 }
228
229 // At this point, we have either picked a single template name declaration D
230 // or we have a non-empty set of results R containing either one template name
231 // declaration or a set of function templates.
232
233 TemplateName Template;
234 TemplateNameKind TemplateKind;
235
236 unsigned ResultCount = R.end() - R.begin();
237 if (!D && ResultCount > 1) {
238 // We assume that we'll preserve the qualifier from a function
239 // template name in other ways.
240 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
241 TemplateKind = TNK_Function_template;
242
243 // We'll do this lookup again later.
244 R.suppressDiagnostics();
245 } else {
246 if (!D) {
247 D = getAsTemplateNameDecl(*R.begin());
248 assert(D && "unambiguous result is not a template name")((D && "unambiguous result is not a template name") ?
static_cast<void> (0) : __assert_fail ("D && \"unambiguous result is not a template name\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 248, __PRETTY_FUNCTION__))
;
249 }
250
251 if (isa<UnresolvedUsingValueDecl>(D)) {
252 // We don't yet know whether this is a template-name or not.
253 MemberOfUnknownSpecialization = true;
254 return TNK_Non_template;
255 }
256
257 TemplateDecl *TD = cast<TemplateDecl>(D);
258
259 if (SS.isSet() && !SS.isInvalid()) {
260 NestedNameSpecifier *Qualifier = SS.getScopeRep();
261 Template = Context.getQualifiedTemplateName(Qualifier,
262 hasTemplateKeyword, TD);
263 } else {
264 Template = TemplateName(TD);
265 }
266
267 if (isa<FunctionTemplateDecl>(TD)) {
268 TemplateKind = TNK_Function_template;
269
270 // We'll do this lookup again later.
271 R.suppressDiagnostics();
272 } else {
273 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||((isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl
>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl
>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl
>(TD)) ? static_cast<void> (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 275, __PRETTY_FUNCTION__))
274 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||((isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl
>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl
>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl
>(TD)) ? static_cast<void> (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 275, __PRETTY_FUNCTION__))
275 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD))((isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl
>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl
>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl
>(TD)) ? static_cast<void> (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 275, __PRETTY_FUNCTION__))
;
276 TemplateKind =
277 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
278 isa<ConceptDecl>(TD) ? TNK_Concept_template :
279 TNK_Type_template;
280 }
281 }
282
283 TemplateResult = TemplateTy::make(Template);
284 return TemplateKind;
285}
286
287bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
288 SourceLocation NameLoc,
289 ParsedTemplateTy *Template) {
290 CXXScopeSpec SS;
291 bool MemberOfUnknownSpecialization = false;
292
293 // We could use redeclaration lookup here, but we don't need to: the
294 // syntactic form of a deduction guide is enough to identify it even
295 // if we can't look up the template name at all.
296 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
297 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
298 /*EnteringContext*/ false,
299 MemberOfUnknownSpecialization))
300 return false;
301
302 if (R.empty()) return false;
303 if (R.isAmbiguous()) {
304 // FIXME: Diagnose an ambiguity if we find at least one template.
305 R.suppressDiagnostics();
306 return false;
307 }
308
309 // We only treat template-names that name type templates as valid deduction
310 // guide names.
311 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
312 if (!TD || !getAsTypeTemplateDecl(TD))
313 return false;
314
315 if (Template)
316 *Template = TemplateTy::make(TemplateName(TD));
317 return true;
318}
319
320bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
321 SourceLocation IILoc,
322 Scope *S,
323 const CXXScopeSpec *SS,
324 TemplateTy &SuggestedTemplate,
325 TemplateNameKind &SuggestedKind) {
326 // We can't recover unless there's a dependent scope specifier preceding the
327 // template name.
328 // FIXME: Typo correction?
329 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
330 computeDeclContext(*SS))
331 return false;
332
333 // The code is missing a 'template' keyword prior to the dependent template
334 // name.
335 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
336 Diag(IILoc, diag::err_template_kw_missing)
337 << Qualifier << II.getName()
338 << FixItHint::CreateInsertion(IILoc, "template ");
339 SuggestedTemplate
340 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
341 SuggestedKind = TNK_Dependent_template_name;
342 return true;
343}
344
345bool Sema::LookupTemplateName(LookupResult &Found,
346 Scope *S, CXXScopeSpec &SS,
347 QualType ObjectType,
348 bool EnteringContext,
349 bool &MemberOfUnknownSpecialization,
350 SourceLocation TemplateKWLoc,
351 AssumedTemplateKind *ATK) {
352 if (ATK)
353 *ATK = AssumedTemplateKind::None;
354
355 Found.setTemplateNameLookup(true);
356
357 // Determine where to perform name lookup
358 MemberOfUnknownSpecialization = false;
359 DeclContext *LookupCtx = nullptr;
360 bool IsDependent = false;
361 if (!ObjectType.isNull()) {
362 // This nested-name-specifier occurs in a member access expression, e.g.,
363 // x->B::f, and we are looking into the type of the object.
364 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist")((!SS.isSet() && "ObjectType and scope specifier cannot coexist"
) ? static_cast<void> (0) : __assert_fail ("!SS.isSet() && \"ObjectType and scope specifier cannot coexist\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 364, __PRETTY_FUNCTION__))
;
365 LookupCtx = computeDeclContext(ObjectType);
366 IsDependent = !LookupCtx && ObjectType->isDependentType();
367 assert((IsDependent || !ObjectType->isIncompleteType() ||(((IsDependent || !ObjectType->isIncompleteType() || ObjectType
->castAs<TagType>()->isBeingDefined()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 369, __PRETTY_FUNCTION__))
368 ObjectType->castAs<TagType>()->isBeingDefined()) &&(((IsDependent || !ObjectType->isIncompleteType() || ObjectType
->castAs<TagType>()->isBeingDefined()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 369, __PRETTY_FUNCTION__))
369 "Caller should have completed object type")(((IsDependent || !ObjectType->isIncompleteType() || ObjectType
->castAs<TagType>()->isBeingDefined()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 369, __PRETTY_FUNCTION__))
;
370
371 // Template names cannot appear inside an Objective-C class or object type
372 // or a vector type.
373 //
374 // FIXME: This is wrong. For example:
375 //
376 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
377 // Vec<int> vi;
378 // vi.Vec<int>::~Vec<int>();
379 //
380 // ... should be accepted but we will not treat 'Vec' as a template name
381 // here. The right thing to do would be to check if the name is a valid
382 // vector component name, and look up a template name if not. And similarly
383 // for lookups into Objective-C class and object types, where the same
384 // problem can arise.
385 if (ObjectType->isObjCObjectOrInterfaceType() ||
386 ObjectType->isVectorType()) {
387 Found.clear();
388 return false;
389 }
390 } else if (SS.isSet()) {
391 // This nested-name-specifier occurs after another nested-name-specifier,
392 // so long into the context associated with the prior nested-name-specifier.
393 LookupCtx = computeDeclContext(SS, EnteringContext);
394 IsDependent = !LookupCtx;
395
396 // The declaration context must be complete.
397 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
398 return true;
399 }
400
401 bool ObjectTypeSearchedInScope = false;
402 bool AllowFunctionTemplatesInLookup = true;
403 if (LookupCtx) {
404 // Perform "qualified" name lookup into the declaration context we
405 // computed, which is either the type of the base of a member access
406 // expression or the declaration context associated with a prior
407 // nested-name-specifier.
408 LookupQualifiedName(Found, LookupCtx);
409
410 // FIXME: The C++ standard does not clearly specify what happens in the
411 // case where the object type is dependent, and implementations vary. In
412 // Clang, we treat a name after a . or -> as a template-name if lookup
413 // finds a non-dependent member or member of the current instantiation that
414 // is a type template, or finds no such members and lookup in the context
415 // of the postfix-expression finds a type template. In the latter case, the
416 // name is nonetheless dependent, and we may resolve it to a member of an
417 // unknown specialization when we come to instantiate the template.
418 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
419 }
420
421 if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
422 // C++ [basic.lookup.classref]p1:
423 // In a class member access expression (5.2.5), if the . or -> token is
424 // immediately followed by an identifier followed by a <, the
425 // identifier must be looked up to determine whether the < is the
426 // beginning of a template argument list (14.2) or a less-than operator.
427 // The identifier is first looked up in the class of the object
428 // expression. If the identifier is not found, it is then looked up in
429 // the context of the entire postfix-expression and shall name a class
430 // template.
431 if (S)
432 LookupName(Found, S);
433
434 if (!ObjectType.isNull()) {
435 // FIXME: We should filter out all non-type templates here, particularly
436 // variable templates and concepts. But the exclusion of alias templates
437 // and template template parameters is a wording defect.
438 AllowFunctionTemplatesInLookup = false;
439 ObjectTypeSearchedInScope = true;
440 }
441
442 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
443 }
444
445 if (Found.isAmbiguous())
446 return false;
447
448 if (ATK && !SS.isSet() && ObjectType.isNull() && TemplateKWLoc.isInvalid()) {
449 // C++2a [temp.names]p2:
450 // A name is also considered to refer to a template if it is an
451 // unqualified-id followed by a < and name lookup finds either one or more
452 // functions or finds nothing.
453 //
454 // To keep our behavior consistent, we apply the "finds nothing" part in
455 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
456 // successfully form a call to an undeclared template-id.
457 bool AllFunctions =
458 getLangOpts().CPlusPlus2a &&
459 std::all_of(Found.begin(), Found.end(), [](NamedDecl *ND) {
460 return isa<FunctionDecl>(ND->getUnderlyingDecl());
461 });
462 if (AllFunctions || (Found.empty() && !IsDependent)) {
463 // If lookup found any functions, or if this is a name that can only be
464 // used for a function, then strongly assume this is a function
465 // template-id.
466 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
467 ? AssumedTemplateKind::FoundNothing
468 : AssumedTemplateKind::FoundFunctions;
469 Found.clear();
470 return false;
471 }
472 }
473
474 if (Found.empty() && !IsDependent) {
475 // If we did not find any names, attempt to correct any typos.
476 DeclarationName Name = Found.getLookupName();
477 Found.clear();
478 // Simple filter callback that, for keywords, only accepts the C++ *_cast
479 DefaultFilterCCC FilterCCC{};
480 FilterCCC.WantTypeSpecifiers = false;
481 FilterCCC.WantExpressionKeywords = false;
482 FilterCCC.WantRemainingKeywords = false;
483 FilterCCC.WantCXXNamedCasts = true;
484 if (TypoCorrection Corrected =
485 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
486 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
487 if (auto *ND = Corrected.getFoundDecl())
488 Found.addDecl(ND);
489 FilterAcceptableTemplateNames(Found);
490 if (Found.isAmbiguous()) {
491 Found.clear();
492 } else if (!Found.empty()) {
493 Found.setLookupName(Corrected.getCorrection());
494 if (LookupCtx) {
495 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
496 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
497 Name.getAsString() == CorrectedStr;
498 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
499 << Name << LookupCtx << DroppedSpecifier
500 << SS.getRange());
501 } else {
502 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
503 }
504 }
505 }
506 }
507
508 NamedDecl *ExampleLookupResult =
509 Found.empty() ? nullptr : Found.getRepresentativeDecl();
510 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
511 if (Found.empty()) {
512 if (IsDependent) {
513 MemberOfUnknownSpecialization = true;
514 return false;
515 }
516
517 // If a 'template' keyword was used, a lookup that finds only non-template
518 // names is an error.
519 if (ExampleLookupResult && TemplateKWLoc.isValid()) {
520 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
521 << Found.getLookupName() << SS.getRange();
522 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
523 diag::note_template_kw_refers_to_non_template)
524 << Found.getLookupName();
525 return true;
526 }
527
528 return false;
529 }
530
531 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
532 !getLangOpts().CPlusPlus11) {
533 // C++03 [basic.lookup.classref]p1:
534 // [...] If the lookup in the class of the object expression finds a
535 // template, the name is also looked up in the context of the entire
536 // postfix-expression and [...]
537 //
538 // Note: C++11 does not perform this second lookup.
539 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
540 LookupOrdinaryName);
541 FoundOuter.setTemplateNameLookup(true);
542 LookupName(FoundOuter, S);
543 // FIXME: We silently accept an ambiguous lookup here, in violation of
544 // [basic.lookup]/1.
545 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
546
547 NamedDecl *OuterTemplate;
548 if (FoundOuter.empty()) {
549 // - if the name is not found, the name found in the class of the
550 // object expression is used, otherwise
551 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
552 !(OuterTemplate =
553 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
554 // - if the name is found in the context of the entire
555 // postfix-expression and does not name a class template, the name
556 // found in the class of the object expression is used, otherwise
557 FoundOuter.clear();
558 } else if (!Found.isSuppressingDiagnostics()) {
559 // - if the name found is a class template, it must refer to the same
560 // entity as the one found in the class of the object expression,
561 // otherwise the program is ill-formed.
562 if (!Found.isSingleResult() ||
563 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
564 OuterTemplate->getCanonicalDecl()) {
565 Diag(Found.getNameLoc(),
566 diag::ext_nested_name_member_ref_lookup_ambiguous)
567 << Found.getLookupName()
568 << ObjectType;
569 Diag(Found.getRepresentativeDecl()->getLocation(),
570 diag::note_ambig_member_ref_object_type)
571 << ObjectType;
572 Diag(FoundOuter.getFoundDecl()->getLocation(),
573 diag::note_ambig_member_ref_scope);
574
575 // Recover by taking the template that we found in the object
576 // expression's type.
577 }
578 }
579 }
580
581 return false;
582}
583
584void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
585 SourceLocation Less,
586 SourceLocation Greater) {
587 if (TemplateName.isInvalid())
588 return;
589
590 DeclarationNameInfo NameInfo;
591 CXXScopeSpec SS;
592 LookupNameKind LookupKind;
593
594 DeclContext *LookupCtx = nullptr;
595 NamedDecl *Found = nullptr;
596 bool MissingTemplateKeyword = false;
597
598 // Figure out what name we looked up.
599 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
600 NameInfo = DRE->getNameInfo();
601 SS.Adopt(DRE->getQualifierLoc());
602 LookupKind = LookupOrdinaryName;
603 Found = DRE->getFoundDecl();
604 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
605 NameInfo = ME->getMemberNameInfo();
606 SS.Adopt(ME->getQualifierLoc());
607 LookupKind = LookupMemberName;
608 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
609 Found = ME->getMemberDecl();
610 } else if (auto *DSDRE =
611 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
612 NameInfo = DSDRE->getNameInfo();
613 SS.Adopt(DSDRE->getQualifierLoc());
614 MissingTemplateKeyword = true;
615 } else if (auto *DSME =
616 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
617 NameInfo = DSME->getMemberNameInfo();
618 SS.Adopt(DSME->getQualifierLoc());
619 MissingTemplateKeyword = true;
620 } else {
621 llvm_unreachable("unexpected kind of potential template name")::llvm::llvm_unreachable_internal("unexpected kind of potential template name"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 621)
;
622 }
623
624 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
625 // was missing.
626 if (MissingTemplateKeyword) {
627 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
628 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
629 return;
630 }
631
632 // Try to correct the name by looking for templates and C++ named casts.
633 struct TemplateCandidateFilter : CorrectionCandidateCallback {
634 Sema &S;
635 TemplateCandidateFilter(Sema &S) : S(S) {
636 WantTypeSpecifiers = false;
637 WantExpressionKeywords = false;
638 WantRemainingKeywords = false;
639 WantCXXNamedCasts = true;
640 };
641 bool ValidateCandidate(const TypoCorrection &Candidate) override {
642 if (auto *ND = Candidate.getCorrectionDecl())
643 return S.getAsTemplateNameDecl(ND);
644 return Candidate.isKeyword();
645 }
646
647 std::unique_ptr<CorrectionCandidateCallback> clone() override {
648 return std::make_unique<TemplateCandidateFilter>(*this);
649 }
650 };
651
652 DeclarationName Name = NameInfo.getName();
653 TemplateCandidateFilter CCC(*this);
654 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
655 CTK_ErrorRecovery, LookupCtx)) {
656 auto *ND = Corrected.getFoundDecl();
657 if (ND)
658 ND = getAsTemplateNameDecl(ND);
659 if (ND || Corrected.isKeyword()) {
660 if (LookupCtx) {
661 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
662 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
663 Name.getAsString() == CorrectedStr;
664 diagnoseTypo(Corrected,
665 PDiag(diag::err_non_template_in_member_template_id_suggest)
666 << Name << LookupCtx << DroppedSpecifier
667 << SS.getRange(), false);
668 } else {
669 diagnoseTypo(Corrected,
670 PDiag(diag::err_non_template_in_template_id_suggest)
671 << Name, false);
672 }
673 if (Found)
674 Diag(Found->getLocation(),
675 diag::note_non_template_in_template_id_found);
676 return;
677 }
678 }
679
680 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
681 << Name << SourceRange(Less, Greater);
682 if (Found)
683 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
684}
685
686/// ActOnDependentIdExpression - Handle a dependent id-expression that
687/// was just parsed. This is only possible with an explicit scope
688/// specifier naming a dependent type.
689ExprResult
690Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
691 SourceLocation TemplateKWLoc,
692 const DeclarationNameInfo &NameInfo,
693 bool isAddressOfOperand,
694 const TemplateArgumentListInfo *TemplateArgs) {
695 DeclContext *DC = getFunctionLevelDeclContext();
696
697 // C++11 [expr.prim.general]p12:
698 // An id-expression that denotes a non-static data member or non-static
699 // member function of a class can only be used:
700 // (...)
701 // - if that id-expression denotes a non-static data member and it
702 // appears in an unevaluated operand.
703 //
704 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
705 // CXXDependentScopeMemberExpr. The former can instantiate to either
706 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
707 // always a MemberExpr.
708 bool MightBeCxx11UnevalField =
709 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
710
711 // Check if the nested name specifier is an enum type.
712 bool IsEnum = false;
713 if (NestedNameSpecifier *NNS = SS.getScopeRep())
714 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
715
716 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
717 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
718 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
719
720 // Since the 'this' expression is synthesized, we don't need to
721 // perform the double-lookup check.
722 NamedDecl *FirstQualifierInScope = nullptr;
723
724 return CXXDependentScopeMemberExpr::Create(
725 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
726 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
727 FirstQualifierInScope, NameInfo, TemplateArgs);
728 }
729
730 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
731}
732
733ExprResult
734Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
735 SourceLocation TemplateKWLoc,
736 const DeclarationNameInfo &NameInfo,
737 const TemplateArgumentListInfo *TemplateArgs) {
738 // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
739 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
740 if (!QualifierLoc)
741 return ExprError();
742
743 return DependentScopeDeclRefExpr::Create(
744 Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
745}
746
747
748/// Determine whether we would be unable to instantiate this template (because
749/// it either has no definition, or is in the process of being instantiated).
750bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
751 NamedDecl *Instantiation,
752 bool InstantiatedFromMember,
753 const NamedDecl *Pattern,
754 const NamedDecl *PatternDef,
755 TemplateSpecializationKind TSK,
756 bool Complain /*= true*/) {
757 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||((isa<TagDecl>(Instantiation) || isa<FunctionDecl>
(Instantiation) || isa<VarDecl>(Instantiation)) ? static_cast
<void> (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 758, __PRETTY_FUNCTION__))
758 isa<VarDecl>(Instantiation))((isa<TagDecl>(Instantiation) || isa<FunctionDecl>
(Instantiation) || isa<VarDecl>(Instantiation)) ? static_cast
<void> (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 758, __PRETTY_FUNCTION__))
;
759
760 bool IsEntityBeingDefined = false;
761 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
762 IsEntityBeingDefined = TD->isBeingDefined();
763
764 if (PatternDef && !IsEntityBeingDefined) {
765 NamedDecl *SuggestedDef = nullptr;
766 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
767 /*OnlyNeedComplete*/false)) {
768 // If we're allowed to diagnose this and recover, do so.
769 bool Recover = Complain && !isSFINAEContext();
770 if (Complain)
771 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
772 Sema::MissingImportKind::Definition, Recover);
773 return !Recover;
774 }
775 return false;
776 }
777
778 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
779 return true;
780
781 llvm::Optional<unsigned> Note;
782 QualType InstantiationTy;
783 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
784 InstantiationTy = Context.getTypeDeclType(TD);
785 if (PatternDef) {
786 Diag(PointOfInstantiation,
787 diag::err_template_instantiate_within_definition)
788 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
789 << InstantiationTy;
790 // Not much point in noting the template declaration here, since
791 // we're lexically inside it.
792 Instantiation->setInvalidDecl();
793 } else if (InstantiatedFromMember) {
794 if (isa<FunctionDecl>(Instantiation)) {
795 Diag(PointOfInstantiation,
796 diag::err_explicit_instantiation_undefined_member)
797 << /*member function*/ 1 << Instantiation->getDeclName()
798 << Instantiation->getDeclContext();
799 Note = diag::note_explicit_instantiation_here;
800 } else {
801 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!")((isa<TagDecl>(Instantiation) && "Must be a TagDecl!"
) ? static_cast<void> (0) : __assert_fail ("isa<TagDecl>(Instantiation) && \"Must be a TagDecl!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 801, __PRETTY_FUNCTION__))
;
802 Diag(PointOfInstantiation,
803 diag::err_implicit_instantiate_member_undefined)
804 << InstantiationTy;
805 Note = diag::note_member_declared_at;
806 }
807 } else {
808 if (isa<FunctionDecl>(Instantiation)) {
809 Diag(PointOfInstantiation,
810 diag::err_explicit_instantiation_undefined_func_template)
811 << Pattern;
812 Note = diag::note_explicit_instantiation_here;
813 } else if (isa<TagDecl>(Instantiation)) {
814 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
815 << (TSK != TSK_ImplicitInstantiation)
816 << InstantiationTy;
817 Note = diag::note_template_decl_here;
818 } else {
819 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!")((isa<VarDecl>(Instantiation) && "Must be a VarDecl!"
) ? static_cast<void> (0) : __assert_fail ("isa<VarDecl>(Instantiation) && \"Must be a VarDecl!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 819, __PRETTY_FUNCTION__))
;
820 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
821 Diag(PointOfInstantiation,
822 diag::err_explicit_instantiation_undefined_var_template)
823 << Instantiation;
824 Instantiation->setInvalidDecl();
825 } else
826 Diag(PointOfInstantiation,
827 diag::err_explicit_instantiation_undefined_member)
828 << /*static data member*/ 2 << Instantiation->getDeclName()
829 << Instantiation->getDeclContext();
830 Note = diag::note_explicit_instantiation_here;
831 }
832 }
833 if (Note) // Diagnostics were emitted.
834 Diag(Pattern->getLocation(), Note.getValue());
835
836 // In general, Instantiation isn't marked invalid to get more than one
837 // error for multiple undefined instantiations. But the code that does
838 // explicit declaration -> explicit definition conversion can't handle
839 // invalid declarations, so mark as invalid in that case.
840 if (TSK == TSK_ExplicitInstantiationDeclaration)
841 Instantiation->setInvalidDecl();
842 return true;
843}
844
845/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
846/// that the template parameter 'PrevDecl' is being shadowed by a new
847/// declaration at location Loc. Returns true to indicate that this is
848/// an error, and false otherwise.
849void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
850 assert(PrevDecl->isTemplateParameter() && "Not a template parameter")((PrevDecl->isTemplateParameter() && "Not a template parameter"
) ? static_cast<void> (0) : __assert_fail ("PrevDecl->isTemplateParameter() && \"Not a template parameter\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 850, __PRETTY_FUNCTION__))
;
851
852 // C++ [temp.local]p4:
853 // A template-parameter shall not be redeclared within its
854 // scope (including nested scopes).
855 //
856 // Make this a warning when MSVC compatibility is requested.
857 unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
858 : diag::err_template_param_shadow;
859 Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName();
860 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
861}
862
863/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
864/// the parameter D to reference the templated declaration and return a pointer
865/// to the template declaration. Otherwise, do nothing to D and return null.
866TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
867 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
868 D = Temp->getTemplatedDecl();
869 return Temp;
870 }
871 return nullptr;
872}
873
874ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
875 SourceLocation EllipsisLoc) const {
876 assert(Kind == Template &&((Kind == Template && "Only template template arguments can be pack expansions here"
) ? static_cast<void> (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 877, __PRETTY_FUNCTION__))
877 "Only template template arguments can be pack expansions here")((Kind == Template && "Only template template arguments can be pack expansions here"
) ? static_cast<void> (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 877, __PRETTY_FUNCTION__))
;
878 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&((getAsTemplate().get().containsUnexpandedParameterPack() &&
"Template template argument pack expansion without packs") ?
static_cast<void> (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 879, __PRETTY_FUNCTION__))
879 "Template template argument pack expansion without packs")((getAsTemplate().get().containsUnexpandedParameterPack() &&
"Template template argument pack expansion without packs") ?
static_cast<void> (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 879, __PRETTY_FUNCTION__))
;
880 ParsedTemplateArgument Result(*this);
881 Result.EllipsisLoc = EllipsisLoc;
882 return Result;
883}
884
885static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
886 const ParsedTemplateArgument &Arg) {
887
888 switch (Arg.getKind()) {
889 case ParsedTemplateArgument::Type: {
890 TypeSourceInfo *DI;
891 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
892 if (!DI)
893 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
894 return TemplateArgumentLoc(TemplateArgument(T), DI);
895 }
896
897 case ParsedTemplateArgument::NonType: {
898 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
899 return TemplateArgumentLoc(TemplateArgument(E), E);
900 }
901
902 case ParsedTemplateArgument::Template: {
903 TemplateName Template = Arg.getAsTemplate().get();
904 TemplateArgument TArg;
905 if (Arg.getEllipsisLoc().isValid())
906 TArg = TemplateArgument(Template, Optional<unsigned int>());
907 else
908 TArg = Template;
909 return TemplateArgumentLoc(TArg,
910 Arg.getScopeSpec().getWithLocInContext(
911 SemaRef.Context),
912 Arg.getLocation(),
913 Arg.getEllipsisLoc());
914 }
915 }
916
917 llvm_unreachable("Unhandled parsed template argument")::llvm::llvm_unreachable_internal("Unhandled parsed template argument"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 917)
;
918}
919
920/// Translates template arguments as provided by the parser
921/// into template arguments used by semantic analysis.
922void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
923 TemplateArgumentListInfo &TemplateArgs) {
924 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
925 TemplateArgs.addArgument(translateTemplateArgument(*this,
926 TemplateArgsIn[I]));
927}
928
929static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
930 SourceLocation Loc,
931 IdentifierInfo *Name) {
932 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
933 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
934 if (PrevDecl && PrevDecl->isTemplateParameter())
935 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
936}
937
938/// Convert a parsed type into a parsed template argument. This is mostly
939/// trivial, except that we may have parsed a C++17 deduced class template
940/// specialization type, in which case we should form a template template
941/// argument instead of a type template argument.
942ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
943 TypeSourceInfo *TInfo;
944 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
945 if (T.isNull())
946 return ParsedTemplateArgument();
947 assert(TInfo && "template argument with no location")((TInfo && "template argument with no location") ? static_cast
<void> (0) : __assert_fail ("TInfo && \"template argument with no location\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 947, __PRETTY_FUNCTION__))
;
948
949 // If we might have formed a deduced template specialization type, convert
950 // it to a template template argument.
951 if (getLangOpts().CPlusPlus17) {
952 TypeLoc TL = TInfo->getTypeLoc();
953 SourceLocation EllipsisLoc;
954 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
955 EllipsisLoc = PET.getEllipsisLoc();
956 TL = PET.getPatternLoc();
957 }
958
959 CXXScopeSpec SS;
960 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
961 SS.Adopt(ET.getQualifierLoc());
962 TL = ET.getNamedTypeLoc();
963 }
964
965 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
966 TemplateName Name = DTST.getTypePtr()->getTemplateName();
967 if (SS.isSet())
968 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
969 /*HasTemplateKeyword*/ false,
970 Name.getAsTemplateDecl());
971 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
972 DTST.getTemplateNameLoc());
973 if (EllipsisLoc.isValid())
974 Result = Result.getTemplatePackExpansion(EllipsisLoc);
975 return Result;
976 }
977 }
978
979 // This is a normal type template argument. Note, if the type template
980 // argument is an injected-class-name for a template, it has a dual nature
981 // and can be used as either a type or a template. We handle that in
982 // convertTypeTemplateArgumentToTemplate.
983 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
984 ParsedType.get().getAsOpaquePtr(),
985 TInfo->getTypeLoc().getBeginLoc());
986}
987
988/// ActOnTypeParameter - Called when a C++ template type parameter
989/// (e.g., "typename T") has been parsed. Typename specifies whether
990/// the keyword "typename" was used to declare the type parameter
991/// (otherwise, "class" was used), and KeyLoc is the location of the
992/// "class" or "typename" keyword. ParamName is the name of the
993/// parameter (NULL indicates an unnamed template parameter) and
994/// ParamNameLoc is the location of the parameter name (if any).
995/// If the type parameter has a default argument, it will be added
996/// later via ActOnTypeParameterDefault.
997NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
998 SourceLocation EllipsisLoc,
999 SourceLocation KeyLoc,
1000 IdentifierInfo *ParamName,
1001 SourceLocation ParamNameLoc,
1002 unsigned Depth, unsigned Position,
1003 SourceLocation EqualLoc,
1004 ParsedType DefaultArg) {
1005 assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "Template type parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1006, __PRETTY_FUNCTION__))
1006 "Template type parameter not in template parameter scope!")((S->isTemplateParamScope() && "Template type parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1006, __PRETTY_FUNCTION__))
;
1007
1008 bool IsParameterPack = EllipsisLoc.isValid();
1009 TemplateTypeParmDecl *Param = TemplateTypeParmDecl::Create(
1010 Context, Context.getTranslationUnitDecl(), KeyLoc, ParamNameLoc, Depth,
1011 Position, ParamName, Typename, IsParameterPack);
1012 Param->setAccess(AS_public);
1013
1014 if (Param->isParameterPack())
1015 if (auto *LSI = getEnclosingLambda())
1016 LSI->LocalPacks.push_back(Param);
1017
1018 if (ParamName) {
1019 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1020
1021 // Add the template parameter into the current scope.
1022 S->AddDecl(Param);
1023 IdResolver.AddDecl(Param);
1024 }
1025
1026 // C++0x [temp.param]p9:
1027 // A default template-argument may be specified for any kind of
1028 // template-parameter that is not a template parameter pack.
1029 if (DefaultArg && IsParameterPack) {
1030 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1031 DefaultArg = nullptr;
1032 }
1033
1034 // Handle the default argument, if provided.
1035 if (DefaultArg) {
1036 TypeSourceInfo *DefaultTInfo;
1037 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1038
1039 assert(DefaultTInfo && "expected source information for type")((DefaultTInfo && "expected source information for type"
) ? static_cast<void> (0) : __assert_fail ("DefaultTInfo && \"expected source information for type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1039, __PRETTY_FUNCTION__))
;
1040
1041 // Check for unexpanded parameter packs.
1042 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1043 UPPC_DefaultArgument))
1044 return Param;
1045
1046 // Check the template argument itself.
1047 if (CheckTemplateArgument(Param, DefaultTInfo)) {
1048 Param->setInvalidDecl();
1049 return Param;
1050 }
1051
1052 Param->setDefaultArgument(DefaultTInfo);
1053 }
1054
1055 return Param;
1056}
1057
1058/// Check that the type of a non-type template parameter is
1059/// well-formed.
1060///
1061/// \returns the (possibly-promoted) parameter type if valid;
1062/// otherwise, produces a diagnostic and returns a NULL type.
1063QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1064 SourceLocation Loc) {
1065 if (TSI->getType()->isUndeducedType()) {
1066 // C++17 [temp.dep.expr]p3:
1067 // An id-expression is type-dependent if it contains
1068 // - an identifier associated by name lookup with a non-type
1069 // template-parameter declared with a type that contains a
1070 // placeholder type (7.1.7.4),
1071 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
1072 }
1073
1074 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1075}
1076
1077QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1078 SourceLocation Loc) {
1079 // We don't allow variably-modified types as the type of non-type template
1080 // parameters.
1081 if (T->isVariablyModifiedType()) {
1082 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1083 << T;
1084 return QualType();
1085 }
1086
1087 // C++ [temp.param]p4:
1088 //
1089 // A non-type template-parameter shall have one of the following
1090 // (optionally cv-qualified) types:
1091 //
1092 // -- integral or enumeration type,
1093 if (T->isIntegralOrEnumerationType() ||
1094 // -- pointer to object or pointer to function,
1095 T->isPointerType() ||
1096 // -- reference to object or reference to function,
1097 T->isReferenceType() ||
1098 // -- pointer to member,
1099 T->isMemberPointerType() ||
1100 // -- std::nullptr_t.
1101 T->isNullPtrType() ||
1102 // If T is a dependent type, we can't do the check now, so we
1103 // assume that it is well-formed.
1104 T->isDependentType() ||
1105 // Allow use of auto in template parameter declarations.
1106 T->isUndeducedType()) {
1107 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1108 // are ignored when determining its type.
1109 return T.getUnqualifiedType();
1110 }
1111
1112 // C++ [temp.param]p8:
1113 //
1114 // A non-type template-parameter of type "array of T" or
1115 // "function returning T" is adjusted to be of type "pointer to
1116 // T" or "pointer to function returning T", respectively.
1117 else if (T->isArrayType() || T->isFunctionType())
1118 return Context.getDecayedType(T);
1119
1120 Diag(Loc, diag::err_template_nontype_parm_bad_type)
1121 << T;
1122
1123 return QualType();
1124}
1125
1126NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1127 unsigned Depth,
1128 unsigned Position,
1129 SourceLocation EqualLoc,
1130 Expr *Default) {
1131 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
1132
1133 // Check that we have valid decl-specifiers specified.
1134 auto CheckValidDeclSpecifiers = [this, &D] {
1135 // C++ [temp.param]
1136 // p1
1137 // template-parameter:
1138 // ...
1139 // parameter-declaration
1140 // p2
1141 // ... A storage class shall not be specified in a template-parameter
1142 // declaration.
1143 // [dcl.typedef]p1:
1144 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1145 // of a parameter-declaration
1146 const DeclSpec &DS = D.getDeclSpec();
1147 auto EmitDiag = [this](SourceLocation Loc) {
1148 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1149 << FixItHint::CreateRemoval(Loc);
1150 };
1151 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1152 EmitDiag(DS.getStorageClassSpecLoc());
1153
1154 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1155 EmitDiag(DS.getThreadStorageClassSpecLoc());
1156
1157 // [dcl.inline]p1:
1158 // The inline specifier can be applied only to the declaration or
1159 // definition of a variable or function.
1160
1161 if (DS.isInlineSpecified())
1162 EmitDiag(DS.getInlineSpecLoc());
1163
1164 // [dcl.constexpr]p1:
1165 // The constexpr specifier shall be applied only to the definition of a
1166 // variable or variable template or the declaration of a function or
1167 // function template.
1168
1169 if (DS.hasConstexprSpecifier())
1170 EmitDiag(DS.getConstexprSpecLoc());
1171
1172 // [dcl.fct.spec]p1:
1173 // Function-specifiers can be used only in function declarations.
1174
1175 if (DS.isVirtualSpecified())
1176 EmitDiag(DS.getVirtualSpecLoc());
1177
1178 if (DS.hasExplicitSpecifier())
1179 EmitDiag(DS.getExplicitSpecLoc());
1180
1181 if (DS.isNoreturnSpecified())
1182 EmitDiag(DS.getNoreturnSpecLoc());
1183 };
1184
1185 CheckValidDeclSpecifiers();
1186
1187 if (TInfo->getType()->isUndeducedType()) {
1188 Diag(D.getIdentifierLoc(),
1189 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1190 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1191 }
1192
1193 assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "Non-type template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1194, __PRETTY_FUNCTION__))
1194 "Non-type template parameter not in template parameter scope!")((S->isTemplateParamScope() && "Non-type template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1194, __PRETTY_FUNCTION__))
;
1195 bool Invalid = false;
1196
1197 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1198 if (T.isNull()) {
1199 T = Context.IntTy; // Recover with an 'int' type.
1200 Invalid = true;
1201 }
1202
1203 CheckFunctionOrTemplateParamDeclarator(S, D);
1204
1205 IdentifierInfo *ParamName = D.getIdentifier();
1206 bool IsParameterPack = D.hasEllipsis();
1207 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1208 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1209 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1210 TInfo);
1211 Param->setAccess(AS_public);
1212
1213 if (Invalid)
1214 Param->setInvalidDecl();
1215
1216 if (Param->isParameterPack())
1217 if (auto *LSI = getEnclosingLambda())
1218 LSI->LocalPacks.push_back(Param);
1219
1220 if (ParamName) {
1221 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1222 ParamName);
1223
1224 // Add the template parameter into the current scope.
1225 S->AddDecl(Param);
1226 IdResolver.AddDecl(Param);
1227 }
1228
1229 // C++0x [temp.param]p9:
1230 // A default template-argument may be specified for any kind of
1231 // template-parameter that is not a template parameter pack.
1232 if (Default && IsParameterPack) {
1233 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1234 Default = nullptr;
1235 }
1236
1237 // Check the well-formedness of the default template argument, if provided.
1238 if (Default) {
1239 // Check for unexpanded parameter packs.
1240 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1241 return Param;
1242
1243 TemplateArgument Converted;
1244 ExprResult DefaultRes =
1245 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
1246 if (DefaultRes.isInvalid()) {
1247 Param->setInvalidDecl();
1248 return Param;
1249 }
1250 Default = DefaultRes.get();
1251
1252 Param->setDefaultArgument(Default);
1253 }
1254
1255 return Param;
1256}
1257
1258/// ActOnTemplateTemplateParameter - Called when a C++ template template
1259/// parameter (e.g. T in template <template \<typename> class T> class array)
1260/// has been parsed. S is the current scope.
1261NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1262 SourceLocation TmpLoc,
1263 TemplateParameterList *Params,
1264 SourceLocation EllipsisLoc,
1265 IdentifierInfo *Name,
1266 SourceLocation NameLoc,
1267 unsigned Depth,
1268 unsigned Position,
1269 SourceLocation EqualLoc,
1270 ParsedTemplateArgument Default) {
1271 assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "Template template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1272, __PRETTY_FUNCTION__))
1272 "Template template parameter not in template parameter scope!")((S->isTemplateParamScope() && "Template template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1272, __PRETTY_FUNCTION__))
;
1273
1274 // Construct the parameter object.
1275 bool IsParameterPack = EllipsisLoc.isValid();
1276 TemplateTemplateParmDecl *Param =
1277 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1278 NameLoc.isInvalid()? TmpLoc : NameLoc,
1279 Depth, Position, IsParameterPack,
1280 Name, Params);
1281 Param->setAccess(AS_public);
1282
1283 if (Param->isParameterPack())
1284 if (auto *LSI = getEnclosingLambda())
1285 LSI->LocalPacks.push_back(Param);
1286
1287 // If the template template parameter has a name, then link the identifier
1288 // into the scope and lookup mechanisms.
1289 if (Name) {
1290 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1291
1292 S->AddDecl(Param);
1293 IdResolver.AddDecl(Param);
1294 }
1295
1296 if (Params->size() == 0) {
1297 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1298 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1299 Param->setInvalidDecl();
1300 }
1301
1302 // C++0x [temp.param]p9:
1303 // A default template-argument may be specified for any kind of
1304 // template-parameter that is not a template parameter pack.
1305 if (IsParameterPack && !Default.isInvalid()) {
1306 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1307 Default = ParsedTemplateArgument();
1308 }
1309
1310 if (!Default.isInvalid()) {
1311 // Check only that we have a template template argument. We don't want to
1312 // try to check well-formedness now, because our template template parameter
1313 // might have dependent types in its template parameters, which we wouldn't
1314 // be able to match now.
1315 //
1316 // If none of the template template parameter's template arguments mention
1317 // other template parameters, we could actually perform more checking here.
1318 // However, it isn't worth doing.
1319 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1320 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1321 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1322 << DefaultArg.getSourceRange();
1323 return Param;
1324 }
1325
1326 // Check for unexpanded parameter packs.
1327 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1328 DefaultArg.getArgument().getAsTemplate(),
1329 UPPC_DefaultArgument))
1330 return Param;
1331
1332 Param->setDefaultArgument(Context, DefaultArg);
1333 }
1334
1335 return Param;
1336}
1337
1338/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1339/// constrained by RequiresClause, that contains the template parameters in
1340/// Params.
1341TemplateParameterList *
1342Sema::ActOnTemplateParameterList(unsigned Depth,
1343 SourceLocation ExportLoc,
1344 SourceLocation TemplateLoc,
1345 SourceLocation LAngleLoc,
1346 ArrayRef<NamedDecl *> Params,
1347 SourceLocation RAngleLoc,
1348 Expr *RequiresClause) {
1349 if (ExportLoc.isValid())
1350 Diag(ExportLoc, diag::warn_template_export_unsupported);
1351
1352 return TemplateParameterList::Create(
1353 Context, TemplateLoc, LAngleLoc,
1354 llvm::makeArrayRef(Params.data(), Params.size()),
1355 RAngleLoc, RequiresClause);
1356}
1357
1358static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1359 const CXXScopeSpec &SS) {
1360 if (SS.isSet())
1361 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1362}
1363
1364DeclResult Sema::CheckClassTemplate(
1365 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1366 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1367 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1368 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1369 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1370 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1371 assert(TemplateParams && TemplateParams->size() > 0 &&((TemplateParams && TemplateParams->size() > 0 &&
"No template parameters") ? static_cast<void> (0) : __assert_fail
("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1372, __PRETTY_FUNCTION__))
1372 "No template parameters")((TemplateParams && TemplateParams->size() > 0 &&
"No template parameters") ? static_cast<void> (0) : __assert_fail
("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1372, __PRETTY_FUNCTION__))
;
1373 assert(TUK != TUK_Reference && "Can only declare or define class templates")((TUK != TUK_Reference && "Can only declare or define class templates"
) ? static_cast<void> (0) : __assert_fail ("TUK != TUK_Reference && \"Can only declare or define class templates\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1373, __PRETTY_FUNCTION__))
;
1374 bool Invalid = false;
1375
1376 // Check that we can declare a template here.
1377 if (CheckTemplateDeclScope(S, TemplateParams))
1378 return true;
1379
1380 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1381 assert(Kind != TTK_Enum && "can't build template of enumerated type")((Kind != TTK_Enum && "can't build template of enumerated type"
) ? static_cast<void> (0) : __assert_fail ("Kind != TTK_Enum && \"can't build template of enumerated type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1381, __PRETTY_FUNCTION__))
;
1382
1383 // There is no such thing as an unnamed class template.
1384 if (!Name) {
1385 Diag(KWLoc, diag::err_template_unnamed_class);
1386 return true;
1387 }
1388
1389 // Find any previous declaration with this name. For a friend with no
1390 // scope explicitly specified, we only look for tag declarations (per
1391 // C++11 [basic.lookup.elab]p2).
1392 DeclContext *SemanticContext;
1393 LookupResult Previous(*this, Name, NameLoc,
1394 (SS.isEmpty() && TUK == TUK_Friend)
1395 ? LookupTagName : LookupOrdinaryName,
1396 forRedeclarationInCurContext());
1397 if (SS.isNotEmpty() && !SS.isInvalid()) {
1398 SemanticContext = computeDeclContext(SS, true);
1399 if (!SemanticContext) {
1400 // FIXME: Horrible, horrible hack! We can't currently represent this
1401 // in the AST, and historically we have just ignored such friend
1402 // class templates, so don't complain here.
1403 Diag(NameLoc, TUK == TUK_Friend
1404 ? diag::warn_template_qualified_friend_ignored
1405 : diag::err_template_qualified_declarator_no_match)
1406 << SS.getScopeRep() << SS.getRange();
1407 return TUK != TUK_Friend;
1408 }
1409
1410 if (RequireCompleteDeclContext(SS, SemanticContext))
1411 return true;
1412
1413 // If we're adding a template to a dependent context, we may need to
1414 // rebuilding some of the types used within the template parameter list,
1415 // now that we know what the current instantiation is.
1416 if (SemanticContext->isDependentContext()) {
1417 ContextRAII SavedContext(*this, SemanticContext);
1418 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1419 Invalid = true;
1420 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1421 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1422
1423 LookupQualifiedName(Previous, SemanticContext);
1424 } else {
1425 SemanticContext = CurContext;
1426
1427 // C++14 [class.mem]p14:
1428 // If T is the name of a class, then each of the following shall have a
1429 // name different from T:
1430 // -- every member template of class T
1431 if (TUK != TUK_Friend &&
1432 DiagnoseClassNameShadow(SemanticContext,
1433 DeclarationNameInfo(Name, NameLoc)))
1434 return true;
1435
1436 LookupName(Previous, S);
1437 }
1438
1439 if (Previous.isAmbiguous())
1440 return true;
1441
1442 NamedDecl *PrevDecl = nullptr;
1443 if (Previous.begin() != Previous.end())
1444 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1445
1446 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1447 // Maybe we will complain about the shadowed template parameter.
1448 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1449 // Just pretend that we didn't see the previous declaration.
1450 PrevDecl = nullptr;
1451 }
1452
1453 // If there is a previous declaration with the same name, check
1454 // whether this is a valid redeclaration.
1455 ClassTemplateDecl *PrevClassTemplate =
1456 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1457
1458 // We may have found the injected-class-name of a class template,
1459 // class template partial specialization, or class template specialization.
1460 // In these cases, grab the template that is being defined or specialized.
1461 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1462 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1463 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1464 PrevClassTemplate
1465 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1466 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1467 PrevClassTemplate
1468 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1469 ->getSpecializedTemplate();
1470 }
1471 }
1472
1473 if (TUK == TUK_Friend) {
1474 // C++ [namespace.memdef]p3:
1475 // [...] When looking for a prior declaration of a class or a function
1476 // declared as a friend, and when the name of the friend class or
1477 // function is neither a qualified name nor a template-id, scopes outside
1478 // the innermost enclosing namespace scope are not considered.
1479 if (!SS.isSet()) {
1480 DeclContext *OutermostContext = CurContext;
1481 while (!OutermostContext->isFileContext())
1482 OutermostContext = OutermostContext->getLookupParent();
1483
1484 if (PrevDecl &&
1485 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1486 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1487 SemanticContext = PrevDecl->getDeclContext();
1488 } else {
1489 // Declarations in outer scopes don't matter. However, the outermost
1490 // context we computed is the semantic context for our new
1491 // declaration.
1492 PrevDecl = PrevClassTemplate = nullptr;
1493 SemanticContext = OutermostContext;
1494
1495 // Check that the chosen semantic context doesn't already contain a
1496 // declaration of this name as a non-tag type.
1497 Previous.clear(LookupOrdinaryName);
1498 DeclContext *LookupContext = SemanticContext;
1499 while (LookupContext->isTransparentContext())
1500 LookupContext = LookupContext->getLookupParent();
1501 LookupQualifiedName(Previous, LookupContext);
1502
1503 if (Previous.isAmbiguous())
1504 return true;
1505
1506 if (Previous.begin() != Previous.end())
1507 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1508 }
1509 }
1510 } else if (PrevDecl &&
1511 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1512 S, SS.isValid()))
1513 PrevDecl = PrevClassTemplate = nullptr;
1514
1515 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1516 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1517 if (SS.isEmpty() &&
1518 !(PrevClassTemplate &&
1519 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1520 SemanticContext->getRedeclContext()))) {
1521 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1522 Diag(Shadow->getTargetDecl()->getLocation(),
1523 diag::note_using_decl_target);
1524 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1525 // Recover by ignoring the old declaration.
1526 PrevDecl = PrevClassTemplate = nullptr;
1527 }
1528 }
1529
1530 // TODO Memory management; associated constraints are not always stored.
1531 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1532
1533 if (PrevClassTemplate) {
1534 // Ensure that the template parameter lists are compatible. Skip this check
1535 // for a friend in a dependent context: the template parameter list itself
1536 // could be dependent.
1537 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1538 !TemplateParameterListsAreEqual(TemplateParams,
1539 PrevClassTemplate->getTemplateParameters(),
1540 /*Complain=*/true,
1541 TPL_TemplateMatch))
1542 return true;
1543
1544 // Check for matching associated constraints on redeclarations.
1545 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1546 const bool RedeclACMismatch = [&] {
1547 if (!(CurAC || PrevAC))
1548 return false; // Nothing to check; no mismatch.
1549 if (CurAC && PrevAC) {
1550 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1551 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1552 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1553 if (CurACInfo == PrevACInfo)
1554 return false; // All good; no mismatch.
1555 }
1556 return true;
1557 }();
1558
1559 if (RedeclACMismatch) {
1560 Diag(CurAC ? CurAC->getBeginLoc() : NameLoc,
1561 diag::err_template_different_associated_constraints);
1562 Diag(PrevAC ? PrevAC->getBeginLoc() : PrevClassTemplate->getLocation(),
1563 diag::note_template_prev_declaration)
1564 << /*declaration*/ 0;
1565 return true;
1566 }
1567
1568 // C++ [temp.class]p4:
1569 // In a redeclaration, partial specialization, explicit
1570 // specialization or explicit instantiation of a class template,
1571 // the class-key shall agree in kind with the original class
1572 // template declaration (7.1.5.3).
1573 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1574 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1575 TUK == TUK_Definition, KWLoc, Name)) {
1576 Diag(KWLoc, diag::err_use_with_wrong_tag)
1577 << Name
1578 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1579 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1580 Kind = PrevRecordDecl->getTagKind();
1581 }
1582
1583 // Check for redefinition of this class template.
1584 if (TUK == TUK_Definition) {
1585 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1586 // If we have a prior definition that is not visible, treat this as
1587 // simply making that previous definition visible.
1588 NamedDecl *Hidden = nullptr;
1589 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1590 SkipBody->ShouldSkip = true;
1591 SkipBody->Previous = Def;
1592 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1593 assert(Tmpl && "original definition of a class template is not a "((Tmpl && "original definition of a class template is not a "
"class template?") ? static_cast<void> (0) : __assert_fail
("Tmpl && \"original definition of a class template is not a \" \"class template?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1594, __PRETTY_FUNCTION__))
1594 "class template?")((Tmpl && "original definition of a class template is not a "
"class template?") ? static_cast<void> (0) : __assert_fail
("Tmpl && \"original definition of a class template is not a \" \"class template?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1594, __PRETTY_FUNCTION__))
;
1595 makeMergedDefinitionVisible(Hidden);
1596 makeMergedDefinitionVisible(Tmpl);
1597 } else {
1598 Diag(NameLoc, diag::err_redefinition) << Name;
1599 Diag(Def->getLocation(), diag::note_previous_definition);
1600 // FIXME: Would it make sense to try to "forget" the previous
1601 // definition, as part of error recovery?
1602 return true;
1603 }
1604 }
1605 }
1606 } else if (PrevDecl) {
1607 // C++ [temp]p5:
1608 // A class template shall not have the same name as any other
1609 // template, class, function, object, enumeration, enumerator,
1610 // namespace, or type in the same scope (3.3), except as specified
1611 // in (14.5.4).
1612 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1613 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1614 return true;
1615 }
1616
1617 // Check the template parameter list of this declaration, possibly
1618 // merging in the template parameter list from the previous class
1619 // template declaration. Skip this check for a friend in a dependent
1620 // context, because the template parameter list might be dependent.
1621 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1622 CheckTemplateParameterList(
1623 TemplateParams,
1624 PrevClassTemplate
1625 ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1626 : nullptr,
1627 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1628 SemanticContext->isDependentContext())
1629 ? TPC_ClassTemplateMember
1630 : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
1631 SkipBody))
1632 Invalid = true;
1633
1634 if (SS.isSet()) {
1635 // If the name of the template was qualified, we must be defining the
1636 // template out-of-line.
1637 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1638 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1639 : diag::err_member_decl_does_not_match)
1640 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1641 Invalid = true;
1642 }
1643 }
1644
1645 // If this is a templated friend in a dependent context we should not put it
1646 // on the redecl chain. In some cases, the templated friend can be the most
1647 // recent declaration tricking the template instantiator to make substitutions
1648 // there.
1649 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1650 bool ShouldAddRedecl
1651 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1652
1653 CXXRecordDecl *NewClass =
1654 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1655 PrevClassTemplate && ShouldAddRedecl ?
1656 PrevClassTemplate->getTemplatedDecl() : nullptr,
1657 /*DelayTypeCreation=*/true);
1658 SetNestedNameSpecifier(*this, NewClass, SS);
1659 if (NumOuterTemplateParamLists > 0)
1660 NewClass->setTemplateParameterListsInfo(
1661 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1662 NumOuterTemplateParamLists));
1663
1664 // Add alignment attributes if necessary; these attributes are checked when
1665 // the ASTContext lays out the structure.
1666 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
1667 AddAlignmentAttributesForRecord(NewClass);
1668 AddMsStructLayoutForRecord(NewClass);
1669 }
1670
1671 // Attach the associated constraints when the declaration will not be part of
1672 // a decl chain.
1673 Expr *const ACtoAttach =
1674 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1675
1676 ClassTemplateDecl *NewTemplate
1677 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1678 DeclarationName(Name), TemplateParams,
1679 NewClass, ACtoAttach);
1680
1681 if (ShouldAddRedecl)
1682 NewTemplate->setPreviousDecl(PrevClassTemplate);
1683
1684 NewClass->setDescribedClassTemplate(NewTemplate);
1685
1686 if (ModulePrivateLoc.isValid())
1687 NewTemplate->setModulePrivate();
1688
1689 // Build the type for the class template declaration now.
1690 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1691 T = Context.getInjectedClassNameType(NewClass, T);
1692 assert(T->isDependentType() && "Class template type is not dependent?")((T->isDependentType() && "Class template type is not dependent?"
) ? static_cast<void> (0) : __assert_fail ("T->isDependentType() && \"Class template type is not dependent?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1692, __PRETTY_FUNCTION__))
;
1693 (void)T;
1694
1695 // If we are providing an explicit specialization of a member that is a
1696 // class template, make a note of that.
1697 if (PrevClassTemplate &&
1698 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1699 PrevClassTemplate->setMemberSpecialization();
1700
1701 // Set the access specifier.
1702 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1703 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1704
1705 // Set the lexical context of these templates
1706 NewClass->setLexicalDeclContext(CurContext);
1707 NewTemplate->setLexicalDeclContext(CurContext);
1708
1709 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
1710 NewClass->startDefinition();
1711
1712 ProcessDeclAttributeList(S, NewClass, Attr);
1713
1714 if (PrevClassTemplate)
1715 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1716
1717 AddPushedVisibilityAttribute(NewClass);
1718 inferGslOwnerPointerAttribute(NewClass);
1719
1720 if (TUK != TUK_Friend) {
1721 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1722 Scope *Outer = S;
1723 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1724 Outer = Outer->getParent();
1725 PushOnScopeChains(NewTemplate, Outer);
1726 } else {
1727 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1728 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1729 NewClass->setAccess(PrevClassTemplate->getAccess());
1730 }
1731
1732 NewTemplate->setObjectOfFriendDecl();
1733
1734 // Friend templates are visible in fairly strange ways.
1735 if (!CurContext->isDependentContext()) {
1736 DeclContext *DC = SemanticContext->getRedeclContext();
1737 DC->makeDeclVisibleInContext(NewTemplate);
1738 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1739 PushOnScopeChains(NewTemplate, EnclosingScope,
1740 /* AddToContext = */ false);
1741 }
1742
1743 FriendDecl *Friend = FriendDecl::Create(
1744 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1745 Friend->setAccess(AS_public);
1746 CurContext->addDecl(Friend);
1747 }
1748
1749 if (PrevClassTemplate)
1750 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1751
1752 if (Invalid) {
1753 NewTemplate->setInvalidDecl();
1754 NewClass->setInvalidDecl();
1755 }
1756
1757 ActOnDocumentableDecl(NewTemplate);
1758
1759 if (SkipBody && SkipBody->ShouldSkip)
1760 return SkipBody->Previous;
1761
1762 return NewTemplate;
1763}
1764
1765namespace {
1766/// Tree transform to "extract" a transformed type from a class template's
1767/// constructor to a deduction guide.
1768class ExtractTypeForDeductionGuide
1769 : public TreeTransform<ExtractTypeForDeductionGuide> {
1770public:
1771 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
1772 ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
1773
1774 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
1775
1776 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
1777 return TransformType(
1
Calling 'TreeTransform::TransformType'
1778 TLB,
1779 TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc());
1780 }
1781};
1782
1783/// Transform to convert portions of a constructor declaration into the
1784/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1785struct ConvertConstructorToDeductionGuideTransform {
1786 ConvertConstructorToDeductionGuideTransform(Sema &S,
1787 ClassTemplateDecl *Template)
1788 : SemaRef(S), Template(Template) {}
1789
1790 Sema &SemaRef;
1791 ClassTemplateDecl *Template;
1792
1793 DeclContext *DC = Template->getDeclContext();
1794 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1795 DeclarationName DeductionGuideName =
1796 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1797
1798 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1799
1800 // Index adjustment to apply to convert depth-1 template parameters into
1801 // depth-0 template parameters.
1802 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1803
1804 /// Transform a constructor declaration into a deduction guide.
1805 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1806 CXXConstructorDecl *CD) {
1807 SmallVector<TemplateArgument, 16> SubstArgs;
1808
1809 LocalInstantiationScope Scope(SemaRef);
1810
1811 // C++ [over.match.class.deduct]p1:
1812 // -- For each constructor of the class template designated by the
1813 // template-name, a function template with the following properties:
1814
1815 // -- The template parameters are the template parameters of the class
1816 // template followed by the template parameters (including default
1817 // template arguments) of the constructor, if any.
1818 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1819 if (FTD) {
1820 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1821 SmallVector<NamedDecl *, 16> AllParams;
1822 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1823 AllParams.insert(AllParams.begin(),
1824 TemplateParams->begin(), TemplateParams->end());
1825 SubstArgs.reserve(InnerParams->size());
1826
1827 // Later template parameters could refer to earlier ones, so build up
1828 // a list of substituted template arguments as we go.
1829 for (NamedDecl *Param : *InnerParams) {
1830 MultiLevelTemplateArgumentList Args;
1831 Args.addOuterTemplateArguments(SubstArgs);
1832 Args.addOuterRetainedLevel();
1833 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1834 if (!NewParam)
1835 return nullptr;
1836 AllParams.push_back(NewParam);
1837 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1838 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1839 }
1840 TemplateParams = TemplateParameterList::Create(
1841 SemaRef.Context, InnerParams->getTemplateLoc(),
1842 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1843 /*FIXME: RequiresClause*/ nullptr);
1844 }
1845
1846 // If we built a new template-parameter-list, track that we need to
1847 // substitute references to the old parameters into references to the
1848 // new ones.
1849 MultiLevelTemplateArgumentList Args;
1850 if (FTD) {
1851 Args.addOuterTemplateArguments(SubstArgs);
1852 Args.addOuterRetainedLevel();
1853 }
1854
1855 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
1856 .getAsAdjusted<FunctionProtoTypeLoc>();
1857 assert(FPTL && "no prototype for constructor declaration")((FPTL && "no prototype for constructor declaration")
? static_cast<void> (0) : __assert_fail ("FPTL && \"no prototype for constructor declaration\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1857, __PRETTY_FUNCTION__))
;
1858
1859 // Transform the type of the function, adjusting the return type and
1860 // replacing references to the old parameters with references to the
1861 // new ones.
1862 TypeLocBuilder TLB;
1863 SmallVector<ParmVarDecl*, 8> Params;
1864 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1865 if (NewType.isNull())
1866 return nullptr;
1867 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1868
1869 return buildDeductionGuide(TemplateParams, CD->getExplicitSpecifier(),
1870 NewTInfo, CD->getBeginLoc(), CD->getLocation(),
1871 CD->getEndLoc());
1872 }
1873
1874 /// Build a deduction guide with the specified parameter types.
1875 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1876 SourceLocation Loc = Template->getLocation();
1877
1878 // Build the requested type.
1879 FunctionProtoType::ExtProtoInfo EPI;
1880 EPI.HasTrailingReturn = true;
1881 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1882 DeductionGuideName, EPI);
1883 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1884
1885 FunctionProtoTypeLoc FPTL =
1886 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1887
1888 // Build the parameters, needed during deduction / substitution.
1889 SmallVector<ParmVarDecl*, 4> Params;
1890 for (auto T : ParamTypes) {
1891 ParmVarDecl *NewParam = ParmVarDecl::Create(
1892 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1893 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1894 NewParam->setScopeInfo(0, Params.size());
1895 FPTL.setParam(Params.size(), NewParam);
1896 Params.push_back(NewParam);
1897 }
1898
1899 return buildDeductionGuide(Template->getTemplateParameters(),
1900 ExplicitSpecifier(), TSI, Loc, Loc, Loc);
1901 }
1902
1903private:
1904 /// Transform a constructor template parameter into a deduction guide template
1905 /// parameter, rebuilding any internal references to earlier parameters and
1906 /// renumbering as we go.
1907 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1908 MultiLevelTemplateArgumentList &Args) {
1909 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1910 // TemplateTypeParmDecl's index cannot be changed after creation, so
1911 // substitute it directly.
1912 auto *NewTTP = TemplateTypeParmDecl::Create(
1913 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
1914 /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
1915 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1916 TTP->isParameterPack());
1917 if (TTP->hasDefaultArgument()) {
1918 TypeSourceInfo *InstantiatedDefaultArg =
1919 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1920 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1921 if (InstantiatedDefaultArg)
1922 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1923 }
1924 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1925 NewTTP);
1926 return NewTTP;
1927 }
1928
1929 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1930 return transformTemplateParameterImpl(TTP, Args);
1931
1932 return transformTemplateParameterImpl(
1933 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1934 }
1935 template<typename TemplateParmDecl>
1936 TemplateParmDecl *
1937 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1938 MultiLevelTemplateArgumentList &Args) {
1939 // Ask the template instantiator to do the heavy lifting for us, then adjust
1940 // the index of the parameter once it's done.
1941 auto *NewParam =
1942 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1943 assert(NewParam->getDepth() == 0 && "unexpected template param depth")((NewParam->getDepth() == 0 && "unexpected template param depth"
) ? static_cast<void> (0) : __assert_fail ("NewParam->getDepth() == 0 && \"unexpected template param depth\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1943, __PRETTY_FUNCTION__))
;
1944 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1945 return NewParam;
1946 }
1947
1948 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1949 FunctionProtoTypeLoc TL,
1950 SmallVectorImpl<ParmVarDecl*> &Params,
1951 MultiLevelTemplateArgumentList &Args) {
1952 SmallVector<QualType, 4> ParamTypes;
1953 const FunctionProtoType *T = TL.getTypePtr();
1954
1955 // -- The types of the function parameters are those of the constructor.
1956 for (auto *OldParam : TL.getParams()) {
1957 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
1958 if (!NewParam)
1959 return QualType();
1960 ParamTypes.push_back(NewParam->getType());
1961 Params.push_back(NewParam);
1962 }
1963
1964 // -- The return type is the class template specialization designated by
1965 // the template-name and template arguments corresponding to the
1966 // template parameters obtained from the class template.
1967 //
1968 // We use the injected-class-name type of the primary template instead.
1969 // This has the convenient property that it is different from any type that
1970 // the user can write in a deduction-guide (because they cannot enter the
1971 // context of the template), so implicit deduction guides can never collide
1972 // with explicit ones.
1973 QualType ReturnType = DeducedType;
1974 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1975
1976 // Resolving a wording defect, we also inherit the variadicness of the
1977 // constructor.
1978 FunctionProtoType::ExtProtoInfo EPI;
1979 EPI.Variadic = T->isVariadic();
1980 EPI.HasTrailingReturn = true;
1981
1982 QualType Result = SemaRef.BuildFunctionType(
1983 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
1984 if (Result.isNull())
1985 return QualType();
1986
1987 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1988 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1989 NewTL.setLParenLoc(TL.getLParenLoc());
1990 NewTL.setRParenLoc(TL.getRParenLoc());
1991 NewTL.setExceptionSpecRange(SourceRange());
1992 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1993 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1994 NewTL.setParam(I, Params[I]);
1995
1996 return Result;
1997 }
1998
1999 ParmVarDecl *
2000 transformFunctionTypeParam(ParmVarDecl *OldParam,
2001 MultiLevelTemplateArgumentList &Args) {
2002 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2003 TypeSourceInfo *NewDI;
2004 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2005 // Expand out the one and only element in each inner pack.
2006 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2007 NewDI =
2008 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2009 OldParam->getLocation(), OldParam->getDeclName());
2010 if (!NewDI) return nullptr;
2011 NewDI =
2012 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2013 PackTL.getTypePtr()->getNumExpansions());
2014 } else
2015 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2016 OldParam->getDeclName());
2017 if (!NewDI)
2018 return nullptr;
2019
2020 // Extract the type. This (for instance) replaces references to typedef
2021 // members of the current instantiations with the definitions of those
2022 // typedefs, avoiding triggering instantiation of the deduced type during
2023 // deduction.
2024 NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
2025
2026 // Resolving a wording defect, we also inherit default arguments from the
2027 // constructor.
2028 ExprResult NewDefArg;
2029 if (OldParam->hasDefaultArg()) {
2030 NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
2031 if (NewDefArg.isInvalid())
2032 return nullptr;
2033 }
2034
2035 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
2036 OldParam->getInnerLocStart(),
2037 OldParam->getLocation(),
2038 OldParam->getIdentifier(),
2039 NewDI->getType(),
2040 NewDI,
2041 OldParam->getStorageClass(),
2042 NewDefArg.get());
2043 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2044 OldParam->getFunctionScopeIndex());
2045 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2046 return NewParam;
2047 }
2048
2049 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
2050 ExplicitSpecifier ES, TypeSourceInfo *TInfo,
2051 SourceLocation LocStart, SourceLocation Loc,
2052 SourceLocation LocEnd) {
2053 DeclarationNameInfo Name(DeductionGuideName, Loc);
2054 ArrayRef<ParmVarDecl *> Params =
2055 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2056
2057 // Build the implicit deduction guide template.
2058 auto *Guide =
2059 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2060 TInfo->getType(), TInfo, LocEnd);
2061 Guide->setImplicit();
2062 Guide->setParams(Params);
2063
2064 for (auto *Param : Params)
2065 Param->setDeclContext(Guide);
2066
2067 auto *GuideTemplate = FunctionTemplateDecl::Create(
2068 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2069 GuideTemplate->setImplicit();
2070 Guide->setDescribedFunctionTemplate(GuideTemplate);
2071
2072 if (isa<CXXRecordDecl>(DC)) {
2073 Guide->setAccess(AS_public);
2074 GuideTemplate->setAccess(AS_public);
2075 }
2076
2077 DC->addDecl(GuideTemplate);
2078 return GuideTemplate;
2079 }
2080};
2081}
2082
2083void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2084 SourceLocation Loc) {
2085 if (CXXRecordDecl *DefRecord =
2086 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2087 TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
2088 Template = DescribedTemplate ? DescribedTemplate : Template;
2089 }
2090
2091 DeclContext *DC = Template->getDeclContext();
2092 if (DC->isDependentContext())
2093 return;
2094
2095 ConvertConstructorToDeductionGuideTransform Transform(
2096 *this, cast<ClassTemplateDecl>(Template));
2097 if (!isCompleteType(Loc, Transform.DeducedType))
2098 return;
2099
2100 // Check whether we've already declared deduction guides for this template.
2101 // FIXME: Consider storing a flag on the template to indicate this.
2102 auto Existing = DC->lookup(Transform.DeductionGuideName);
2103 for (auto *D : Existing)
2104 if (D->isImplicit())
2105 return;
2106
2107 // In case we were expanding a pack when we attempted to declare deduction
2108 // guides, turn off pack expansion for everything we're about to do.
2109 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2110 // Create a template instantiation record to track the "instantiation" of
2111 // constructors into deduction guides.
2112 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2113 // this substitution process actually fail?
2114 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
2115 if (BuildingDeductionGuides.isInvalid())
2116 return;
2117
2118 // Convert declared constructors into deduction guide templates.
2119 // FIXME: Skip constructors for which deduction must necessarily fail (those
2120 // for which some class template parameter without a default argument never
2121 // appears in a deduced context).
2122 bool AddedAny = false;
2123 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2124 D = D->getUnderlyingDecl();
2125 if (D->isInvalidDecl() || D->isImplicit())
2126 continue;
2127 D = cast<NamedDecl>(D->getCanonicalDecl());
2128
2129 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2130 auto *CD =
2131 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
2132 // Class-scope explicit specializations (MS extension) do not result in
2133 // deduction guides.
2134 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
2135 continue;
2136
2137 Transform.transformConstructor(FTD, CD);
2138 AddedAny = true;
2139 }
2140
2141 // C++17 [over.match.class.deduct]
2142 // -- If C is not defined or does not declare any constructors, an
2143 // additional function template derived as above from a hypothetical
2144 // constructor C().
2145 if (!AddedAny)
2146 Transform.buildSimpleDeductionGuide(None);
2147
2148 // -- An additional function template derived as above from a hypothetical
2149 // constructor C(C), called the copy deduction candidate.
2150 cast<CXXDeductionGuideDecl>(
2151 cast<FunctionTemplateDecl>(
2152 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2153 ->getTemplatedDecl())
2154 ->setIsCopyDeductionCandidate();
2155}
2156
2157/// Diagnose the presence of a default template argument on a
2158/// template parameter, which is ill-formed in certain contexts.
2159///
2160/// \returns true if the default template argument should be dropped.
2161static bool DiagnoseDefaultTemplateArgument(Sema &S,
2162 Sema::TemplateParamListContext TPC,
2163 SourceLocation ParamLoc,
2164 SourceRange DefArgRange) {
2165 switch (TPC) {
2166 case Sema::TPC_ClassTemplate:
2167 case Sema::TPC_VarTemplate:
2168 case Sema::TPC_TypeAliasTemplate:
2169 return false;
2170
2171 case Sema::TPC_FunctionTemplate:
2172 case Sema::TPC_FriendFunctionTemplateDefinition:
2173 // C++ [temp.param]p9:
2174 // A default template-argument shall not be specified in a
2175 // function template declaration or a function template
2176 // definition [...]
2177 // If a friend function template declaration specifies a default
2178 // template-argument, that declaration shall be a definition and shall be
2179 // the only declaration of the function template in the translation unit.
2180 // (C++98/03 doesn't have this wording; see DR226).
2181 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2182 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2183 : diag::ext_template_parameter_default_in_function_template)
2184 << DefArgRange;
2185 return false;
2186
2187 case Sema::TPC_ClassTemplateMember:
2188 // C++0x [temp.param]p9:
2189 // A default template-argument shall not be specified in the
2190 // template-parameter-lists of the definition of a member of a
2191 // class template that appears outside of the member's class.
2192 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2193 << DefArgRange;
2194 return true;
2195
2196 case Sema::TPC_FriendClassTemplate:
2197 case Sema::TPC_FriendFunctionTemplate:
2198 // C++ [temp.param]p9:
2199 // A default template-argument shall not be specified in a
2200 // friend template declaration.
2201 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2202 << DefArgRange;
2203 return true;
2204
2205 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2206 // for friend function templates if there is only a single
2207 // declaration (and it is a definition). Strange!
2208 }
2209
2210 llvm_unreachable("Invalid TemplateParamListContext!")::llvm::llvm_unreachable_internal("Invalid TemplateParamListContext!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2210)
;
2211}
2212
2213/// Check for unexpanded parameter packs within the template parameters
2214/// of a template template parameter, recursively.
2215static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2216 TemplateTemplateParmDecl *TTP) {
2217 // A template template parameter which is a parameter pack is also a pack
2218 // expansion.
2219 if (TTP->isParameterPack())
2220 return false;
2221
2222 TemplateParameterList *Params = TTP->getTemplateParameters();
2223 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2224 NamedDecl *P = Params->getParam(I);
2225 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2226 if (!NTTP->isParameterPack() &&
2227 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2228 NTTP->getTypeSourceInfo(),
2229 Sema::UPPC_NonTypeTemplateParameterType))
2230 return true;
2231
2232 continue;
2233 }
2234
2235 if (TemplateTemplateParmDecl *InnerTTP
2236 = dyn_cast<TemplateTemplateParmDecl>(P))
2237 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2238 return true;
2239 }
2240
2241 return false;
2242}
2243
2244/// Checks the validity of a template parameter list, possibly
2245/// considering the template parameter list from a previous
2246/// declaration.
2247///
2248/// If an "old" template parameter list is provided, it must be
2249/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2250/// template parameter list.
2251///
2252/// \param NewParams Template parameter list for a new template
2253/// declaration. This template parameter list will be updated with any
2254/// default arguments that are carried through from the previous
2255/// template parameter list.
2256///
2257/// \param OldParams If provided, template parameter list from a
2258/// previous declaration of the same template. Default template
2259/// arguments will be merged from the old template parameter list to
2260/// the new template parameter list.
2261///
2262/// \param TPC Describes the context in which we are checking the given
2263/// template parameter list.
2264///
2265/// \param SkipBody If we might have already made a prior merged definition
2266/// of this template visible, the corresponding body-skipping information.
2267/// Default argument redefinition is not an error when skipping such a body,
2268/// because (under the ODR) we can assume the default arguments are the same
2269/// as the prior merged definition.
2270///
2271/// \returns true if an error occurred, false otherwise.
2272bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2273 TemplateParameterList *OldParams,
2274 TemplateParamListContext TPC,
2275 SkipBodyInfo *SkipBody) {
2276 bool Invalid = false;
2277
2278 // C++ [temp.param]p10:
2279 // The set of default template-arguments available for use with a
2280 // template declaration or definition is obtained by merging the
2281 // default arguments from the definition (if in scope) and all
2282 // declarations in scope in the same way default function
2283 // arguments are (8.3.6).
2284 bool SawDefaultArgument = false;
2285 SourceLocation PreviousDefaultArgLoc;
2286
2287 // Dummy initialization to avoid warnings.
2288 TemplateParameterList::iterator OldParam = NewParams->end();
2289 if (OldParams)
2290 OldParam = OldParams->begin();
2291
2292 bool RemoveDefaultArguments = false;
2293 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2294 NewParamEnd = NewParams->end();
2295 NewParam != NewParamEnd; ++NewParam) {
2296 // Variables used to diagnose redundant default arguments
2297 bool RedundantDefaultArg = false;
2298 SourceLocation OldDefaultLoc;
2299 SourceLocation NewDefaultLoc;
2300
2301 // Variable used to diagnose missing default arguments
2302 bool MissingDefaultArg = false;
2303
2304 // Variable used to diagnose non-final parameter packs
2305 bool SawParameterPack = false;
2306
2307 if (TemplateTypeParmDecl *NewTypeParm
2308 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2309 // Check the presence of a default argument here.
2310 if (NewTypeParm->hasDefaultArgument() &&
2311 DiagnoseDefaultTemplateArgument(*this, TPC,
2312 NewTypeParm->getLocation(),
2313 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2314 .getSourceRange()))
2315 NewTypeParm->removeDefaultArgument();
2316
2317 // Merge default arguments for template type parameters.
2318 TemplateTypeParmDecl *OldTypeParm
2319 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2320 if (NewTypeParm->isParameterPack()) {
2321 assert(!NewTypeParm->hasDefaultArgument() &&((!NewTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2322, __PRETTY_FUNCTION__))
2322 "Parameter packs can't have a default argument!")((!NewTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2322, __PRETTY_FUNCTION__))
;
2323 SawParameterPack = true;
2324 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2325 NewTypeParm->hasDefaultArgument() &&
2326 (!SkipBody || !SkipBody->ShouldSkip)) {
2327 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2328 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2329 SawDefaultArgument = true;
2330 RedundantDefaultArg = true;
2331 PreviousDefaultArgLoc = NewDefaultLoc;
2332 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2333 // Merge the default argument from the old declaration to the
2334 // new declaration.
2335 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2336 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2337 } else if (NewTypeParm->hasDefaultArgument()) {
2338 SawDefaultArgument = true;
2339 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2340 } else if (SawDefaultArgument)
2341 MissingDefaultArg = true;
2342 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2343 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2344 // Check for unexpanded parameter packs.
2345 if (!NewNonTypeParm->isParameterPack() &&
2346 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2347 NewNonTypeParm->getTypeSourceInfo(),
2348 UPPC_NonTypeTemplateParameterType)) {
2349 Invalid = true;
2350 continue;
2351 }
2352
2353 // Check the presence of a default argument here.
2354 if (NewNonTypeParm->hasDefaultArgument() &&
2355 DiagnoseDefaultTemplateArgument(*this, TPC,
2356 NewNonTypeParm->getLocation(),
2357 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2358 NewNonTypeParm->removeDefaultArgument();
2359 }
2360
2361 // Merge default arguments for non-type template parameters
2362 NonTypeTemplateParmDecl *OldNonTypeParm
2363 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2364 if (NewNonTypeParm->isParameterPack()) {
2365 assert(!NewNonTypeParm->hasDefaultArgument() &&((!NewNonTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2366, __PRETTY_FUNCTION__))
2366 "Parameter packs can't have a default argument!")((!NewNonTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2366, __PRETTY_FUNCTION__))
;
2367 if (!NewNonTypeParm->isPackExpansion())
2368 SawParameterPack = true;
2369 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2370 NewNonTypeParm->hasDefaultArgument() &&
2371 (!SkipBody || !SkipBody->ShouldSkip)) {
2372 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2373 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2374 SawDefaultArgument = true;
2375 RedundantDefaultArg = true;
2376 PreviousDefaultArgLoc = NewDefaultLoc;
2377 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2378 // Merge the default argument from the old declaration to the
2379 // new declaration.
2380 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2381 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2382 } else if (NewNonTypeParm->hasDefaultArgument()) {
2383 SawDefaultArgument = true;
2384 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2385 } else if (SawDefaultArgument)
2386 MissingDefaultArg = true;
2387 } else {
2388 TemplateTemplateParmDecl *NewTemplateParm
2389 = cast<TemplateTemplateParmDecl>(*NewParam);
2390
2391 // Check for unexpanded parameter packs, recursively.
2392 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2393 Invalid = true;
2394 continue;
2395 }
2396
2397 // Check the presence of a default argument here.
2398 if (NewTemplateParm->hasDefaultArgument() &&
2399 DiagnoseDefaultTemplateArgument(*this, TPC,
2400 NewTemplateParm->getLocation(),
2401 NewTemplateParm->getDefaultArgument().getSourceRange()))
2402 NewTemplateParm->removeDefaultArgument();
2403
2404 // Merge default arguments for template template parameters
2405 TemplateTemplateParmDecl *OldTemplateParm
2406 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2407 if (NewTemplateParm->isParameterPack()) {
2408 assert(!NewTemplateParm->hasDefaultArgument() &&((!NewTemplateParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2409, __PRETTY_FUNCTION__))
2409 "Parameter packs can't have a default argument!")((!NewTemplateParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2409, __PRETTY_FUNCTION__))
;
2410 if (!NewTemplateParm->isPackExpansion())
2411 SawParameterPack = true;
2412 } else if (OldTemplateParm &&
2413 hasVisibleDefaultArgument(OldTemplateParm) &&
2414 NewTemplateParm->hasDefaultArgument() &&
2415 (!SkipBody || !SkipBody->ShouldSkip)) {
2416 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2417 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2418 SawDefaultArgument = true;
2419 RedundantDefaultArg = true;
2420 PreviousDefaultArgLoc = NewDefaultLoc;
2421 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2422 // Merge the default argument from the old declaration to the
2423 // new declaration.
2424 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2425 PreviousDefaultArgLoc
2426 = OldTemplateParm->getDefaultArgument().getLocation();
2427 } else if (NewTemplateParm->hasDefaultArgument()) {
2428 SawDefaultArgument = true;
2429 PreviousDefaultArgLoc
2430 = NewTemplateParm->getDefaultArgument().getLocation();
2431 } else if (SawDefaultArgument)
2432 MissingDefaultArg = true;
2433 }
2434
2435 // C++11 [temp.param]p11:
2436 // If a template parameter of a primary class template or alias template
2437 // is a template parameter pack, it shall be the last template parameter.
2438 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2439 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2440 TPC == TPC_TypeAliasTemplate)) {
2441 Diag((*NewParam)->getLocation(),
2442 diag::err_template_param_pack_must_be_last_template_parameter);
2443 Invalid = true;
2444 }
2445
2446 if (RedundantDefaultArg) {
2447 // C++ [temp.param]p12:
2448 // A template-parameter shall not be given default arguments
2449 // by two different declarations in the same scope.
2450 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2451 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2452 Invalid = true;
2453 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2454 // C++ [temp.param]p11:
2455 // If a template-parameter of a class template has a default
2456 // template-argument, each subsequent template-parameter shall either
2457 // have a default template-argument supplied or be a template parameter
2458 // pack.
2459 Diag((*NewParam)->getLocation(),
2460 diag::err_template_param_default_arg_missing);
2461 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2462 Invalid = true;
2463 RemoveDefaultArguments = true;
2464 }
2465
2466 // If we have an old template parameter list that we're merging
2467 // in, move on to the next parameter.
2468 if (OldParams)
2469 ++OldParam;
2470 }
2471
2472 // We were missing some default arguments at the end of the list, so remove
2473 // all of the default arguments.
2474 if (RemoveDefaultArguments) {
2475 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2476 NewParamEnd = NewParams->end();
2477 NewParam != NewParamEnd; ++NewParam) {
2478 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2479 TTP->removeDefaultArgument();
2480 else if (NonTypeTemplateParmDecl *NTTP
2481 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2482 NTTP->removeDefaultArgument();
2483 else
2484 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2485 }
2486 }
2487
2488 return Invalid;
2489}
2490
2491namespace {
2492
2493/// A class which looks for a use of a certain level of template
2494/// parameter.
2495struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2496 typedef RecursiveASTVisitor<DependencyChecker> super;
2497
2498 unsigned Depth;
2499
2500 // Whether we're looking for a use of a template parameter that makes the
2501 // overall construct type-dependent / a dependent type. This is strictly
2502 // best-effort for now; we may fail to match at all for a dependent type
2503 // in some cases if this is set.
2504 bool IgnoreNonTypeDependent;
2505
2506 bool Match;
2507 SourceLocation MatchLoc;
2508
2509 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2510 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2511 Match(false) {}
2512
2513 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2514 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2515 NamedDecl *ND = Params->getParam(0);
2516 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2517 Depth = PD->getDepth();
2518 } else if (NonTypeTemplateParmDecl *PD =
2519 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2520 Depth = PD->getDepth();
2521 } else {
2522 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2523 }
2524 }
2525
2526 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2527 if (ParmDepth >= Depth) {
2528 Match = true;
2529 MatchLoc = Loc;
2530 return true;
2531 }
2532 return false;
2533 }
2534
2535 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2536 // Prune out non-type-dependent expressions if requested. This can
2537 // sometimes result in us failing to find a template parameter reference
2538 // (if a value-dependent expression creates a dependent type), but this
2539 // mode is best-effort only.
2540 if (auto *E = dyn_cast_or_null<Expr>(S))
2541 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2542 return true;
2543 return super::TraverseStmt(S, Q);
2544 }
2545
2546 bool TraverseTypeLoc(TypeLoc TL) {
2547 if (IgnoreNonTypeDependent && !TL.isNull() &&
2548 !TL.getType()->isDependentType())
2549 return true;
2550 return super::TraverseTypeLoc(TL);
2551 }
2552
2553 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2554 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2555 }
2556
2557 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2558 // For a best-effort search, keep looking until we find a location.
2559 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2560 }
2561
2562 bool TraverseTemplateName(TemplateName N) {
2563 if (TemplateTemplateParmDecl *PD =
2564 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2565 if (Matches(PD->getDepth()))
2566 return false;
2567 return super::TraverseTemplateName(N);
2568 }
2569
2570 bool VisitDeclRefExpr(DeclRefExpr *E) {
2571 if (NonTypeTemplateParmDecl *PD =
2572 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2573 if (Matches(PD->getDepth(), E->getExprLoc()))
2574 return false;
2575 return super::VisitDeclRefExpr(E);
2576 }
2577
2578 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2579 return TraverseType(T->getReplacementType());
2580 }
2581
2582 bool
2583 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2584 return TraverseTemplateArgument(T->getArgumentPack());
2585 }
2586
2587 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2588 return TraverseType(T->getInjectedSpecializationType());
2589 }
2590};
2591} // end anonymous namespace
2592
2593/// Determines whether a given type depends on the given parameter
2594/// list.
2595static bool
2596DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2597 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2598 Checker.TraverseType(T);
2599 return Checker.Match;
2600}
2601
2602// Find the source range corresponding to the named type in the given
2603// nested-name-specifier, if any.
2604static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2605 QualType T,
2606 const CXXScopeSpec &SS) {
2607 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2608 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2609 if (const Type *CurType = NNS->getAsType()) {
2610 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2611 return NNSLoc.getTypeLoc().getSourceRange();
2612 } else
2613 break;
2614
2615 NNSLoc = NNSLoc.getPrefix();
2616 }
2617
2618 return SourceRange();
2619}
2620
2621/// Match the given template parameter lists to the given scope
2622/// specifier, returning the template parameter list that applies to the
2623/// name.
2624///
2625/// \param DeclStartLoc the start of the declaration that has a scope
2626/// specifier or a template parameter list.
2627///
2628/// \param DeclLoc The location of the declaration itself.
2629///
2630/// \param SS the scope specifier that will be matched to the given template
2631/// parameter lists. This scope specifier precedes a qualified name that is
2632/// being declared.
2633///
2634/// \param TemplateId The template-id following the scope specifier, if there
2635/// is one. Used to check for a missing 'template<>'.
2636///
2637/// \param ParamLists the template parameter lists, from the outermost to the
2638/// innermost template parameter lists.
2639///
2640/// \param IsFriend Whether to apply the slightly different rules for
2641/// matching template parameters to scope specifiers in friend
2642/// declarations.
2643///
2644/// \param IsMemberSpecialization will be set true if the scope specifier
2645/// denotes a fully-specialized type, and therefore this is a declaration of
2646/// a member specialization.
2647///
2648/// \returns the template parameter list, if any, that corresponds to the
2649/// name that is preceded by the scope specifier @p SS. This template
2650/// parameter list may have template parameters (if we're declaring a
2651/// template) or may have no template parameters (if we're declaring a
2652/// template specialization), or may be NULL (if what we're declaring isn't
2653/// itself a template).
2654TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2655 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2656 TemplateIdAnnotation *TemplateId,
2657 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2658 bool &IsMemberSpecialization, bool &Invalid) {
2659 IsMemberSpecialization = false;
2660 Invalid = false;
2661
2662 // The sequence of nested types to which we will match up the template
2663 // parameter lists. We first build this list by starting with the type named
2664 // by the nested-name-specifier and walking out until we run out of types.
2665 SmallVector<QualType, 4> NestedTypes;
2666 QualType T;
2667 if (SS.getScopeRep()) {
2668 if (CXXRecordDecl *Record
2669 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2670 T = Context.getTypeDeclType(Record);
2671 else
2672 T = QualType(SS.getScopeRep()->getAsType(), 0);
2673 }
2674
2675 // If we found an explicit specialization that prevents us from needing
2676 // 'template<>' headers, this will be set to the location of that
2677 // explicit specialization.
2678 SourceLocation ExplicitSpecLoc;
2679
2680 while (!T.isNull()) {
2681 NestedTypes.push_back(T);
2682
2683 // Retrieve the parent of a record type.
2684 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2685 // If this type is an explicit specialization, we're done.
2686 if (ClassTemplateSpecializationDecl *Spec
2687 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2688 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2689 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2690 ExplicitSpecLoc = Spec->getLocation();
2691 break;
2692 }
2693 } else if (Record->getTemplateSpecializationKind()
2694 == TSK_ExplicitSpecialization) {
2695 ExplicitSpecLoc = Record->getLocation();
2696 break;
2697 }
2698
2699 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2700 T = Context.getTypeDeclType(Parent);
2701 else
2702 T = QualType();
2703 continue;
2704 }
2705
2706 if (const TemplateSpecializationType *TST
2707 = T->getAs<TemplateSpecializationType>()) {
2708 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2709 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2710 T = Context.getTypeDeclType(Parent);
2711 else
2712 T = QualType();
2713 continue;
2714 }
2715 }
2716
2717 // Look one step prior in a dependent template specialization type.
2718 if (const DependentTemplateSpecializationType *DependentTST
2719 = T->getAs<DependentTemplateSpecializationType>()) {
2720 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2721 T = QualType(NNS->getAsType(), 0);
2722 else
2723 T = QualType();
2724 continue;
2725 }
2726
2727 // Look one step prior in a dependent name type.
2728 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2729 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2730 T = QualType(NNS->getAsType(), 0);
2731 else
2732 T = QualType();
2733 continue;
2734 }
2735
2736 // Retrieve the parent of an enumeration type.
2737 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2738 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2739 // check here.
2740 EnumDecl *Enum = EnumT->getDecl();
2741
2742 // Get to the parent type.
2743 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2744 T = Context.getTypeDeclType(Parent);
2745 else
2746 T = QualType();
2747 continue;
2748 }
2749
2750 T = QualType();
2751 }
2752 // Reverse the nested types list, since we want to traverse from the outermost
2753 // to the innermost while checking template-parameter-lists.
2754 std::reverse(NestedTypes.begin(), NestedTypes.end());
2755
2756 // C++0x [temp.expl.spec]p17:
2757 // A member or a member template may be nested within many
2758 // enclosing class templates. In an explicit specialization for
2759 // such a member, the member declaration shall be preceded by a
2760 // template<> for each enclosing class template that is
2761 // explicitly specialized.
2762 bool SawNonEmptyTemplateParameterList = false;
2763
2764 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2765 if (SawNonEmptyTemplateParameterList) {
2766 Diag(DeclLoc, diag::err_specialize_member_of_template)
2767 << !Recovery << Range;
2768 Invalid = true;
2769 IsMemberSpecialization = false;
2770 return true;
2771 }
2772
2773 return false;
2774 };
2775
2776 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2777 // Check that we can have an explicit specialization here.
2778 if (CheckExplicitSpecialization(Range, true))
2779 return true;
2780
2781 // We don't have a template header, but we should.
2782 SourceLocation ExpectedTemplateLoc;
2783 if (!ParamLists.empty())
2784 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2785 else
2786 ExpectedTemplateLoc = DeclStartLoc;
2787
2788 Diag(DeclLoc, diag::err_template_spec_needs_header)
2789 << Range
2790 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2791 return false;
2792 };
2793
2794 unsigned ParamIdx = 0;
2795 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2796 ++TypeIdx) {
2797 T = NestedTypes[TypeIdx];
2798
2799 // Whether we expect a 'template<>' header.
2800 bool NeedEmptyTemplateHeader = false;
2801
2802 // Whether we expect a template header with parameters.
2803 bool NeedNonemptyTemplateHeader = false;
2804
2805 // For a dependent type, the set of template parameters that we
2806 // expect to see.
2807 TemplateParameterList *ExpectedTemplateParams = nullptr;
2808
2809 // C++0x [temp.expl.spec]p15:
2810 // A member or a member template may be nested within many enclosing
2811 // class templates. In an explicit specialization for such a member, the
2812 // member declaration shall be preceded by a template<> for each
2813 // enclosing class template that is explicitly specialized.
2814 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2815 if (ClassTemplatePartialSpecializationDecl *Partial
2816 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2817 ExpectedTemplateParams = Partial->getTemplateParameters();
2818 NeedNonemptyTemplateHeader = true;
2819 } else if (Record->isDependentType()) {
2820 if (Record->getDescribedClassTemplate()) {
2821 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2822 ->getTemplateParameters();
2823 NeedNonemptyTemplateHeader = true;
2824 }
2825 } else if (ClassTemplateSpecializationDecl *Spec
2826 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2827 // C++0x [temp.expl.spec]p4:
2828 // Members of an explicitly specialized class template are defined
2829 // in the same manner as members of normal classes, and not using
2830 // the template<> syntax.
2831 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2832 NeedEmptyTemplateHeader = true;
2833 else
2834 continue;
2835 } else if (Record->getTemplateSpecializationKind()) {
2836 if (Record->getTemplateSpecializationKind()
2837 != TSK_ExplicitSpecialization &&
2838 TypeIdx == NumTypes - 1)
2839 IsMemberSpecialization = true;
2840
2841 continue;
2842 }
2843 } else if (const TemplateSpecializationType *TST
2844 = T->getAs<TemplateSpecializationType>()) {
2845 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2846 ExpectedTemplateParams = Template->getTemplateParameters();
2847 NeedNonemptyTemplateHeader = true;
2848 }
2849 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2850 // FIXME: We actually could/should check the template arguments here
2851 // against the corresponding template parameter list.
2852 NeedNonemptyTemplateHeader = false;
2853 }
2854
2855 // C++ [temp.expl.spec]p16:
2856 // In an explicit specialization declaration for a member of a class
2857 // template or a member template that ap- pears in namespace scope, the
2858 // member template and some of its enclosing class templates may remain
2859 // unspecialized, except that the declaration shall not explicitly
2860 // specialize a class member template if its en- closing class templates
2861 // are not explicitly specialized as well.
2862 if (ParamIdx < ParamLists.size()) {
2863 if (ParamLists[ParamIdx]->size() == 0) {
2864 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2865 false))
2866 return nullptr;
2867 } else
2868 SawNonEmptyTemplateParameterList = true;
2869 }
2870
2871 if (NeedEmptyTemplateHeader) {
2872 // If we're on the last of the types, and we need a 'template<>' header
2873 // here, then it's a member specialization.
2874 if (TypeIdx == NumTypes - 1)
2875 IsMemberSpecialization = true;
2876
2877 if (ParamIdx < ParamLists.size()) {
2878 if (ParamLists[ParamIdx]->size() > 0) {
2879 // The header has template parameters when it shouldn't. Complain.
2880 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2881 diag::err_template_param_list_matches_nontemplate)
2882 << T
2883 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2884 ParamLists[ParamIdx]->getRAngleLoc())
2885 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2886 Invalid = true;
2887 return nullptr;
2888 }
2889
2890 // Consume this template header.
2891 ++ParamIdx;
2892 continue;
2893 }
2894
2895 if (!IsFriend)
2896 if (DiagnoseMissingExplicitSpecialization(
2897 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2898 return nullptr;
2899
2900 continue;
2901 }
2902
2903 if (NeedNonemptyTemplateHeader) {
2904 // In friend declarations we can have template-ids which don't
2905 // depend on the corresponding template parameter lists. But
2906 // assume that empty parameter lists are supposed to match this
2907 // template-id.
2908 if (IsFriend && T->isDependentType()) {
2909 if (ParamIdx < ParamLists.size() &&
2910 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2911 ExpectedTemplateParams = nullptr;
2912 else
2913 continue;
2914 }
2915
2916 if (ParamIdx < ParamLists.size()) {
2917 // Check the template parameter list, if we can.
2918 if (ExpectedTemplateParams &&
2919 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2920 ExpectedTemplateParams,
2921 true, TPL_TemplateMatch))
2922 Invalid = true;
2923
2924 if (!Invalid &&
2925 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2926 TPC_ClassTemplateMember))
2927 Invalid = true;
2928
2929 ++ParamIdx;
2930 continue;
2931 }
2932
2933 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2934 << T
2935 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2936 Invalid = true;
2937 continue;
2938 }
2939 }
2940
2941 // If there were at least as many template-ids as there were template
2942 // parameter lists, then there are no template parameter lists remaining for
2943 // the declaration itself.
2944 if (ParamIdx >= ParamLists.size()) {
2945 if (TemplateId && !IsFriend) {
2946 // We don't have a template header for the declaration itself, but we
2947 // should.
2948 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2949 TemplateId->RAngleLoc));
2950
2951 // Fabricate an empty template parameter list for the invented header.
2952 return TemplateParameterList::Create(Context, SourceLocation(),
2953 SourceLocation(), None,
2954 SourceLocation(), nullptr);
2955 }
2956
2957 return nullptr;
2958 }
2959
2960 // If there were too many template parameter lists, complain about that now.
2961 if (ParamIdx < ParamLists.size() - 1) {
2962 bool HasAnyExplicitSpecHeader = false;
2963 bool AllExplicitSpecHeaders = true;
2964 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2965 if (ParamLists[I]->size() == 0)
2966 HasAnyExplicitSpecHeader = true;
2967 else
2968 AllExplicitSpecHeaders = false;
2969 }
2970
2971 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2972 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2973 : diag::err_template_spec_extra_headers)
2974 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2975 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
2976
2977 // If there was a specialization somewhere, such that 'template<>' is
2978 // not required, and there were any 'template<>' headers, note where the
2979 // specialization occurred.
2980 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2981 Diag(ExplicitSpecLoc,
2982 diag::note_explicit_template_spec_does_not_need_header)
2983 << NestedTypes.back();
2984
2985 // We have a template parameter list with no corresponding scope, which
2986 // means that the resulting template declaration can't be instantiated
2987 // properly (we'll end up with dependent nodes when we shouldn't).
2988 if (!AllExplicitSpecHeaders)
2989 Invalid = true;
2990 }
2991
2992 // C++ [temp.expl.spec]p16:
2993 // In an explicit specialization declaration for a member of a class
2994 // template or a member template that ap- pears in namespace scope, the
2995 // member template and some of its enclosing class templates may remain
2996 // unspecialized, except that the declaration shall not explicitly
2997 // specialize a class member template if its en- closing class templates
2998 // are not explicitly specialized as well.
2999 if (ParamLists.back()->size() == 0 &&
3000 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3001 false))
3002 return nullptr;
3003
3004 // Return the last template parameter list, which corresponds to the
3005 // entity being declared.
3006 return ParamLists.back();
3007}
3008
3009void Sema::NoteAllFoundTemplates(TemplateName Name) {
3010 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3011 Diag(Template->getLocation(), diag::note_template_declared_here)
3012 << (isa<FunctionTemplateDecl>(Template)
3013 ? 0
3014 : isa<ClassTemplateDecl>(Template)
3015 ? 1
3016 : isa<VarTemplateDecl>(Template)
3017 ? 2
3018 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3019 << Template->getDeclName();
3020 return;
3021 }
3022
3023 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3024 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3025 IEnd = OST->end();
3026 I != IEnd; ++I)
3027 Diag((*I)->getLocation(), diag::note_template_declared_here)
3028 << 0 << (*I)->getDeclName();
3029
3030 return;
3031 }
3032}
3033
3034static QualType
3035checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3036 const SmallVectorImpl<TemplateArgument> &Converted,
3037 SourceLocation TemplateLoc,
3038 TemplateArgumentListInfo &TemplateArgs) {
3039 ASTContext &Context = SemaRef.getASTContext();
3040 switch (BTD->getBuiltinTemplateKind()) {
3041 case BTK__make_integer_seq: {
3042 // Specializations of __make_integer_seq<S, T, N> are treated like
3043 // S<T, 0, ..., N-1>.
3044
3045 // C++14 [inteseq.intseq]p1:
3046 // T shall be an integer type.
3047 if (!Converted[1].getAsType()->isIntegralType(Context)) {
3048 SemaRef.Diag(TemplateArgs[1].getLocation(),
3049 diag::err_integer_sequence_integral_element_type);
3050 return QualType();
3051 }
3052
3053 // C++14 [inteseq.make]p1:
3054 // If N is negative the program is ill-formed.
3055 TemplateArgument NumArgsArg = Converted[2];
3056 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
3057 if (NumArgs < 0) {
3058 SemaRef.Diag(TemplateArgs[2].getLocation(),
3059 diag::err_integer_sequence_negative_length);
3060 return QualType();
3061 }
3062
3063 QualType ArgTy = NumArgsArg.getIntegralType();
3064 TemplateArgumentListInfo SyntheticTemplateArgs;
3065 // The type argument gets reused as the first template argument in the
3066 // synthetic template argument list.
3067 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
3068 // Expand N into 0 ... N-1.
3069 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3070 I < NumArgs; ++I) {
3071 TemplateArgument TA(Context, I, ArgTy);
3072 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3073 TA, ArgTy, TemplateArgs[2].getLocation()));
3074 }
3075 // The first template argument will be reused as the template decl that
3076 // our synthetic template arguments will be applied to.
3077 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3078 TemplateLoc, SyntheticTemplateArgs);
3079 }
3080
3081 case BTK__type_pack_element:
3082 // Specializations of
3083 // __type_pack_element<Index, T_1, ..., T_N>
3084 // are treated like T_Index.
3085 assert(Converted.size() == 2 &&((Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack"
) ? static_cast<void> (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3086, __PRETTY_FUNCTION__))
3086 "__type_pack_element should be given an index and a parameter pack")((Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack"
) ? static_cast<void> (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3086, __PRETTY_FUNCTION__))
;
3087
3088 // If the Index is out of bounds, the program is ill-formed.
3089 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3090 llvm::APSInt Index = IndexArg.getAsIntegral();
3091 assert(Index >= 0 && "the index used with __type_pack_element should be of "((Index >= 0 && "the index used with __type_pack_element should be of "
"type std::size_t, and hence be non-negative") ? static_cast
<void> (0) : __assert_fail ("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3092, __PRETTY_FUNCTION__))
3092 "type std::size_t, and hence be non-negative")((Index >= 0 && "the index used with __type_pack_element should be of "
"type std::size_t, and hence be non-negative") ? static_cast
<void> (0) : __assert_fail ("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3092, __PRETTY_FUNCTION__))
;
3093 if (Index >= Ts.pack_size()) {
3094 SemaRef.Diag(TemplateArgs[0].getLocation(),
3095 diag::err_type_pack_element_out_of_bounds);
3096 return QualType();
3097 }
3098
3099 // We simply return the type at index `Index`.
3100 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3101 return Nth->getAsType();
3102 }
3103 llvm_unreachable("unexpected BuiltinTemplateDecl!")::llvm::llvm_unreachable_internal("unexpected BuiltinTemplateDecl!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3103)
;
3104}
3105
3106/// Determine whether this alias template is "enable_if_t".
3107static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3108 return AliasTemplate->getName().equals("enable_if_t");
3109}
3110
3111/// Collect all of the separable terms in the given condition, which
3112/// might be a conjunction.
3113///
3114/// FIXME: The right answer is to convert the logical expression into
3115/// disjunctive normal form, so we can find the first failed term
3116/// within each possible clause.
3117static void collectConjunctionTerms(Expr *Clause,
3118 SmallVectorImpl<Expr *> &Terms) {
3119 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3120 if (BinOp->getOpcode() == BO_LAnd) {
3121 collectConjunctionTerms(BinOp->getLHS(), Terms);
3122 collectConjunctionTerms(BinOp->getRHS(), Terms);
3123 }
3124
3125 return;
3126 }
3127
3128 Terms.push_back(Clause);
3129}
3130
3131// The ranges-v3 library uses an odd pattern of a top-level "||" with
3132// a left-hand side that is value-dependent but never true. Identify
3133// the idiom and ignore that term.
3134static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3135 // Top-level '||'.
3136 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3137 if (!BinOp) return Cond;
3138
3139 if (BinOp->getOpcode() != BO_LOr) return Cond;
3140
3141 // With an inner '==' that has a literal on the right-hand side.
3142 Expr *LHS = BinOp->getLHS();
3143 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3144 if (!InnerBinOp) return Cond;
3145
3146 if (InnerBinOp->getOpcode() != BO_EQ ||
3147 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3148 return Cond;
3149
3150 // If the inner binary operation came from a macro expansion named
3151 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3152 // of the '||', which is the real, user-provided condition.
3153 SourceLocation Loc = InnerBinOp->getExprLoc();
3154 if (!Loc.isMacroID()) return Cond;
3155
3156 StringRef MacroName = PP.getImmediateMacroName(Loc);
3157 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3158 return BinOp->getRHS();
3159
3160 return Cond;
3161}
3162
3163namespace {
3164
3165// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3166// within failing boolean expression, such as substituting template parameters
3167// for actual types.
3168class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3169public:
3170 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3171 : Policy(P) {}
3172
3173 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3174 const auto *DR = dyn_cast<DeclRefExpr>(E);
3175 if (DR && DR->getQualifier()) {
3176 // If this is a qualified name, expand the template arguments in nested
3177 // qualifiers.
3178 DR->getQualifier()->print(OS, Policy, true);
3179 // Then print the decl itself.
3180 const ValueDecl *VD = DR->getDecl();
3181 OS << VD->getName();
3182 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3183 // This is a template variable, print the expanded template arguments.
3184 printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3185 }
3186 return true;
3187 }
3188 return false;
3189 }
3190
3191private:
3192 const PrintingPolicy Policy;
3193};
3194
3195} // end anonymous namespace
3196
3197std::pair<Expr *, std::string>
3198Sema::findFailedBooleanCondition(Expr *Cond) {
3199 Cond = lookThroughRangesV3Condition(PP, Cond);
3200
3201 // Separate out all of the terms in a conjunction.
3202 SmallVector<Expr *, 4> Terms;
3203 collectConjunctionTerms(Cond, Terms);
3204
3205 // Determine which term failed.
3206 Expr *FailedCond = nullptr;
3207 for (Expr *Term : Terms) {
3208 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3209
3210 // Literals are uninteresting.
3211 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3212 isa<IntegerLiteral>(TermAsWritten))
3213 continue;
3214
3215 // The initialization of the parameter from the argument is
3216 // a constant-evaluated context.
3217 EnterExpressionEvaluationContext ConstantEvaluated(
3218 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3219
3220 bool Succeeded;
3221 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3222 !Succeeded) {
3223 FailedCond = TermAsWritten;
3224 break;
3225 }
3226 }
3227 if (!FailedCond)
3228 FailedCond = Cond->IgnoreParenImpCasts();
3229
3230 std::string Description;
3231 {
3232 llvm::raw_string_ostream Out(Description);
3233 PrintingPolicy Policy = getPrintingPolicy();
3234 Policy.PrintCanonicalTypes = true;
3235 FailedBooleanConditionPrinterHelper Helper(Policy);
3236 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3237 }
3238 return { FailedCond, Description };
3239}
3240
3241QualType Sema::CheckTemplateIdType(TemplateName Name,
3242 SourceLocation TemplateLoc,
3243 TemplateArgumentListInfo &TemplateArgs) {
3244 DependentTemplateName *DTN
3245 = Name.getUnderlying().getAsDependentTemplateName();
3246 if (DTN && DTN->isIdentifier())
3247 // When building a template-id where the template-name is dependent,
3248 // assume the template is a type template. Either our assumption is
3249 // correct, or the code is ill-formed and will be diagnosed when the
3250 // dependent name is substituted.
3251 return Context.getDependentTemplateSpecializationType(ETK_None,
3252 DTN->getQualifier(),
3253 DTN->getIdentifier(),
3254 TemplateArgs);
3255
3256 TemplateDecl *Template = Name.getAsTemplateDecl();
3257 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3258 isa<VarTemplateDecl>(Template) ||
3259 isa<ConceptDecl>(Template)) {
3260 // We might have a substituted template template parameter pack. If so,
3261 // build a template specialization type for it.
3262 if (Name.getAsSubstTemplateTemplateParmPack())
3263 return Context.getTemplateSpecializationType(Name, TemplateArgs);
3264
3265 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3266 << Name;
3267 NoteAllFoundTemplates(Name);
3268 return QualType();
3269 }
3270
3271 // Check that the template argument list is well-formed for this
3272 // template.
3273 SmallVector<TemplateArgument, 4> Converted;
3274 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3275 false, Converted))
3276 return QualType();
3277
3278 QualType CanonType;
3279
3280 bool InstantiationDependent = false;
3281 if (TypeAliasTemplateDecl *AliasTemplate =
3282 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3283 // Find the canonical type for this type alias template specialization.
3284 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3285 if (Pattern->isInvalidDecl())
3286 return QualType();
3287
3288 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3289 Converted);
3290
3291 // Only substitute for the innermost template argument list.
3292 MultiLevelTemplateArgumentList TemplateArgLists;
3293 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3294 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3295 for (unsigned I = 0; I < Depth; ++I)
3296 TemplateArgLists.addOuterTemplateArguments(None);
3297
3298 LocalInstantiationScope Scope(*this);
3299 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3300 if (Inst.isInvalid())
3301 return QualType();
3302
3303 CanonType = SubstType(Pattern->getUnderlyingType(),
3304 TemplateArgLists, AliasTemplate->getLocation(),
3305 AliasTemplate->getDeclName());
3306 if (CanonType.isNull()) {
3307 // If this was enable_if and we failed to find the nested type
3308 // within enable_if in a SFINAE context, dig out the specific
3309 // enable_if condition that failed and present that instead.
3310 if (isEnableIfAliasTemplate(AliasTemplate)) {
3311 if (auto DeductionInfo = isSFINAEContext()) {
3312 if (*DeductionInfo &&
3313 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3314 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3315 diag::err_typename_nested_not_found_enable_if &&
3316 TemplateArgs[0].getArgument().getKind()
3317 == TemplateArgument::Expression) {
3318 Expr *FailedCond;
3319 std::string FailedDescription;
3320 std::tie(FailedCond, FailedDescription) =
3321 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3322
3323 // Remove the old SFINAE diagnostic.
3324 PartialDiagnosticAt OldDiag =
3325 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3326 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3327
3328 // Add a new SFINAE diagnostic specifying which condition
3329 // failed.
3330 (*DeductionInfo)->addSFINAEDiagnostic(
3331 OldDiag.first,
3332 PDiag(diag::err_typename_nested_not_found_requirement)
3333 << FailedDescription
3334 << FailedCond->getSourceRange());
3335 }
3336 }
3337 }
3338
3339 return QualType();
3340 }
3341 } else if (Name.isDependent() ||
3342 TemplateSpecializationType::anyDependentTemplateArguments(
3343 TemplateArgs, InstantiationDependent)) {
3344 // This class template specialization is a dependent
3345 // type. Therefore, its canonical type is another class template
3346 // specialization type that contains all of the converted
3347 // arguments in canonical form. This ensures that, e.g., A<T> and
3348 // A<T, T> have identical types when A is declared as:
3349 //
3350 // template<typename T, typename U = T> struct A;
3351 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3352
3353 // This might work out to be a current instantiation, in which
3354 // case the canonical type needs to be the InjectedClassNameType.
3355 //
3356 // TODO: in theory this could be a simple hashtable lookup; most
3357 // changes to CurContext don't change the set of current
3358 // instantiations.
3359 if (isa<ClassTemplateDecl>(Template)) {
3360 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3361 // If we get out to a namespace, we're done.
3362 if (Ctx->isFileContext()) break;
3363
3364 // If this isn't a record, keep looking.
3365 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3366 if (!Record) continue;
3367
3368 // Look for one of the two cases with InjectedClassNameTypes
3369 // and check whether it's the same template.
3370 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3371 !Record->getDescribedClassTemplate())
3372 continue;
3373
3374 // Fetch the injected class name type and check whether its
3375 // injected type is equal to the type we just built.
3376 QualType ICNT = Context.getTypeDeclType(Record);
3377 QualType Injected = cast<InjectedClassNameType>(ICNT)
3378 ->getInjectedSpecializationType();
3379
3380 if (CanonType != Injected->getCanonicalTypeInternal())
3381 continue;
3382
3383 // If so, the canonical type of this TST is the injected
3384 // class name type of the record we just found.
3385 assert(ICNT.isCanonical())((ICNT.isCanonical()) ? static_cast<void> (0) : __assert_fail
("ICNT.isCanonical()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3385, __PRETTY_FUNCTION__))
;
3386 CanonType = ICNT;
3387 break;
3388 }
3389 }
3390 } else if (ClassTemplateDecl *ClassTemplate
3391 = dyn_cast<ClassTemplateDecl>(Template)) {
3392 // Find the class template specialization declaration that
3393 // corresponds to these arguments.
3394 void *InsertPos = nullptr;
3395 ClassTemplateSpecializationDecl *Decl
3396 = ClassTemplate->findSpecialization(Converted, InsertPos);
3397 if (!Decl) {
3398 // This is the first time we have referenced this class template
3399 // specialization. Create the canonical declaration and add it to
3400 // the set of specializations.
3401 Decl = ClassTemplateSpecializationDecl::Create(
3402 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3403 ClassTemplate->getDeclContext(),
3404 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3405 ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
3406 ClassTemplate->AddSpecialization(Decl, InsertPos);
3407 if (ClassTemplate->isOutOfLine())
3408 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3409 }
3410
3411 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3412 MultiLevelTemplateArgumentList TemplateArgLists;
3413 TemplateArgLists.addOuterTemplateArguments(Converted);
3414 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3415 Decl);
3416 }
3417
3418 // Diagnose uses of this specialization.
3419 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3420
3421 CanonType = Context.getTypeDeclType(Decl);
3422 assert(isa<RecordType>(CanonType) &&((isa<RecordType>(CanonType) && "type of non-dependent specialization is not a RecordType"
) ? static_cast<void> (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3423, __PRETTY_FUNCTION__))
3423 "type of non-dependent specialization is not a RecordType")((isa<RecordType>(CanonType) && "type of non-dependent specialization is not a RecordType"
) ? static_cast<void> (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3423, __PRETTY_FUNCTION__))
;
3424 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3425 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3426 TemplateArgs);
3427 }
3428
3429 // Build the fully-sugared type for this class template
3430 // specialization, which refers back to the class template
3431 // specialization we created or found.
3432 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3433}
3434
3435void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3436 TemplateNameKind &TNK,
3437 SourceLocation NameLoc,
3438 IdentifierInfo *&II) {
3439 assert(TNK == TNK_Undeclared_template && "not an undeclared template name")((TNK == TNK_Undeclared_template && "not an undeclared template name"
) ? static_cast<void> (0) : __assert_fail ("TNK == TNK_Undeclared_template && \"not an undeclared template name\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3439, __PRETTY_FUNCTION__))
;
3440
3441 TemplateName Name = ParsedName.get();
3442 auto *ATN = Name.getAsAssumedTemplateName();
3443 assert(ATN && "not an assumed template name")((ATN && "not an assumed template name") ? static_cast
<void> (0) : __assert_fail ("ATN && \"not an assumed template name\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3443, __PRETTY_FUNCTION__))
;
3444 II = ATN->getDeclName().getAsIdentifierInfo();
3445
3446 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3447 // Resolved to a type template name.
3448 ParsedName = TemplateTy::make(Name);
3449 TNK = TNK_Type_template;
3450 }
3451}
3452
3453bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3454 SourceLocation NameLoc,
3455 bool Diagnose) {
3456 // We assumed this undeclared identifier to be an (ADL-only) function
3457 // template name, but it was used in a context where a type was required.
3458 // Try to typo-correct it now.
3459 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3460 assert(ATN && "not an assumed template name")((ATN && "not an assumed template name") ? static_cast
<void> (0) : __assert_fail ("ATN && \"not an assumed template name\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3460, __PRETTY_FUNCTION__))
;
3461
3462 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3463 struct CandidateCallback : CorrectionCandidateCallback {
3464 bool ValidateCandidate(const TypoCorrection &TC) override {
3465 return TC.getCorrectionDecl() &&
3466 getAsTypeTemplateDecl(TC.getCorrectionDecl());
3467 }
3468 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3469 return std::make_unique<CandidateCallback>(*this);
3470 }
3471 } FilterCCC;
3472
3473 TypoCorrection Corrected =
3474 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3475 FilterCCC, CTK_ErrorRecovery);
3476 if (Corrected && Corrected.getFoundDecl()) {
3477 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3478 << ATN->getDeclName());
3479 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3480 return false;
3481 }
3482
3483 if (Diagnose)
3484 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3485 return true;
3486}
3487
3488TypeResult Sema::ActOnTemplateIdType(
3489 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3490 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3491 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3492 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3493 bool IsCtorOrDtorName, bool IsClassName) {
3494 if (SS.isInvalid())
3495 return true;
3496
3497 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3498 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3499
3500 // C++ [temp.res]p3:
3501 // A qualified-id that refers to a type and in which the
3502 // nested-name-specifier depends on a template-parameter (14.6.2)
3503 // shall be prefixed by the keyword typename to indicate that the
3504 // qualified-id denotes a type, forming an
3505 // elaborated-type-specifier (7.1.5.3).
3506 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3507 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3508 << SS.getScopeRep() << TemplateII->getName();
3509 // Recover as if 'typename' were specified.
3510 // FIXME: This is not quite correct recovery as we don't transform SS
3511 // into the corresponding dependent form (and we don't diagnose missing
3512 // 'template' keywords within SS as a result).
3513 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3514 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3515 TemplateArgsIn, RAngleLoc);
3516 }
3517
3518 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3519 // it's not actually allowed to be used as a type in most cases. Because
3520 // we annotate it before we know whether it's valid, we have to check for
3521 // this case here.
3522 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3523 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3524 Diag(TemplateIILoc,
3525 TemplateKWLoc.isInvalid()
3526 ? diag::err_out_of_line_qualified_id_type_names_constructor
3527 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3528 << TemplateII << 0 /*injected-class-name used as template name*/
3529 << 1 /*if any keyword was present, it was 'template'*/;
3530 }
3531 }
3532
3533 TemplateName Template = TemplateD.get();
3534 if (Template.getAsAssumedTemplateName() &&
3535 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3536 return true;
3537
3538 // Translate the parser's template argument list in our AST format.
3539 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3540 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3541
3542 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3543 QualType T
3544 = Context.getDependentTemplateSpecializationType(ETK_None,
3545 DTN->getQualifier(),
3546 DTN->getIdentifier(),
3547 TemplateArgs);
3548 // Build type-source information.
3549 TypeLocBuilder TLB;
3550 DependentTemplateSpecializationTypeLoc SpecTL
3551 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3552 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3553 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3554 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3555 SpecTL.setTemplateNameLoc(TemplateIILoc);
3556 SpecTL.setLAngleLoc(LAngleLoc);
3557 SpecTL.setRAngleLoc(RAngleLoc);
3558 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3559 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3560 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3561 }
3562
3563 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3564 if (Result.isNull())
3565 return true;
3566
3567 // Build type-source information.
3568 TypeLocBuilder TLB;
3569 TemplateSpecializationTypeLoc SpecTL
3570 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3571 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3572 SpecTL.setTemplateNameLoc(TemplateIILoc);
3573 SpecTL.setLAngleLoc(LAngleLoc);
3574 SpecTL.setRAngleLoc(RAngleLoc);
3575 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3576 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3577
3578 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3579 // constructor or destructor name (in such a case, the scope specifier
3580 // will be attached to the enclosing Decl or Expr node).
3581 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3582 // Create an elaborated-type-specifier containing the nested-name-specifier.
3583 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3584 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3585 ElabTL.setElaboratedKeywordLoc(SourceLocation());
3586 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3587 }
3588
3589 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3590}
3591
3592TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3593 TypeSpecifierType TagSpec,
3594 SourceLocation TagLoc,
3595 CXXScopeSpec &SS,
3596 SourceLocation TemplateKWLoc,
3597 TemplateTy TemplateD,
3598 SourceLocation TemplateLoc,
3599 SourceLocation LAngleLoc,
3600 ASTTemplateArgsPtr TemplateArgsIn,
3601 SourceLocation RAngleLoc) {
3602 TemplateName Template = TemplateD.get();
3603
3604 // Translate the parser's template argument list in our AST format.
3605 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3606 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3607
3608 // Determine the tag kind
3609 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3610 ElaboratedTypeKeyword Keyword
3611 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3612
3613 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3614 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
3615 DTN->getQualifier(),
3616 DTN->getIdentifier(),
3617 TemplateArgs);
3618
3619 // Build type-source information.
3620 TypeLocBuilder TLB;
3621 DependentTemplateSpecializationTypeLoc SpecTL
3622 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3623 SpecTL.setElaboratedKeywordLoc(TagLoc);
3624 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3625 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3626 SpecTL.setTemplateNameLoc(TemplateLoc);
3627 SpecTL.setLAngleLoc(LAngleLoc);
3628 SpecTL.setRAngleLoc(RAngleLoc);
3629 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3630 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3631 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3632 }
3633
3634 if (TypeAliasTemplateDecl *TAT =
3635 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3636 // C++0x [dcl.type.elab]p2:
3637 // If the identifier resolves to a typedef-name or the simple-template-id
3638 // resolves to an alias template specialization, the
3639 // elaborated-type-specifier is ill-formed.
3640 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3641 << TAT << NTK_TypeAliasTemplate << TagKind;
3642 Diag(TAT->getLocation(), diag::note_declared_at);
3643 }
3644
3645 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3646 if (Result.isNull())
3647 return TypeResult(true);
3648
3649 // Check the tag kind
3650 if (const RecordType *RT = Result->getAs<RecordType>()) {
3651 RecordDecl *D = RT->getDecl();
3652
3653 IdentifierInfo *Id = D->getIdentifier();
3654 assert(Id && "templated class must have an identifier")((Id && "templated class must have an identifier") ? static_cast
<void> (0) : __assert_fail ("Id && \"templated class must have an identifier\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3654, __PRETTY_FUNCTION__))
;
3655
3656 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3657 TagLoc, Id)) {
3658 Diag(TagLoc, diag::err_use_with_wrong_tag)
3659 << Result
3660 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3661 Diag(D->getLocation(), diag::note_previous_use);
3662 }
3663 }
3664
3665 // Provide source-location information for the template specialization.
3666 TypeLocBuilder TLB;
3667 TemplateSpecializationTypeLoc SpecTL
3668 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3669 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3670 SpecTL.setTemplateNameLoc(TemplateLoc);
3671 SpecTL.setLAngleLoc(LAngleLoc);
3672 SpecTL.setRAngleLoc(RAngleLoc);
3673 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3674 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3675
3676 // Construct an elaborated type containing the nested-name-specifier (if any)
3677 // and tag keyword.
3678 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3679 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3680 ElabTL.setElaboratedKeywordLoc(TagLoc);
3681 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3682 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3683}
3684
3685static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3686 NamedDecl *PrevDecl,
3687 SourceLocation Loc,
3688 bool IsPartialSpecialization);
3689
3690static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3691
3692static bool isTemplateArgumentTemplateParameter(
3693 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3694 switch (Arg.getKind()) {
3695 case TemplateArgument::Null:
3696 case TemplateArgument::NullPtr:
3697 case TemplateArgument::Integral:
3698 case TemplateArgument::Declaration:
3699 case TemplateArgument::Pack:
3700 case TemplateArgument::TemplateExpansion:
3701 return false;
3702
3703 case TemplateArgument::Type: {
3704 QualType Type = Arg.getAsType();
3705 const TemplateTypeParmType *TPT =
3706 Arg.getAsType()->getAs<TemplateTypeParmType>();
3707 return TPT && !Type.hasQualifiers() &&
3708 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3709 }
3710
3711 case TemplateArgument::Expression: {
3712 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3713 if (!DRE || !DRE->getDecl())
3714 return false;
3715 const NonTypeTemplateParmDecl *NTTP =
3716 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3717 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3718 }
3719
3720 case TemplateArgument::Template:
3721 const TemplateTemplateParmDecl *TTP =
3722 dyn_cast_or_null<TemplateTemplateParmDecl>(
3723 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3724 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3725 }
3726 llvm_unreachable("unexpected kind of template argument")::llvm::llvm_unreachable_internal("unexpected kind of template argument"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3726)
;
3727}
3728
3729static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3730 ArrayRef<TemplateArgument> Args) {
3731 if (Params->size() != Args.size())
3732 return false;
3733
3734 unsigned Depth = Params->getDepth();
3735
3736 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3737 TemplateArgument Arg = Args[I];
3738
3739 // If the parameter is a pack expansion, the argument must be a pack
3740 // whose only element is a pack expansion.
3741 if (Params->getParam(I)->isParameterPack()) {
3742 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3743 !Arg.pack_begin()->isPackExpansion())
3744 return false;
3745 Arg = Arg.pack_begin()->getPackExpansionPattern();
3746 }
3747
3748 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3749 return false;
3750 }
3751
3752 return true;
3753}
3754
3755/// Convert the parser's template argument list representation into our form.
3756static TemplateArgumentListInfo
3757makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3758 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3759 TemplateId.RAngleLoc);
3760 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3761 TemplateId.NumArgs);
3762 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3763 return TemplateArgs;
3764}
3765
3766template<typename PartialSpecDecl>
3767static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3768 if (Partial->getDeclContext()->isDependentContext())
3769 return;
3770
3771 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3772 // for non-substitution-failure issues?
3773 TemplateDeductionInfo Info(Partial->getLocation());
3774 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3775 return;
3776
3777 auto *Template = Partial->getSpecializedTemplate();
3778 S.Diag(Partial->getLocation(),
3779 diag::ext_partial_spec_not_more_specialized_than_primary)
3780 << isa<VarTemplateDecl>(Template);
3781
3782 if (Info.hasSFINAEDiagnostic()) {
3783 PartialDiagnosticAt Diag = {SourceLocation(),
3784 PartialDiagnostic::NullDiagnostic()};
3785 Info.takeSFINAEDiagnostic(Diag);
3786 SmallString<128> SFINAEArgString;
3787 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3788 S.Diag(Diag.first,
3789 diag::note_partial_spec_not_more_specialized_than_primary)
3790 << SFINAEArgString;
3791 }
3792
3793 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3794}
3795
3796static void
3797noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3798 const llvm::SmallBitVector &DeducibleParams) {
3799 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3800 if (!DeducibleParams[I]) {
3801 NamedDecl *Param = TemplateParams->getParam(I);
3802 if (Param->getDeclName())
3803 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3804 << Param->getDeclName();
3805 else
3806 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3807 << "(anonymous)";
3808 }
3809 }
3810}
3811
3812
3813template<typename PartialSpecDecl>
3814static void checkTemplatePartialSpecialization(Sema &S,
3815 PartialSpecDecl *Partial) {
3816 // C++1z [temp.class.spec]p8: (DR1495)
3817 // - The specialization shall be more specialized than the primary
3818 // template (14.5.5.2).
3819 checkMoreSpecializedThanPrimary(S, Partial);
3820
3821 // C++ [temp.class.spec]p8: (DR1315)
3822 // - Each template-parameter shall appear at least once in the
3823 // template-id outside a non-deduced context.
3824 // C++1z [temp.class.spec.match]p3 (P0127R2)
3825 // If the template arguments of a partial specialization cannot be
3826 // deduced because of the structure of its template-parameter-list
3827 // and the template-id, the program is ill-formed.
3828 auto *TemplateParams = Partial->getTemplateParameters();
3829 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3830 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3831 TemplateParams->getDepth(), DeducibleParams);
3832
3833 if (!DeducibleParams.all()) {
3834 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3835 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3836 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3837 << (NumNonDeducible > 1)
3838 << SourceRange(Partial->getLocation(),
3839 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3840 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3841 }
3842}
3843
3844void Sema::CheckTemplatePartialSpecialization(
3845 ClassTemplatePartialSpecializationDecl *Partial) {
3846 checkTemplatePartialSpecialization(*this, Partial);
3847}
3848
3849void Sema::CheckTemplatePartialSpecialization(
3850 VarTemplatePartialSpecializationDecl *Partial) {
3851 checkTemplatePartialSpecialization(*this, Partial);
3852}
3853
3854void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3855 // C++1z [temp.param]p11:
3856 // A template parameter of a deduction guide template that does not have a
3857 // default-argument shall be deducible from the parameter-type-list of the
3858 // deduction guide template.
3859 auto *TemplateParams = TD->getTemplateParameters();
3860 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3861 MarkDeducedTemplateParameters(TD, DeducibleParams);
3862 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3863 // A parameter pack is deducible (to an empty pack).
3864 auto *Param = TemplateParams->getParam(I);
3865 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3866 DeducibleParams[I] = true;
3867 }
3868
3869 if (!DeducibleParams.all()) {
3870 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3871 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3872 << (NumNonDeducible > 1);
3873 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3874 }
3875}
3876
3877DeclResult Sema::ActOnVarTemplateSpecialization(
3878 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3879 TemplateParameterList *TemplateParams, StorageClass SC,
3880 bool IsPartialSpecialization) {
3881 // D must be variable template id.
3882 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&((D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
"Variable template specialization is declared with a template it."
) ? static_cast<void> (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template it.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3883, __PRETTY_FUNCTION__))
3883 "Variable template specialization is declared with a template it.")((D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
"Variable template specialization is declared with a template it."
) ? static_cast<void> (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template it.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3883, __PRETTY_FUNCTION__))
;
3884
3885 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3886 TemplateArgumentListInfo TemplateArgs =
3887 makeTemplateArgumentListInfo(*this, *TemplateId);
3888 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3889 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3890 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3891
3892 TemplateName Name = TemplateId->Template.get();
3893
3894 // The template-id must name a variable template.
3895 VarTemplateDecl *VarTemplate =
3896 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3897 if (!VarTemplate) {
3898 NamedDecl *FnTemplate;
3899 if (auto *OTS = Name.getAsOverloadedTemplate())
3900 FnTemplate = *OTS->begin();
3901 else
3902 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3903 if (FnTemplate)
3904 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3905 << FnTemplate->getDeclName();
3906 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3907 << IsPartialSpecialization;
3908 }
3909
3910 // Check for unexpanded parameter packs in any of the template arguments.
3911 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3912 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3913 UPPC_PartialSpecialization))
3914 return true;
3915
3916 // Check that the template argument list is well-formed for this
3917 // template.
3918 SmallVector<TemplateArgument, 4> Converted;
3919 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3920 false, Converted))
3921 return true;
3922
3923 // Find the variable template (partial) specialization declaration that
3924 // corresponds to these arguments.
3925 if (IsPartialSpecialization) {
3926 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3927 TemplateArgs.size(), Converted))
3928 return true;
3929
3930 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3931 // also do them during instantiation.
3932 bool InstantiationDependent;
3933 if (!Name.isDependent() &&
3934 !TemplateSpecializationType::anyDependentTemplateArguments(
3935 TemplateArgs.arguments(),
3936 InstantiationDependent)) {
3937 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3938 << VarTemplate->getDeclName();
3939 IsPartialSpecialization = false;
3940 }
3941
3942 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3943 Converted)) {
3944 // C++ [temp.class.spec]p9b3:
3945 //
3946 // -- The argument list of the specialization shall not be identical
3947 // to the implicit argument list of the primary template.
3948 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3949 << /*variable template*/ 1
3950 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3951 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3952 // FIXME: Recover from this by treating the declaration as a redeclaration
3953 // of the primary template.
3954 return true;
3955 }
3956 }
3957
3958 void *InsertPos = nullptr;
3959 VarTemplateSpecializationDecl *PrevDecl = nullptr;
3960
3961 if (IsPartialSpecialization)
3962 // FIXME: Template parameter list matters too
3963 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3964 else
3965 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3966
3967 VarTemplateSpecializationDecl *Specialization = nullptr;
3968
3969 // Check whether we can declare a variable template specialization in
3970 // the current scope.
3971 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3972 TemplateNameLoc,
3973 IsPartialSpecialization))
3974 return true;
3975
3976 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3977 // Since the only prior variable template specialization with these
3978 // arguments was referenced but not declared, reuse that
3979 // declaration node as our own, updating its source location and
3980 // the list of outer template parameters to reflect our new declaration.
3981 Specialization = PrevDecl;
3982 Specialization->setLocation(TemplateNameLoc);
3983 PrevDecl = nullptr;
3984 } else if (IsPartialSpecialization) {
3985 // Create a new class template partial specialization declaration node.
3986 VarTemplatePartialSpecializationDecl *PrevPartial =
3987 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3988 VarTemplatePartialSpecializationDecl *Partial =
3989 VarTemplatePartialSpecializationDecl::Create(
3990 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3991 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3992 Converted, TemplateArgs);
3993
3994 if (!PrevPartial)
3995 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3996 Specialization = Partial;
3997
3998 // If we are providing an explicit specialization of a member variable
3999 // template specialization, make a note of that.
4000 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4001 PrevPartial->setMemberSpecialization();
4002
4003 CheckTemplatePartialSpecialization(Partial);
4004 } else {
4005 // Create a new class template specialization declaration node for
4006 // this explicit specialization or friend declaration.
4007 Specialization = VarTemplateSpecializationDecl::Create(
4008 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4009 VarTemplate, DI->getType(), DI, SC, Converted);
4010 Specialization->setTemplateArgsInfo(TemplateArgs);
4011
4012 if (!PrevDecl)
4013 VarTemplate->AddSpecialization(Specialization, InsertPos);
4014 }
4015
4016 // C++ [temp.expl.spec]p6:
4017 // If a template, a member template or the member of a class template is
4018 // explicitly specialized then that specialization shall be declared
4019 // before the first use of that specialization that would cause an implicit
4020 // instantiation to take place, in every translation unit in which such a
4021 // use occurs; no diagnostic is required.
4022 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4023 bool Okay = false;
4024 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4025 // Is there any previous explicit specialization declaration?
4026 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4027 Okay = true;
4028 break;
4029 }
4030 }
4031
4032 if (!Okay) {
4033 SourceRange Range(TemplateNameLoc, RAngleLoc);
4034 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4035 << Name << Range;
4036
4037 Diag(PrevDecl->getPointOfInstantiation(),
4038 diag::note_instantiation_required_here)
4039 << (PrevDecl->getTemplateSpecializationKind() !=
4040 TSK_ImplicitInstantiation);
4041 return true;
4042 }
4043 }
4044
4045 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4046 Specialization->setLexicalDeclContext(CurContext);
4047
4048 // Add the specialization into its lexical context, so that it can
4049 // be seen when iterating through the list of declarations in that
4050 // context. However, specializations are not found by name lookup.
4051 CurContext->addDecl(Specialization);
4052
4053 // Note that this is an explicit specialization.
4054 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4055
4056 if (PrevDecl) {
4057 // Check that this isn't a redefinition of this specialization,
4058 // merging with previous declarations.
4059 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
4060 forRedeclarationInCurContext());
4061 PrevSpec.addDecl(PrevDecl);
4062 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
4063 } else if (Specialization->isStaticDataMember() &&
4064 Specialization->isOutOfLine()) {
4065 Specialization->setAccess(VarTemplate->getAccess());
4066 }
4067
4068 return Specialization;
4069}
4070
4071namespace {
4072/// A partial specialization whose template arguments have matched
4073/// a given template-id.
4074struct PartialSpecMatchResult {
4075 VarTemplatePartialSpecializationDecl *Partial;
4076 TemplateArgumentList *Args;
4077};
4078} // end anonymous namespace
4079
4080DeclResult
4081Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4082 SourceLocation TemplateNameLoc,
4083 const TemplateArgumentListInfo &TemplateArgs) {
4084 assert(Template && "A variable template id without template?")((Template && "A variable template id without template?"
) ? static_cast<void> (0) : __assert_fail ("Template && \"A variable template id without template?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4084, __PRETTY_FUNCTION__))
;
4085
4086 // Check that the template argument list is well-formed for this template.
4087 SmallVector<TemplateArgument, 4> Converted;
4088 if (CheckTemplateArgumentList(
4089 Template, TemplateNameLoc,
4090 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4091 Converted))
4092 return true;
4093
4094 // Find the variable template specialization declaration that
4095 // corresponds to these arguments.
4096 void *InsertPos = nullptr;
4097 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
4098 Converted, InsertPos)) {
4099 checkSpecializationVisibility(TemplateNameLoc, Spec);
4100 // If we already have a variable template specialization, return it.
4101 return Spec;
4102 }
4103
4104 // This is the first time we have referenced this variable template
4105 // specialization. Create the canonical declaration and add it to
4106 // the set of specializations, based on the closest partial specialization
4107 // that it represents. That is,
4108 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4109 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
4110 Converted);
4111 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4112 bool AmbiguousPartialSpec = false;
4113 typedef PartialSpecMatchResult MatchResult;
4114 SmallVector<MatchResult, 4> Matched;
4115 SourceLocation PointOfInstantiation = TemplateNameLoc;
4116 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4117 /*ForTakingAddress=*/false);
4118
4119 // 1. Attempt to find the closest partial specialization that this
4120 // specializes, if any.
4121 // If any of the template arguments is dependent, then this is probably
4122 // a placeholder for an incomplete declarative context; which must be
4123 // complete by instantiation time. Thus, do not search through the partial
4124 // specializations yet.
4125 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4126 // Perhaps better after unification of DeduceTemplateArguments() and
4127 // getMoreSpecializedPartialSpecialization().
4128 bool InstantiationDependent = false;
4129 if (!TemplateSpecializationType::anyDependentTemplateArguments(
4130 TemplateArgs, InstantiationDependent)) {
4131
4132 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4133 Template->getPartialSpecializations(PartialSpecs);
4134
4135 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4136 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4137 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4138
4139 if (TemplateDeductionResult Result =
4140 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4141 // Store the failed-deduction information for use in diagnostics, later.
4142 // TODO: Actually use the failed-deduction info?
4143 FailedCandidates.addCandidate().set(
4144 DeclAccessPair::make(Template, AS_public), Partial,
4145 MakeDeductionFailureInfo(Context, Result, Info));
4146 (void)Result;
4147 } else {
4148 Matched.push_back(PartialSpecMatchResult());
4149 Matched.back().Partial = Partial;
4150 Matched.back().Args = Info.take();
4151 }
4152 }
4153
4154 if (Matched.size() >= 1) {
4155 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4156 if (Matched.size() == 1) {
4157 // -- If exactly one matching specialization is found, the
4158 // instantiation is generated from that specialization.
4159 // We don't need to do anything for this.
4160 } else {
4161 // -- If more than one matching specialization is found, the
4162 // partial order rules (14.5.4.2) are used to determine
4163 // whether one of the specializations is more specialized
4164 // than the others. If none of the specializations is more
4165 // specialized than all of the other matching
4166 // specializations, then the use of the variable template is
4167 // ambiguous and the program is ill-formed.
4168 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4169 PEnd = Matched.end();
4170 P != PEnd; ++P) {
4171 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4172 PointOfInstantiation) ==
4173 P->Partial)
4174 Best = P;
4175 }
4176
4177 // Determine if the best partial specialization is more specialized than
4178 // the others.
4179 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4180 PEnd = Matched.end();
4181 P != PEnd; ++P) {
4182 if (P != Best && getMoreSpecializedPartialSpecialization(
4183 P->Partial, Best->Partial,
4184 PointOfInstantiation) != Best->Partial) {
4185 AmbiguousPartialSpec = true;
4186 break;
4187 }
4188 }
4189 }
4190
4191 // Instantiate using the best variable template partial specialization.
4192 InstantiationPattern = Best->Partial;
4193 InstantiationArgs = Best->Args;
4194 } else {
4195 // -- If no match is found, the instantiation is generated
4196 // from the primary template.
4197 // InstantiationPattern = Template->getTemplatedDecl();
4198 }
4199 }
4200
4201 // 2. Create the canonical declaration.
4202 // Note that we do not instantiate a definition until we see an odr-use
4203 // in DoMarkVarDeclReferenced().
4204 // FIXME: LateAttrs et al.?
4205 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4206 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4207 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4208 if (!Decl)
4209 return true;
4210
4211 if (AmbiguousPartialSpec) {
4212 // Partial ordering did not produce a clear winner. Complain.
4213 Decl->setInvalidDecl();
4214 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4215 << Decl;
4216
4217 // Print the matching partial specializations.
4218 for (MatchResult P : Matched)
4219 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4220 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4221 *P.Args);
4222 return true;
4223 }
4224
4225 if (VarTemplatePartialSpecializationDecl *D =
4226 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4227 Decl->setInstantiationOf(D, InstantiationArgs);
4228
4229 checkSpecializationVisibility(TemplateNameLoc, Decl);
4230
4231 assert(Decl && "No variable template specialization?")((Decl && "No variable template specialization?") ? static_cast
<void> (0) : __assert_fail ("Decl && \"No variable template specialization?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4231, __PRETTY_FUNCTION__))
;
4232 return Decl;
4233}
4234
4235ExprResult
4236Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4237 const DeclarationNameInfo &NameInfo,
4238 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4239 const TemplateArgumentListInfo *TemplateArgs) {
4240
4241 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4242 *TemplateArgs);
4243 if (Decl.isInvalid())
4244 return ExprError();
4245
4246 VarDecl *Var = cast<VarDecl>(Decl.get());
4247 if (!Var->getTemplateSpecializationKind())
4248 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4249 NameInfo.getLoc());
4250
4251 // Build an ordinary singleton decl ref.
4252 return BuildDeclarationNameExpr(SS, NameInfo, Var,
4253 /*FoundD=*/nullptr, TemplateArgs);
4254}
4255
4256void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4257 SourceLocation Loc) {
4258 Diag(Loc, diag::err_template_missing_args)
4259 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4260 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4261 Diag(TD->getLocation(), diag::note_template_decl_here)
4262 << TD->getTemplateParameters()->getSourceRange();
4263 }
4264}
4265
4266ExprResult
4267Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4268 const DeclarationNameInfo &NameInfo,
4269 ConceptDecl *Template,
4270 SourceLocation TemplateLoc,
4271 const TemplateArgumentListInfo *TemplateArgs) {
4272 // TODO: Do concept specialization here.
4273 Diag(NameInfo.getBeginLoc(), diag::err_concept_not_implemented) <<
4274 "concept specialization";
4275 return ExprError();
4276}
4277
4278ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4279 SourceLocation TemplateKWLoc,
4280 LookupResult &R,
4281 bool RequiresADL,
4282 const TemplateArgumentListInfo *TemplateArgs) {
4283 // FIXME: Can we do any checking at this point? I guess we could check the
4284 // template arguments that we have against the template name, if the template
4285 // name refers to a single template. That's not a terribly common case,
4286 // though.
4287 // foo<int> could identify a single function unambiguously
4288 // This approach does NOT work, since f<int>(1);
4289 // gets resolved prior to resorting to overload resolution
4290 // i.e., template<class T> void f(double);
4291 // vs template<class T, class U> void f(U);
4292
4293 // These should be filtered out by our callers.
4294 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid")((!R.isAmbiguous() && "ambiguous lookup when building templateid"
) ? static_cast<void> (0) : __assert_fail ("!R.isAmbiguous() && \"ambiguous lookup when building templateid\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4294, __PRETTY_FUNCTION__))
;
4295
4296 // Non-function templates require a template argument list.
4297 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4298 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4299 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4300 return ExprError();
4301 }
4302 }
4303
4304 auto AnyDependentArguments = [&]() -> bool {
4305 bool InstantiationDependent;
4306 return TemplateArgs &&
4307 TemplateSpecializationType::anyDependentTemplateArguments(
4308 *TemplateArgs, InstantiationDependent);
4309 };
4310
4311 // In C++1y, check variable template ids.
4312 if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
4313 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4314 R.getAsSingle<VarTemplateDecl>(),
4315 TemplateKWLoc, TemplateArgs);
4316 }
4317
4318 if (R.getAsSingle<ConceptDecl>() && !AnyDependentArguments()) {
4319 return CheckConceptTemplateId(SS, R.getLookupNameInfo(),
4320 R.getAsSingle<ConceptDecl>(),
4321 TemplateKWLoc, TemplateArgs);
4322 }
4323
4324 // We don't want lookup warnings at this point.
4325 R.suppressDiagnostics();
4326
4327 UnresolvedLookupExpr *ULE
4328 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
4329 SS.getWithLocInContext(Context),
4330 TemplateKWLoc,
4331 R.getLookupNameInfo(),
4332 RequiresADL, TemplateArgs,
4333 R.begin(), R.end());
4334
4335 return ULE;
4336}
4337
4338// We actually only call this from template instantiation.
4339ExprResult
4340Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4341 SourceLocation TemplateKWLoc,
4342 const DeclarationNameInfo &NameInfo,
4343 const TemplateArgumentListInfo *TemplateArgs) {
4344
4345 assert(TemplateArgs || TemplateKWLoc.isValid())((TemplateArgs || TemplateKWLoc.isValid()) ? static_cast<void
> (0) : __assert_fail ("TemplateArgs || TemplateKWLoc.isValid()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4345, __PRETTY_FUNCTION__))
;
4346 DeclContext *DC;
4347 if (!(DC = computeDeclContext(SS, false)) ||
4348 DC->isDependentContext() ||
4349 RequireCompleteDeclContext(SS, DC))
4350 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4351
4352 bool MemberOfUnknownSpecialization;
4353 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4354 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4355 /*Entering*/false, MemberOfUnknownSpecialization,
4356 TemplateKWLoc))
4357 return ExprError();
4358
4359 if (R.isAmbiguous())
4360 return ExprError();
4361
4362 if (R.empty()) {
4363 Diag(NameInfo.getLoc(), diag::err_no_member)
4364 << NameInfo.getName() << DC << SS.getRange();
4365 return ExprError();
4366 }
4367
4368 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4369 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4370 << SS.getScopeRep()
4371 << NameInfo.getName().getAsString() << SS.getRange();
4372 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4373 return ExprError();
4374 }
4375
4376 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4377}
4378
4379/// Form a dependent template name.
4380///
4381/// This action forms a dependent template name given the template
4382/// name and its (presumably dependent) scope specifier. For
4383/// example, given "MetaFun::template apply", the scope specifier \p
4384/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4385/// of the "template" keyword, and "apply" is the \p Name.
4386TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
4387 CXXScopeSpec &SS,
4388 SourceLocation TemplateKWLoc,
4389 const UnqualifiedId &Name,
4390 ParsedType ObjectType,
4391 bool EnteringContext,
4392 TemplateTy &Result,
4393 bool AllowInjectedClassName) {
4394 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4395 Diag(TemplateKWLoc,
4396 getLangOpts().CPlusPlus11 ?
4397 diag::warn_cxx98_compat_template_outside_of_template :
4398 diag::ext_template_outside_of_template)
4399 << FixItHint::CreateRemoval(TemplateKWLoc);
4400
4401 DeclContext *LookupCtx = nullptr;
4402 if (SS.isSet())
4403 LookupCtx = computeDeclContext(SS, EnteringContext);
4404 if (!LookupCtx && ObjectType)
4405 LookupCtx = computeDeclContext(ObjectType.get());
4406 if (LookupCtx) {
4407 // C++0x [temp.names]p5:
4408 // If a name prefixed by the keyword template is not the name of
4409 // a template, the program is ill-formed. [Note: the keyword
4410 // template may not be applied to non-template members of class
4411 // templates. -end note ] [ Note: as is the case with the
4412 // typename prefix, the template prefix is allowed in cases
4413 // where it is not strictly necessary; i.e., when the
4414 // nested-name-specifier or the expression on the left of the ->
4415 // or . is not dependent on a template-parameter, or the use
4416 // does not appear in the scope of a template. -end note]
4417 //
4418 // Note: C++03 was more strict here, because it banned the use of
4419 // the "template" keyword prior to a template-name that was not a
4420 // dependent name. C++ DR468 relaxed this requirement (the
4421 // "template" keyword is now permitted). We follow the C++0x
4422 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4423 bool MemberOfUnknownSpecialization;
4424 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4425 ObjectType, EnteringContext, Result,
4426 MemberOfUnknownSpecialization);
4427 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
4428 // This is a dependent template. Handle it below.
4429 } else if (TNK == TNK_Non_template) {
4430 // Do the lookup again to determine if this is a "nothing found" case or
4431 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4432 // need to do this.
4433 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4434 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4435 LookupOrdinaryName);
4436 bool MOUS;
4437 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
4438 MOUS, TemplateKWLoc) && !R.isAmbiguous())
4439 Diag(Name.getBeginLoc(), diag::err_no_member)
4440 << DNI.getName() << LookupCtx << SS.getRange();
4441 return TNK_Non_template;
4442 } else {
4443 // We found something; return it.
4444 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4445 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4446 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4447 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4448 // C++14 [class.qual]p2:
4449 // In a lookup in which function names are not ignored and the
4450 // nested-name-specifier nominates a class C, if the name specified
4451 // [...] is the injected-class-name of C, [...] the name is instead
4452 // considered to name the constructor
4453 //
4454 // We don't get here if naming the constructor would be valid, so we
4455 // just reject immediately and recover by treating the
4456 // injected-class-name as naming the template.
4457 Diag(Name.getBeginLoc(),
4458 diag::ext_out_of_line_qualified_id_type_names_constructor)
4459 << Name.Identifier
4460 << 0 /*injected-class-name used as template name*/
4461 << 1 /*'template' keyword was used*/;
4462 }
4463 return TNK;
4464 }
4465 }
4466
4467 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4468
4469 switch (Name.getKind()) {
4470 case UnqualifiedIdKind::IK_Identifier:
4471 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4472 Name.Identifier));
4473 return TNK_Dependent_template_name;
4474
4475 case UnqualifiedIdKind::IK_OperatorFunctionId:
4476 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4477 Name.OperatorFunctionId.Operator));
4478 return TNK_Function_template;
4479
4480 case UnqualifiedIdKind::IK_LiteralOperatorId:
4481 llvm_unreachable("literal operator id cannot have a dependent scope")::llvm::llvm_unreachable_internal("literal operator id cannot have a dependent scope"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4481)
;
4482
4483 default:
4484 break;
4485 }
4486
4487 Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
4488 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4489 << TemplateKWLoc;
4490 return TNK_Non_template;
4491}
4492
4493bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
4494 TemplateArgumentLoc &AL,
4495 SmallVectorImpl<TemplateArgument> &Converted) {
4496 const TemplateArgument &Arg = AL.getArgument();
4497 QualType ArgType;
4498 TypeSourceInfo *TSI = nullptr;
4499
4500 // Check template type parameter.
4501 switch(Arg.getKind()) {
4502 case TemplateArgument::Type:
4503 // C++ [temp.arg.type]p1:
4504 // A template-argument for a template-parameter which is a
4505 // type shall be a type-id.
4506 ArgType = Arg.getAsType();
4507 TSI = AL.getTypeSourceInfo();
4508 break;
4509 case TemplateArgument::Template:
4510 case TemplateArgument::TemplateExpansion: {
4511 // We have a template type parameter but the template argument
4512 // is a template without any arguments.
4513 SourceRange SR = AL.getSourceRange();
4514 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
4515 diagnoseMissingTemplateArguments(Name, SR.getEnd());
4516 return true;
4517 }
4518 case TemplateArgument::Expression: {
4519 // We have a template type parameter but the template argument is an
4520 // expression; see if maybe it is missing the "typename" keyword.
4521 CXXScopeSpec SS;
4522 DeclarationNameInfo NameInfo;
4523
4524 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4525 SS.Adopt(ArgExpr->getQualifierLoc());
4526 NameInfo = ArgExpr->getNameInfo();
4527 } else if (DependentScopeDeclRefExpr *ArgExpr =
4528 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4529 SS.Adopt(ArgExpr->getQualifierLoc());
4530 NameInfo = ArgExpr->getNameInfo();
4531 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4532 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4533 if (ArgExpr->isImplicitAccess()) {
4534 SS.Adopt(ArgExpr->getQualifierLoc());
4535 NameInfo = ArgExpr->getMemberNameInfo();
4536 }
4537 }
4538
4539 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4540 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4541 LookupParsedName(Result, CurScope, &SS);
4542
4543 if (Result.getAsSingle<TypeDecl>() ||
4544 Result.getResultKind() ==
4545 LookupResult::NotFoundInCurrentInstantiation) {
4546 // Suggest that the user add 'typename' before the NNS.
4547 SourceLocation Loc = AL.getSourceRange().getBegin();
4548 Diag(Loc, getLangOpts().MSVCCompat
4549 ? diag::ext_ms_template_type_arg_missing_typename
4550 : diag::err_template_arg_must_be_type_suggest)
4551 << FixItHint::CreateInsertion(Loc, "typename ");
4552 Diag(Param->getLocation(), diag::note_template_param_here);
4553
4554 // Recover by synthesizing a type using the location information that we
4555 // already have.
4556 ArgType =
4557 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4558 TypeLocBuilder TLB;
4559 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4560 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4561 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4562 TL.setNameLoc(NameInfo.getLoc());
4563 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4564
4565 // Overwrite our input TemplateArgumentLoc so that we can recover
4566 // properly.
4567 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4568 TemplateArgumentLocInfo(TSI));
4569
4570 break;
4571 }
4572 }
4573 // fallthrough
4574 LLVM_FALLTHROUGH[[gnu::fallthrough]];
4575 }
4576 default: {
4577 // We have a template type parameter but the template argument
4578 // is not a type.
4579 SourceRange SR = AL.getSourceRange();
4580 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4581 Diag(Param->getLocation(), diag::note_template_param_here);
4582
4583 return true;
4584 }
4585 }
4586
4587 if (CheckTemplateArgument(Param, TSI))
4588 return true;
4589
4590 // Add the converted template type argument.
4591 ArgType = Context.getCanonicalType(ArgType);
4592
4593 // Objective-C ARC:
4594 // If an explicitly-specified template argument type is a lifetime type
4595 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4596 if (getLangOpts().ObjCAutoRefCount &&
4597 ArgType->isObjCLifetimeType() &&
4598 !ArgType.getObjCLifetime()) {
4599 Qualifiers Qs;
4600 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4601 ArgType = Context.getQualifiedType(ArgType, Qs);
4602 }
4603
4604 Converted.push_back(TemplateArgument(ArgType));
4605 return false;
4606}
4607
4608/// Substitute template arguments into the default template argument for
4609/// the given template type parameter.
4610///
4611/// \param SemaRef the semantic analysis object for which we are performing
4612/// the substitution.
4613///
4614/// \param Template the template that we are synthesizing template arguments
4615/// for.
4616///
4617/// \param TemplateLoc the location of the template name that started the
4618/// template-id we are checking.
4619///
4620/// \param RAngleLoc the location of the right angle bracket ('>') that
4621/// terminates the template-id.
4622///
4623/// \param Param the template template parameter whose default we are
4624/// substituting into.
4625///
4626/// \param Converted the list of template arguments provided for template
4627/// parameters that precede \p Param in the template parameter list.
4628/// \returns the substituted template argument, or NULL if an error occurred.
4629static TypeSourceInfo *
4630SubstDefaultTemplateArgument(Sema &SemaRef,
4631 TemplateDecl *Template,
4632 SourceLocation TemplateLoc,
4633 SourceLocation RAngleLoc,
4634 TemplateTypeParmDecl *Param,
4635 SmallVectorImpl<TemplateArgument> &Converted) {
4636 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4637
4638 // If the argument type is dependent, instantiate it now based
4639 // on the previously-computed template arguments.
4640 if (ArgType->getType()->isInstantiationDependentType()) {
4641 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4642 Param, Template, Converted,
4643 SourceRange(TemplateLoc, RAngleLoc));
4644 if (Inst.isInvalid())
4645 return nullptr;
4646
4647 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4648
4649 // Only substitute for the innermost template argument list.
4650 MultiLevelTemplateArgumentList TemplateArgLists;
4651 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4652 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4653 TemplateArgLists.addOuterTemplateArguments(None);
4654
4655 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4656 ArgType =
4657 SemaRef.SubstType(ArgType, TemplateArgLists,
4658 Param->getDefaultArgumentLoc(), Param->getDeclName());
4659 }
4660
4661 return ArgType;
4662}
4663
4664/// Substitute template arguments into the default template argument for
4665/// the given non-type template parameter.
4666///
4667/// \param SemaRef the semantic analysis object for which we are performing
4668/// the substitution.
4669///
4670/// \param Template the template that we are synthesizing template arguments
4671/// for.
4672///
4673/// \param TemplateLoc the location of the template name that started the
4674/// template-id we are checking.
4675///
4676/// \param RAngleLoc the location of the right angle bracket ('>') that
4677/// terminates the template-id.
4678///
4679/// \param Param the non-type template parameter whose default we are
4680/// substituting into.
4681///
4682/// \param Converted the list of template arguments provided for template
4683/// parameters that precede \p Param in the template parameter list.
4684///
4685/// \returns the substituted template argument, or NULL if an error occurred.
4686static ExprResult
4687SubstDefaultTemplateArgument(Sema &SemaRef,
4688 TemplateDecl *Template,
4689 SourceLocation TemplateLoc,
4690 SourceLocation RAngleLoc,
4691 NonTypeTemplateParmDecl *Param,
4692 SmallVectorImpl<TemplateArgument> &Converted) {
4693 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4694 Param, Template, Converted,
4695 SourceRange(TemplateLoc, RAngleLoc));
4696 if (Inst.isInvalid())
4697 return ExprError();
4698
4699 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4700
4701 // Only substitute for the innermost template argument list.
4702 MultiLevelTemplateArgumentList TemplateArgLists;
4703 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4704 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4705 TemplateArgLists.addOuterTemplateArguments(None);
4706
4707 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4708 EnterExpressionEvaluationContext ConstantEvaluated(
4709 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4710 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4711}
4712
4713/// Substitute template arguments into the default template argument for
4714/// the given template template parameter.
4715///
4716/// \param SemaRef the semantic analysis object for which we are performing
4717/// the substitution.
4718///
4719/// \param Template the template that we are synthesizing template arguments
4720/// for.
4721///
4722/// \param TemplateLoc the location of the template name that started the
4723/// template-id we are checking.
4724///
4725/// \param RAngleLoc the location of the right angle bracket ('>') that
4726/// terminates the template-id.
4727///
4728/// \param Param the template template parameter whose default we are
4729/// substituting into.
4730///
4731/// \param Converted the list of template arguments provided for template
4732/// parameters that precede \p Param in the template parameter list.
4733///
4734/// \param QualifierLoc Will be set to the nested-name-specifier (with
4735/// source-location information) that precedes the template name.
4736///
4737/// \returns the substituted template argument, or NULL if an error occurred.
4738static TemplateName
4739SubstDefaultTemplateArgument(Sema &SemaRef,
4740 TemplateDecl *Template,
4741 SourceLocation TemplateLoc,
4742 SourceLocation RAngleLoc,
4743 TemplateTemplateParmDecl *Param,
4744 SmallVectorImpl<TemplateArgument> &Converted,
4745 NestedNameSpecifierLoc &QualifierLoc) {
4746 Sema::InstantiatingTemplate Inst(
4747 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4748 SourceRange(TemplateLoc, RAngleLoc));
4749 if (Inst.isInvalid())
4750 return TemplateName();
4751
4752 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4753
4754 // Only substitute for the innermost template argument list.
4755 MultiLevelTemplateArgumentList TemplateArgLists;
4756 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4757 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4758 TemplateArgLists.addOuterTemplateArguments(None);
4759
4760 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4761 // Substitute into the nested-name-specifier first,
4762 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4763 if (QualifierLoc) {
4764 QualifierLoc =
4765 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4766 if (!QualifierLoc)
4767 return TemplateName();
4768 }
4769
4770 return SemaRef.SubstTemplateName(
4771 QualifierLoc,
4772 Param->getDefaultArgument().getArgument().getAsTemplate(),
4773 Param->getDefaultArgument().getTemplateNameLoc(),
4774 TemplateArgLists);
4775}
4776
4777/// If the given template parameter has a default template
4778/// argument, substitute into that default template argument and
4779/// return the corresponding template argument.
4780TemplateArgumentLoc
4781Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4782 SourceLocation TemplateLoc,
4783 SourceLocation RAngleLoc,
4784 Decl *Param,
4785 SmallVectorImpl<TemplateArgument>
4786 &Converted,
4787 bool &HasDefaultArg) {
4788 HasDefaultArg = false;
4789
4790 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4791 if (!hasVisibleDefaultArgument(TypeParm))
4792 return TemplateArgumentLoc();
4793
4794 HasDefaultArg = true;
4795 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4796 TemplateLoc,
4797 RAngleLoc,
4798 TypeParm,
4799 Converted);
4800 if (DI)
4801 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4802
4803 return TemplateArgumentLoc();
4804 }
4805
4806 if (NonTypeTemplateParmDecl *NonTypeParm
4807 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4808 if (!hasVisibleDefaultArgument(NonTypeParm))
4809 return TemplateArgumentLoc();
4810
4811 HasDefaultArg = true;
4812 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4813 TemplateLoc,
4814 RAngleLoc,
4815 NonTypeParm,
4816 Converted);
4817 if (Arg.isInvalid())
4818 return TemplateArgumentLoc();
4819
4820 Expr *ArgE = Arg.getAs<Expr>();
4821 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4822 }
4823
4824 TemplateTemplateParmDecl *TempTempParm
4825 = cast<TemplateTemplateParmDecl>(Param);
4826 if (!hasVisibleDefaultArgument(TempTempParm))
4827 return TemplateArgumentLoc();
4828
4829 HasDefaultArg = true;
4830 NestedNameSpecifierLoc QualifierLoc;
4831 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4832 TemplateLoc,
4833 RAngleLoc,
4834 TempTempParm,
4835 Converted,
4836 QualifierLoc);
4837 if (TName.isNull())
4838 return TemplateArgumentLoc();
4839
4840 return TemplateArgumentLoc(TemplateArgument(TName),
4841 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4842 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4843}
4844
4845/// Convert a template-argument that we parsed as a type into a template, if
4846/// possible. C++ permits injected-class-names to perform dual service as
4847/// template template arguments and as template type arguments.
4848static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4849 // Extract and step over any surrounding nested-name-specifier.
4850 NestedNameSpecifierLoc QualLoc;
4851 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4852 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4853 return TemplateArgumentLoc();
4854
4855 QualLoc = ETLoc.getQualifierLoc();
4856 TLoc = ETLoc.getNamedTypeLoc();
4857 }
4858
4859 // If this type was written as an injected-class-name, it can be used as a
4860 // template template argument.
4861 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4862 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4863 QualLoc, InjLoc.getNameLoc());
4864
4865 // If this type was written as an injected-class-name, it may have been
4866 // converted to a RecordType during instantiation. If the RecordType is
4867 // *not* wrapped in a TemplateSpecializationType and denotes a class
4868 // template specialization, it must have come from an injected-class-name.
4869 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4870 if (auto *CTSD =
4871 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4872 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4873 QualLoc, RecLoc.getNameLoc());
4874
4875 return TemplateArgumentLoc();
4876}
4877
4878/// Check that the given template argument corresponds to the given
4879/// template parameter.
4880///
4881/// \param Param The template parameter against which the argument will be
4882/// checked.
4883///
4884/// \param Arg The template argument, which may be updated due to conversions.
4885///
4886/// \param Template The template in which the template argument resides.
4887///
4888/// \param TemplateLoc The location of the template name for the template
4889/// whose argument list we're matching.
4890///
4891/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4892/// the template argument list.
4893///
4894/// \param ArgumentPackIndex The index into the argument pack where this
4895/// argument will be placed. Only valid if the parameter is a parameter pack.
4896///
4897/// \param Converted The checked, converted argument will be added to the
4898/// end of this small vector.
4899///
4900/// \param CTAK Describes how we arrived at this particular template argument:
4901/// explicitly written, deduced, etc.
4902///
4903/// \returns true on error, false otherwise.
4904bool Sema::CheckTemplateArgument(NamedDecl *Param,
4905 TemplateArgumentLoc &Arg,
4906 NamedDecl *Template,
4907 SourceLocation TemplateLoc,
4908 SourceLocation RAngleLoc,
4909 unsigned ArgumentPackIndex,
4910 SmallVectorImpl<TemplateArgument> &Converted,
4911 CheckTemplateArgumentKind CTAK) {
4912 // Check template type parameters.
4913 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4914 return CheckTemplateTypeArgument(TTP, Arg, Converted);
4915
4916 // Check non-type template parameters.
4917 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4918 // Do substitution on the type of the non-type template parameter
4919 // with the template arguments we've seen thus far. But if the
4920 // template has a dependent context then we cannot substitute yet.
4921 QualType NTTPType = NTTP->getType();
4922 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4923 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4924
4925 // FIXME: Do we need to substitute into parameters here if they're
4926 // instantiation-dependent but not dependent?
4927 if (NTTPType->isDependentType() &&
4928 !isa<TemplateTemplateParmDecl>(Template) &&
4929 !Template->getDeclContext()->isDependentContext()) {
4930 // Do substitution on the type of the non-type template parameter.
4931 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4932 NTTP, Converted,
4933 SourceRange(TemplateLoc, RAngleLoc));
4934 if (Inst.isInvalid())
4935 return true;
4936
4937 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
4938 Converted);
4939
4940 // If the parameter is a pack expansion, expand this slice of the pack.
4941 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
4942 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
4943 ArgumentPackIndex);
4944 NTTPType = SubstType(PET->getPattern(),
4945 MultiLevelTemplateArgumentList(TemplateArgs),
4946 NTTP->getLocation(),
4947 NTTP->getDeclName());
4948 } else {
4949 NTTPType = SubstType(NTTPType,
4950 MultiLevelTemplateArgumentList(TemplateArgs),
4951 NTTP->getLocation(),
4952 NTTP->getDeclName());
4953 }
4954
4955 // If that worked, check the non-type template parameter type
4956 // for validity.
4957 if (!NTTPType.isNull())
4958 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4959 NTTP->getLocation());
4960 if (NTTPType.isNull())
4961 return true;
4962 }
4963
4964 switch (Arg.getArgument().getKind()) {
4965 case TemplateArgument::Null:
4966 llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4966)
;
4967
4968 case TemplateArgument::Expression: {
4969 TemplateArgument Result;
4970 unsigned CurSFINAEErrors = NumSFINAEErrors;
4971 ExprResult Res =
4972 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4973 Result, CTAK);
4974 if (Res.isInvalid())
4975 return true;
4976 // If the current template argument causes an error, give up now.
4977 if (CurSFINAEErrors < NumSFINAEErrors)
4978 return true;
4979
4980 // If the resulting expression is new, then use it in place of the
4981 // old expression in the template argument.
4982 if (Res.get() != Arg.getArgument().getAsExpr()) {
4983 TemplateArgument TA(Res.get());
4984 Arg = TemplateArgumentLoc(TA, Res.get());
4985 }
4986
4987 Converted.push_back(Result);
4988 break;
4989 }
4990
4991 case TemplateArgument::Declaration:
4992 case TemplateArgument::Integral:
4993 case TemplateArgument::NullPtr:
4994 // We've already checked this template argument, so just copy
4995 // it to the list of converted arguments.
4996 Converted.push_back(Arg.getArgument());
4997 break;
4998
4999 case TemplateArgument::Template:
5000 case TemplateArgument::TemplateExpansion:
5001 // We were given a template template argument. It may not be ill-formed;
5002 // see below.
5003 if (DependentTemplateName *DTN
5004 = Arg.getArgument().getAsTemplateOrTemplatePattern()
5005 .getAsDependentTemplateName()) {
5006 // We have a template argument such as \c T::template X, which we
5007 // parsed as a template template argument. However, since we now
5008 // know that we need a non-type template argument, convert this
5009 // template name into an expression.
5010
5011 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5012 Arg.getTemplateNameLoc());
5013
5014 CXXScopeSpec SS;
5015 SS.Adopt(Arg.getTemplateQualifierLoc());
5016 // FIXME: the template-template arg was a DependentTemplateName,
5017 // so it was provided with a template keyword. However, its source
5018 // location is not stored in the template argument structure.
5019 SourceLocation TemplateKWLoc;
5020 ExprResult E = DependentScopeDeclRefExpr::Create(
5021 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5022 nullptr);
5023
5024 // If we parsed the template argument as a pack expansion, create a
5025 // pack expansion expression.
5026 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
5027 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5028 if (E.isInvalid())
5029 return true;
5030 }
5031
5032 TemplateArgument Result;
5033 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
5034 if (E.isInvalid())
5035 return true;
5036
5037 Converted.push_back(Result);
5038 break;
5039 }
5040
5041 // We have a template argument that actually does refer to a class
5042 // template, alias template, or template template parameter, and
5043 // therefore cannot be a non-type template argument.
5044 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5045 << Arg.getSourceRange();
5046
5047 Diag(Param->getLocation(), diag::note_template_param_here);
5048 return true;
5049
5050 case TemplateArgument::Type: {
5051 // We have a non-type template parameter but the template
5052 // argument is a type.
5053
5054 // C++ [temp.arg]p2:
5055 // In a template-argument, an ambiguity between a type-id and
5056 // an expression is resolved to a type-id, regardless of the
5057 // form of the corresponding template-parameter.
5058 //
5059 // We warn specifically about this case, since it can be rather
5060 // confusing for users.
5061 QualType T = Arg.getArgument().getAsType();
5062 SourceRange SR = Arg.getSourceRange();
5063 if (T->isFunctionType())
5064 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5065 else
5066 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5067 Diag(Param->getLocation(), diag::note_template_param_here);
5068 return true;
5069 }
5070
5071 case TemplateArgument::Pack:
5072 llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5072)
;
5073 }
5074
5075 return false;
5076 }
5077
5078
5079 // Check template template parameters.
5080 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5081
5082 TemplateParameterList *Params = TempParm->getTemplateParameters();
5083 if (TempParm->isExpandedParameterPack())
5084 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5085
5086 // Substitute into the template parameter list of the template
5087 // template parameter, since previously-supplied template arguments
5088 // may appear within the template template parameter.
5089 //
5090 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5091 {
5092 // Set up a template instantiation context.
5093 LocalInstantiationScope Scope(*this);
5094 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
5095 TempParm, Converted,
5096 SourceRange(TemplateLoc, RAngleLoc));
5097 if (Inst.isInvalid())
5098 return true;
5099
5100 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
5101 Params = SubstTemplateParams(Params, CurContext,
5102 MultiLevelTemplateArgumentList(TemplateArgs));
5103 if (!Params)
5104 return true;
5105 }
5106
5107 // C++1z [temp.local]p1: (DR1004)
5108 // When [the injected-class-name] is used [...] as a template-argument for
5109 // a template template-parameter [...] it refers to the class template
5110 // itself.
5111 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5112 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5113 Arg.getTypeSourceInfo()->getTypeLoc());
5114 if (!ConvertedArg.getArgument().isNull())
5115 Arg = ConvertedArg;
5116 }
5117
5118 switch (Arg.getArgument().getKind()) {
5119 case TemplateArgument::Null:
5120 llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5120)
;
5121
5122 case TemplateArgument::Template:
5123 case TemplateArgument::TemplateExpansion:
5124 if (CheckTemplateTemplateArgument(Params, Arg))
5125 return true;
5126
5127 Converted.push_back(Arg.getArgument());
5128 break;
5129
5130 case TemplateArgument::Expression:
5131 case TemplateArgument::Type:
5132 // We have a template template parameter but the template
5133 // argument does not refer to a template.
5134 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5135 << getLangOpts().CPlusPlus11;
5136 return true;
5137
5138 case TemplateArgument::Declaration:
5139 llvm_unreachable("Declaration argument with template template parameter")::llvm::llvm_unreachable_internal("Declaration argument with template template parameter"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5139)
;
5140 case TemplateArgument::Integral:
5141 llvm_unreachable("Integral argument with template template parameter")::llvm::llvm_unreachable_internal("Integral argument with template template parameter"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5141)
;
5142 case TemplateArgument::NullPtr:
5143 llvm_unreachable("Null pointer argument with template template parameter")::llvm::llvm_unreachable_internal("Null pointer argument with template template parameter"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5143)
;
5144
5145 case TemplateArgument::Pack:
5146 llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5146)
;
5147 }
5148
5149 return false;
5150}
5151
5152/// Check whether the template parameter is a pack expansion, and if so,
5153/// determine the number of parameters produced by that expansion. For instance:
5154///
5155/// \code
5156/// template<typename ...Ts> struct A {
5157/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
5158/// };
5159/// \endcode
5160///
5161/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
5162/// is not a pack expansion, so returns an empty Optional.
5163static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
5164 if (NonTypeTemplateParmDecl *NTTP
5165 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5166 if (NTTP->isExpandedParameterPack())
5167 return NTTP->getNumExpansionTypes();
5168 }
5169
5170 if (TemplateTemplateParmDecl *TTP
5171 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
5172 if (TTP->isExpandedParameterPack())
5173 return TTP->getNumExpansionTemplateParameters();
5174 }
5175
5176 return None;
5177}
5178
5179/// Diagnose a missing template argument.
5180template<typename TemplateParmDecl>
5181static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5182 TemplateDecl *TD,
5183 const TemplateParmDecl *D,
5184 TemplateArgumentListInfo &Args) {
5185 // Dig out the most recent declaration of the template parameter; there may be
5186 // declarations of the template that are more recent than TD.
5187 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5188 ->getTemplateParameters()
5189 ->getParam(D->getIndex()));
5190
5191 // If there's a default argument that's not visible, diagnose that we're
5192 // missing a module import.
5193 llvm::SmallVector<Module*, 8> Modules;
5194 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5195 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5196 D->getDefaultArgumentLoc(), Modules,
5197 Sema::MissingImportKind::DefaultArgument,
5198 /*Recover*/true);
5199 return true;
5200 }
5201
5202 // FIXME: If there's a more recent default argument that *is* visible,
5203 // diagnose that it was declared too late.
5204
5205 TemplateParameterList *Params = TD->getTemplateParameters();
5206
5207 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5208 << /*not enough args*/0
5209 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5210 << TD;
5211 S.Diag(TD->getLocation(), diag::note_template_decl_here)
5212 << Params->getSourceRange();
5213 return true;
5214}
5215
5216/// Check that the given template argument list is well-formed
5217/// for specializing the given template.
5218bool Sema::CheckTemplateArgumentList(
5219 TemplateDecl *Template, SourceLocation TemplateLoc,
5220 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5221 SmallVectorImpl<TemplateArgument> &Converted,
5222 bool UpdateArgsWithConversions) {
5223 // Make a copy of the template arguments for processing. Only make the
5224 // changes at the end when successful in matching the arguments to the
5225 // template.
5226 TemplateArgumentListInfo NewArgs = TemplateArgs;
5227
5228 // Make sure we get the template parameter list from the most
5229 // recentdeclaration, since that is the only one that has is guaranteed to
5230 // have all the default template argument information.
5231 TemplateParameterList *Params =
5232 cast<TemplateDecl>(Template->getMostRecentDecl())
5233 ->getTemplateParameters();
5234
5235 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5236
5237 // C++ [temp.arg]p1:
5238 // [...] The type and form of each template-argument specified in
5239 // a template-id shall match the type and form specified for the
5240 // corresponding parameter declared by the template in its
5241 // template-parameter-list.
5242 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5243 SmallVector<TemplateArgument, 2> ArgumentPack;
5244 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5245 LocalInstantiationScope InstScope(*this, true);
5246 for (TemplateParameterList::iterator Param = Params->begin(),
5247 ParamEnd = Params->end();
5248 Param != ParamEnd; /* increment in loop */) {
5249 // If we have an expanded parameter pack, make sure we don't have too
5250 // many arguments.
5251 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5252 if (*Expansions == ArgumentPack.size()) {
5253 // We're done with this parameter pack. Pack up its arguments and add
5254 // them to the list.
5255 Converted.push_back(
5256 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5257 ArgumentPack.clear();
5258
5259 // This argument is assigned to the next parameter.
5260 ++Param;
5261 continue;
5262 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5263 // Not enough arguments for this parameter pack.
5264 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5265 << /*not enough args*/0
5266 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5267 << Template;
5268 Diag(Template->getLocation(), diag::note_template_decl_here)
5269 << Params->getSourceRange();
5270 return true;
5271 }
5272 }
5273
5274 if (ArgIdx < NumArgs) {
5275 // Check the template argument we were given.
5276 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
5277 TemplateLoc, RAngleLoc,
5278 ArgumentPack.size(), Converted))
5279 return true;
5280
5281 bool PackExpansionIntoNonPack =
5282 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5283 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5284 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
5285 // Core issue 1430: we have a pack expansion as an argument to an
5286 // alias template, and it's not part of a parameter pack. This
5287 // can't be canonicalized, so reject it now.
5288 Diag(NewArgs[ArgIdx].getLocation(),
5289 diag::err_alias_template_expansion_into_fixed_list)
5290 << NewArgs[ArgIdx].getSourceRange();
5291 Diag((*Param)->getLocation(), diag::note_template_param_here);
5292 return true;
5293 }
5294
5295 // We're now done with this argument.
5296 ++ArgIdx;
5297
5298 if ((*Param)->isTemplateParameterPack()) {
5299 // The template parameter was a template parameter pack, so take the
5300 // deduced argument and place it on the argument pack. Note that we
5301 // stay on the same template parameter so that we can deduce more
5302 // arguments.
5303 ArgumentPack.push_back(Converted.pop_back_val());
5304 } else {
5305 // Move to the next template parameter.
5306 ++Param;
5307 }
5308
5309 // If we just saw a pack expansion into a non-pack, then directly convert
5310 // the remaining arguments, because we don't know what parameters they'll
5311 // match up with.
5312 if (PackExpansionIntoNonPack) {
5313 if (!ArgumentPack.empty()) {
5314 // If we were part way through filling in an expanded parameter pack,
5315 // fall back to just producing individual arguments.
5316 Converted.insert(Converted.end(),
5317 ArgumentPack.begin(), ArgumentPack.end());
5318 ArgumentPack.clear();
5319 }
5320
5321 while (ArgIdx < NumArgs) {
5322 Converted.push_back(NewArgs[ArgIdx].getArgument());
5323 ++ArgIdx;
5324 }
5325
5326 return false;
5327 }
5328
5329 continue;
5330 }
5331
5332 // If we're checking a partial template argument list, we're done.
5333 if (PartialTemplateArgs) {
5334 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
5335 Converted.push_back(
5336 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5337
5338 return false;
5339 }
5340
5341 // If we have a template parameter pack with no more corresponding
5342 // arguments, just break out now and we'll fill in the argument pack below.
5343 if ((*Param)->isTemplateParameterPack()) {
5344 assert(!getExpandedPackSize(*Param) &&((!getExpandedPackSize(*Param) && "Should have dealt with this already"
) ? static_cast<void> (0) : __assert_fail ("!getExpandedPackSize(*Param) && \"Should have dealt with this already\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5345, __PRETTY_FUNCTION__))
5345 "Should have dealt with this already")((!getExpandedPackSize(*Param) && "Should have dealt with this already"
) ? static_cast<void> (0) : __assert_fail ("!getExpandedPackSize(*Param) && \"Should have dealt with this already\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5345, __PRETTY_FUNCTION__))
;
5346
5347 // A non-expanded parameter pack before the end of the parameter list
5348 // only occurs for an ill-formed template parameter list, unless we've
5349 // got a partial argument list for a function template, so just bail out.
5350 if (Param + 1 != ParamEnd)
5351 return true;
5352
5353 Converted.push_back(
5354 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5355 ArgumentPack.clear();
5356
5357 ++Param;
5358 continue;
5359 }
5360
5361 // Check whether we have a default argument.
5362 TemplateArgumentLoc Arg;
5363
5364 // Retrieve the default template argument from the template
5365 // parameter. For each kind of template parameter, we substitute the
5366 // template arguments provided thus far and any "outer" template arguments
5367 // (when the template parameter was part of a nested template) into
5368 // the default argument.
5369 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5370 if (!hasVisibleDefaultArgument(TTP))
5371 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5372 NewArgs);
5373
5374 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
5375 Template,
5376 TemplateLoc,
5377 RAngleLoc,
5378 TTP,
5379 Converted);
5380 if (!ArgType)
5381 return true;
5382
5383 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5384 ArgType);
5385 } else if (NonTypeTemplateParmDecl *NTTP
5386 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5387 if (!hasVisibleDefaultArgument(NTTP))
5388 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5389 NewArgs);
5390
5391 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
5392 TemplateLoc,
5393 RAngleLoc,
5394 NTTP,
5395 Converted);
5396 if (E.isInvalid())
5397 return true;
5398
5399 Expr *Ex = E.getAs<Expr>();
5400 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5401 } else {
5402 TemplateTemplateParmDecl *TempParm
5403 = cast<TemplateTemplateParmDecl>(*Param);
5404
5405 if (!hasVisibleDefaultArgument(TempParm))
5406 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5407 NewArgs);
5408
5409 NestedNameSpecifierLoc QualifierLoc;
5410 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
5411 TemplateLoc,
5412 RAngleLoc,
5413 TempParm,
5414 Converted,
5415 QualifierLoc);
5416 if (Name.isNull())
5417 return true;
5418
5419 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5420 TempParm->getDefaultArgument().getTemplateNameLoc());
5421 }
5422
5423 // Introduce an instantiation record that describes where we are using
5424 // the default template argument. We're not actually instantiating a
5425 // template here, we just create this object to put a note into the
5426 // context stack.
5427 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5428 SourceRange(TemplateLoc, RAngleLoc));
5429 if (Inst.isInvalid())
5430 return true;
5431
5432 // Check the default template argument.
5433 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5434 RAngleLoc, 0, Converted))
5435 return true;
5436
5437 // Core issue 150 (assumed resolution): if this is a template template
5438 // parameter, keep track of the default template arguments from the
5439 // template definition.
5440 if (isTemplateTemplateParameter)
5441 NewArgs.addArgument(Arg);
5442
5443 // Move to the next template parameter and argument.
5444 ++Param;
5445 ++ArgIdx;
5446 }
5447
5448 // If we're performing a partial argument substitution, allow any trailing
5449 // pack expansions; they might be empty. This can happen even if
5450 // PartialTemplateArgs is false (the list of arguments is complete but
5451 // still dependent).
5452 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5453 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5454 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5455 Converted.push_back(NewArgs[ArgIdx++].getArgument());
5456 }
5457
5458 // If we have any leftover arguments, then there were too many arguments.
5459 // Complain and fail.
5460 if (ArgIdx < NumArgs) {
5461 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5462 << /*too many args*/1
5463 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5464 << Template
5465 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5466 Diag(Template->getLocation(), diag::note_template_decl_here)
5467 << Params->getSourceRange();
5468 return true;
5469 }
5470
5471 // No problems found with the new argument list, propagate changes back
5472 // to caller.
5473 if (UpdateArgsWithConversions)
5474 TemplateArgs = std::move(NewArgs);
5475
5476 return false;
5477}
5478
5479namespace {
5480 class UnnamedLocalNoLinkageFinder
5481 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5482 {
5483 Sema &S;
5484 SourceRange SR;
5485
5486 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
5487
5488 public:
5489 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5490
5491 bool Visit(QualType T) {
5492 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5493 }
5494
5495#define TYPE(Class, Parent) \
5496 bool Visit##Class##Type(const Class##Type *);
5497#define ABSTRACT_TYPE(Class, Parent) \
5498 bool Visit##Class##Type(const Class##Type *) { return false; }
5499#define NON_CANONICAL_TYPE(Class, Parent) \
5500 bool Visit##Class##Type(const Class##Type *) { return false; }
5501#include "clang/AST/TypeNodes.inc"
5502
5503 bool VisitTagDecl(const TagDecl *Tag);
5504 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5505 };
5506} // end anonymous namespace
5507
5508bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5509 return false;
5510}
5511
5512bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5513 return Visit(T->getElementType());
5514}
5515
5516bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5517 return Visit(T->getPointeeType());
5518}
5519
5520bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5521 const BlockPointerType* T) {
5522 return Visit(T->getPointeeType());
5523}
5524
5525bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5526 const LValueReferenceType* T) {
5527 return Visit(T->getPointeeType());
5528}
5529
5530bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5531 const RValueReferenceType* T) {
5532 return Visit(T->getPointeeType());
5533}
5534
5535bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5536 const MemberPointerType* T) {
5537 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5538}
5539
5540bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5541 const ConstantArrayType* T) {
5542 return Visit(T->getElementType());
5543}
5544
5545bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5546 const IncompleteArrayType* T) {
5547 return Visit(T->getElementType());
5548}
5549
5550bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5551 const VariableArrayType* T) {
5552 return Visit(T->getElementType());
5553}
5554
5555bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5556 const DependentSizedArrayType* T) {
5557 return Visit(T->getElementType());
5558}
5559
5560bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5561 const DependentSizedExtVectorType* T) {
5562 return Visit(T->getElementType());
5563}
5564
5565bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5566 const DependentAddressSpaceType *T) {
5567 return Visit(T->getPointeeType());
5568}
5569
5570bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5571 return Visit(T->getElementType());
5572}
5573
5574bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5575 const DependentVectorType *T) {
5576 return Visit(T->getElementType());
5577}
5578
5579bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5580 return Visit(T->getElementType());
5581}
5582
5583bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5584 const FunctionProtoType* T) {
5585 for (const auto &A : T->param_types()) {
5586 if (Visit(A))
5587 return true;
5588 }
5589
5590 return Visit(T->getReturnType());
5591}
5592
5593bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5594 const FunctionNoProtoType* T) {
5595 return Visit(T->getReturnType());
5596}
5597
5598bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5599 const UnresolvedUsingType*) {
5600 return false;
5601}
5602
5603bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5604 return false;
5605}
5606
5607bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5608 return Visit(T->getUnderlyingType());
5609}
5610
5611bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5612 return false;
5613}
5614
5615bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5616 const UnaryTransformType*) {
5617 return false;
5618}
5619
5620bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5621 return Visit(T->getDeducedType());
5622}
5623
5624bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5625 const DeducedTemplateSpecializationType *T) {
5626 return Visit(T->getDeducedType());
5627}
5628
5629bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5630 return VisitTagDecl(T->getDecl());
5631}
5632
5633bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5634 return VisitTagDecl(T->getDecl());
5635}
5636
5637bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5638 const TemplateTypeParmType*) {
5639 return false;
5640}
5641
5642bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5643 const SubstTemplateTypeParmPackType *) {
5644 return false;
5645}
5646
5647bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5648 const TemplateSpecializationType*) {
5649 return false;
5650}
5651
5652bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5653 const InjectedClassNameType* T) {
5654 return VisitTagDecl(T->getDecl());
5655}
5656
5657bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5658 const DependentNameType* T) {
5659 return VisitNestedNameSpecifier(T->getQualifier());
5660}
5661
5662bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5663 const DependentTemplateSpecializationType* T) {
5664 return VisitNestedNameSpecifier(T->getQualifier());
5665}
5666
5667bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5668 const PackExpansionType* T) {
5669 return Visit(T->getPattern());
5670}
5671
5672bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5673 return false;
5674}
5675
5676bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5677 const ObjCInterfaceType *) {
5678 return false;
5679}
5680
5681bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5682 const ObjCObjectPointerType *) {
5683 return false;
5684}
5685
5686bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5687 return Visit(T->getValueType());
5688}
5689
5690bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5691 return false;
5692}
5693
5694bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5695 if (Tag->getDeclContext()->isFunctionOrMethod()) {
5696 S.Diag(SR.getBegin(),
5697 S.getLangOpts().CPlusPlus11 ?
5698 diag::warn_cxx98_compat_template_arg_local_type :
5699 diag::ext_template_arg_local_type)
5700 << S.Context.getTypeDeclType(Tag) << SR;
5701 return true;
5702 }
5703
5704 if (!Tag->hasNameForLinkage()) {
5705 S.Diag(SR.getBegin(),
5706 S.getLangOpts().CPlusPlus11 ?
5707 diag::warn_cxx98_compat_template_arg_unnamed_type :
5708 diag::ext_template_arg_unnamed_type) << SR;
5709 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5710 return true;
5711 }
5712
5713 return false;
5714}
5715
5716bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5717 NestedNameSpecifier *NNS) {
5718 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5719 return true;
5720
5721 switch (NNS->getKind()) {
5722 case NestedNameSpecifier::Identifier:
5723 case NestedNameSpecifier::Namespace:
5724 case NestedNameSpecifier::NamespaceAlias:
5725 case NestedNameSpecifier::Global:
5726 case NestedNameSpecifier::Super:
5727 return false;
5728
5729 case NestedNameSpecifier::TypeSpec:
5730 case NestedNameSpecifier::TypeSpecWithTemplate:
5731 return Visit(QualType(NNS->getAsType(), 0));
5732 }
5733 llvm_unreachable("Invalid NestedNameSpecifier::Kind!")::llvm::llvm_unreachable_internal("Invalid NestedNameSpecifier::Kind!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5733)
;
5734}
5735
5736/// Check a template argument against its corresponding
5737/// template type parameter.
5738///
5739/// This routine implements the semantics of C++ [temp.arg.type]. It
5740/// returns true if an error occurred, and false otherwise.
5741bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
5742 TypeSourceInfo *ArgInfo) {
5743 assert(ArgInfo && "invalid TypeSourceInfo")((ArgInfo && "invalid TypeSourceInfo") ? static_cast<
void> (0) : __assert_fail ("ArgInfo && \"invalid TypeSourceInfo\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5743, __PRETTY_FUNCTION__))
;
5744 QualType Arg = ArgInfo->getType();
5745 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5746
5747 if (Arg->isVariablyModifiedType()) {
5748 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5749 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5750 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5751 }
5752
5753 // C++03 [temp.arg.type]p2:
5754 // A local type, a type with no linkage, an unnamed type or a type
5755 // compounded from any of these types shall not be used as a
5756 // template-argument for a template type-parameter.
5757 //
5758 // C++11 allows these, and even in C++03 we allow them as an extension with
5759 // a warning.
5760 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5761 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5762 (void)Finder.Visit(Context.getCanonicalType(Arg));
5763 }
5764
5765 return false;
5766}
5767
5768enum NullPointerValueKind {
5769 NPV_NotNullPointer,
5770 NPV_NullPointer,
5771 NPV_Error
5772};
5773
5774/// Determine whether the given template argument is a null pointer
5775/// value of the appropriate type.
5776static NullPointerValueKind
5777isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5778 QualType ParamType, Expr *Arg,
5779 Decl *Entity = nullptr) {
5780 if (Arg->isValueDependent() || Arg->isTypeDependent())
5781 return NPV_NotNullPointer;
5782
5783 // dllimport'd entities aren't constant but are available inside of template
5784 // arguments.
5785 if (Entity && Entity->hasAttr<DLLImportAttr>())
5786 return NPV_NotNullPointer;
5787
5788 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5789 llvm_unreachable(::llvm::llvm_unreachable_internal("Incomplete parameter type in isNullPointerValueTemplateArgument!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5790)
5790 "Incomplete parameter type in isNullPointerValueTemplateArgument!")::llvm::llvm_unreachable_internal("Incomplete parameter type in isNullPointerValueTemplateArgument!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5790)
;
5791
5792 if (!S.getLangOpts().CPlusPlus11)
5793 return NPV_NotNullPointer;
5794
5795 // Determine whether we have a constant expression.
5796 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5797 if (ArgRV.isInvalid())
5798 return NPV_Error;
5799 Arg = ArgRV.get();
5800
5801 Expr::EvalResult EvalResult;
5802 SmallVector<PartialDiagnosticAt, 8> Notes;
5803 EvalResult.Diag = &Notes;
5804 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5805 EvalResult.HasSideEffects) {
5806 SourceLocation DiagLoc = Arg->getExprLoc();
5807
5808 // If our only note is the usual "invalid subexpression" note, just point
5809 // the caret at its location rather than producing an essentially
5810 // redundant note.
5811 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5812 diag::note_invalid_subexpr_in_const_expr) {
5813 DiagLoc = Notes[0].first;
5814 Notes.clear();
5815 }
5816
5817 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5818 << Arg->getType() << Arg->getSourceRange();
5819 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5820 S.Diag(Notes[I].first, Notes[I].second);
5821
5822 S.Diag(Param->getLocation(), diag::note_template_param_here);
5823 return NPV_Error;
5824 }
5825
5826 // C++11 [temp.arg.nontype]p1:
5827 // - an address constant expression of type std::nullptr_t
5828 if (Arg->getType()->isNullPtrType())
5829 return NPV_NullPointer;
5830
5831 // - a constant expression that evaluates to a null pointer value (4.10); or
5832 // - a constant expression that evaluates to a null member pointer value
5833 // (4.11); or
5834 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5835 (EvalResult.Val.isMemberPointer() &&
5836 !EvalResult.Val.getMemberPointerDecl())) {
5837 // If our expression has an appropriate type, we've succeeded.
5838 bool ObjCLifetimeConversion;
5839 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5840 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5841 ObjCLifetimeConversion))
5842 return NPV_NullPointer;
5843
5844 // The types didn't match, but we know we got a null pointer; complain,
5845 // then recover as if the types were correct.
5846 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5847 << Arg->getType() << ParamType << Arg->getSourceRange();
5848 S.Diag(Param->getLocation(), diag::note_template_param_here);
5849 return NPV_NullPointer;
5850 }
5851
5852 // If we don't have a null pointer value, but we do have a NULL pointer
5853 // constant, suggest a cast to the appropriate type.
5854 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5855 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5856 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
5857 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
5858 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
5859 ")");
5860 S.Diag(Param->getLocation(), diag::note_template_param_here);
5861 return NPV_NullPointer;
5862 }
5863
5864 // FIXME: If we ever want to support general, address-constant expressions
5865 // as non-type template arguments, we should return the ExprResult here to
5866 // be interpreted by the caller.
5867 return NPV_NotNullPointer;
5868}
5869
5870/// Checks whether the given template argument is compatible with its
5871/// template parameter.
5872static bool CheckTemplateArgumentIsCompatibleWithParameter(
5873 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5874 Expr *Arg, QualType ArgType) {
5875 bool ObjCLifetimeConversion;
5876 if (ParamType->isPointerType() &&
5877 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5878 S.IsQualificationConversion(ArgType, ParamType, false,
5879 ObjCLifetimeConversion)) {
5880 // For pointer-to-object types, qualification conversions are
5881 // permitted.
5882 } else {
5883 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5884 if (!ParamRef->getPointeeType()->isFunctionType()) {
5885 // C++ [temp.arg.nontype]p5b3:
5886 // For a non-type template-parameter of type reference to
5887 // object, no conversions apply. The type referred to by the
5888 // reference may be more cv-qualified than the (otherwise
5889 // identical) type of the template- argument. The
5890 // template-parameter is bound directly to the
5891 // template-argument, which shall be an lvalue.
5892
5893 // FIXME: Other qualifiers?
5894 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5895 unsigned ArgQuals = ArgType.getCVRQualifiers();
5896
5897 if ((ParamQuals | ArgQuals) != ParamQuals) {
5898 S.Diag(Arg->getBeginLoc(),
5899 diag::err_template_arg_ref_bind_ignores_quals)
5900 << ParamType << Arg->getType() << Arg->getSourceRange();
5901 S.Diag(Param->getLocation(), diag::note_template_param_here);
5902 return true;
5903 }
5904 }
5905 }
5906
5907 // At this point, the template argument refers to an object or
5908 // function with external linkage. We now need to check whether the
5909 // argument and parameter types are compatible.
5910 if (!S.Context.hasSameUnqualifiedType(ArgType,
5911 ParamType.getNonReferenceType())) {
5912 // We can't perform this conversion or binding.
5913 if (ParamType->isReferenceType())
5914 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
5915 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5916 else
5917 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
5918 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5919 S.Diag(Param->getLocation(), diag::note_template_param_here);
5920 return true;
5921 }
5922 }
5923
5924 return false;
5925}
5926
5927/// Checks whether the given template argument is the address
5928/// of an object or function according to C++ [temp.arg.nontype]p1.
5929static bool
5930CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5931 NonTypeTemplateParmDecl *Param,
5932 QualType ParamType,
5933 Expr *ArgIn,
5934 TemplateArgument &Converted) {
5935 bool Invalid = false;
5936 Expr *Arg = ArgIn;
5937 QualType ArgType = Arg->getType();
5938
5939 bool AddressTaken = false;
5940 SourceLocation AddrOpLoc;
5941 if (S.getLangOpts().MicrosoftExt) {
5942 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5943 // dereference and address-of operators.
5944 Arg = Arg->IgnoreParenCasts();
5945
5946 bool ExtWarnMSTemplateArg = false;
5947 UnaryOperatorKind FirstOpKind;
5948 SourceLocation FirstOpLoc;
5949 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5950 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5951 if (UnOpKind == UO_Deref)
5952 ExtWarnMSTemplateArg = true;
5953 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5954 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5955 if (!AddrOpLoc.isValid()) {
5956 FirstOpKind = UnOpKind;
5957 FirstOpLoc = UnOp->getOperatorLoc();
5958 }
5959 } else
5960 break;
5961 }
5962 if (FirstOpLoc.isValid()) {
5963 if (ExtWarnMSTemplateArg)
5964 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
5965 << ArgIn->getSourceRange();
5966
5967 if (FirstOpKind == UO_AddrOf)
5968 AddressTaken = true;
5969 else if (Arg->getType()->isPointerType()) {
5970 // We cannot let pointers get dereferenced here, that is obviously not a
5971 // constant expression.
5972 assert(FirstOpKind == UO_Deref)((FirstOpKind == UO_Deref) ? static_cast<void> (0) : __assert_fail
("FirstOpKind == UO_Deref", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5972, __PRETTY_FUNCTION__))
;
5973 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5974 << Arg->getSourceRange();
5975 }
5976 }
5977 } else {
5978 // See through any implicit casts we added to fix the type.
5979 Arg = Arg->IgnoreImpCasts();
5980
5981 // C++ [temp.arg.nontype]p1:
5982 //
5983 // A template-argument for a non-type, non-template
5984 // template-parameter shall be one of: [...]
5985 //
5986 // -- the address of an object or function with external
5987 // linkage, including function templates and function
5988 // template-ids but excluding non-static class members,
5989 // expressed as & id-expression where the & is optional if
5990 // the name refers to a function or array, or if the
5991 // corresponding template-parameter is a reference; or
5992
5993 // In C++98/03 mode, give an extension warning on any extra parentheses.
5994 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5995 bool ExtraParens = false;
5996 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5997 if (!Invalid && !ExtraParens) {
5998 S.Diag(Arg->getBeginLoc(),
5999 S.getLangOpts().CPlusPlus11
6000 ? diag::warn_cxx98_compat_template_arg_extra_parens
6001 : diag::ext_template_arg_extra_parens)
6002 << Arg->getSourceRange();
6003 ExtraParens = true;
6004 }
6005
6006 Arg = Parens->getSubExpr();
6007 }
6008
6009 while (SubstNonTypeTemplateParmExpr *subst =
6010 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6011 Arg = subst->getReplacement()->IgnoreImpCasts();
6012
6013 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6014 if (UnOp->getOpcode() == UO_AddrOf) {
6015 Arg = UnOp->getSubExpr();
6016 AddressTaken = true;
6017 AddrOpLoc = UnOp->getOperatorLoc();
6018 }
6019 }
6020
6021 while (SubstNonTypeTemplateParmExpr *subst =
6022 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6023 Arg = subst->getReplacement()->IgnoreImpCasts();
6024 }
6025
6026 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
6027 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6028
6029 // If our parameter has pointer type, check for a null template value.
6030 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6031 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6032 Entity)) {
6033 case NPV_NullPointer:
6034 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6035 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6036 /*isNullPtr=*/true);
6037 return false;
6038
6039 case NPV_Error:
6040 return true;
6041
6042 case NPV_NotNullPointer:
6043 break;
6044 }
6045 }
6046
6047 // Stop checking the precise nature of the argument if it is value dependent,
6048 // it should be checked when instantiated.
6049 if (Arg->isValueDependent()) {
6050 Converted = TemplateArgument(ArgIn);
6051 return false;
6052 }
6053
6054 if (isa<CXXUuidofExpr>(Arg)) {
6055 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
6056 ArgIn, Arg, ArgType))
6057 return true;
6058
6059 Converted = TemplateArgument(ArgIn);
6060 return false;
6061 }
6062
6063 if (!DRE) {
6064 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6065 << Arg->getSourceRange();
6066 S.Diag(Param->getLocation(), diag::note_template_param_here);
6067 return true;
6068 }
6069
6070 // Cannot refer to non-static data members
6071 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6072 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6073 << Entity << Arg->getSourceRange();
6074 S.Diag(Param->getLocation(), diag::note_template_param_here);
6075 return true;
6076 }
6077
6078 // Cannot refer to non-static member functions
6079 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6080 if (!Method->isStatic()) {
6081 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6082 << Method << Arg->getSourceRange();
6083 S.Diag(Param->getLocation(), diag::note_template_param_here);
6084 return true;
6085 }
6086 }
6087
6088 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6089 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6090
6091 // A non-type template argument must refer to an object or function.
6092 if (!Func && !Var) {
6093 // We found something, but we don't know specifically what it is.
6094 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6095 << Arg->getSourceRange();
6096 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6097 return true;
6098 }
6099
6100 // Address / reference template args must have external linkage in C++98.
6101 if (Entity->getFormalLinkage() == InternalLinkage) {
6102 S.Diag(Arg->getBeginLoc(),
6103 S.getLangOpts().CPlusPlus11
6104 ? diag::warn_cxx98_compat_template_arg_object_internal
6105 : diag::ext_template_arg_object_internal)
6106 << !Func << Entity << Arg->getSourceRange();
6107 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6108 << !Func;
6109 } else if (!Entity->hasLinkage()) {
6110 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6111 << !Func << Entity << Arg->getSourceRange();
6112 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6113 << !Func;
6114 return true;
6115 }
6116
6117 if (Func) {
6118 // If the template parameter has pointer type, the function decays.
6119 if (ParamType->isPointerType() && !AddressTaken)
6120 ArgType = S.Context.getPointerType(Func->getType());
6121 else if (AddressTaken && ParamType->isReferenceType()) {
6122 // If we originally had an address-of operator, but the
6123 // parameter has reference type, complain and (if things look
6124 // like they will work) drop the address-of operator.
6125 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
6126 ParamType.getNonReferenceType())) {
6127 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6128 << ParamType;
6129 S.Diag(Param->getLocation(), diag::note_template_param_here);
6130 return true;
6131 }
6132
6133 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6134 << ParamType
6135 << FixItHint::CreateRemoval(AddrOpLoc);
6136 S.Diag(Param->getLocation(), diag::note_template_param_here);
6137
6138 ArgType = Func->getType();
6139 }
6140 } else {
6141 // A value of reference type is not an object.
6142 if (Var->getType()->isReferenceType()) {
6143 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6144 << Var->getType() << Arg->getSourceRange();
6145 S.Diag(Param->getLocation(), diag::note_template_param_here);
6146 return true;
6147 }
6148
6149 // A template argument must have static storage duration.
6150 if (Var->getTLSKind()) {
6151 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6152 << Arg->getSourceRange();
6153 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6154 return true;
6155 }
6156
6157 // If the template parameter has pointer type, we must have taken
6158 // the address of this object.
6159 if (ParamType->isReferenceType()) {
6160 if (AddressTaken) {
6161 // If we originally had an address-of operator, but the
6162 // parameter has reference type, complain and (if things look
6163 // like they will work) drop the address-of operator.
6164 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
6165 ParamType.getNonReferenceType())) {
6166 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6167 << ParamType;
6168 S.Diag(Param->getLocation(), diag::note_template_param_here);
6169 return true;
6170 }
6171
6172 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6173 << ParamType
6174 << FixItHint::CreateRemoval(AddrOpLoc);
6175 S.Diag(Param->getLocation(), diag::note_template_param_here);
6176
6177 ArgType = Var->getType();
6178 }
6179 } else if (!AddressTaken && ParamType->isPointerType()) {
6180 if (Var->getType()->isArrayType()) {
6181 // Array-to-pointer decay.
6182 ArgType = S.Context.getArrayDecayedType(Var->getType());
6183 } else {
6184 // If the template parameter has pointer type but the address of
6185 // this object was not taken, complain and (possibly) recover by
6186 // taking the address of the entity.
6187 ArgType = S.Context.getPointerType(Var->getType());
6188 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6189 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6190 << ParamType;
6191 S.Diag(Param->getLocation(), diag::note_template_param_here);
6192 return true;
6193 }
6194
6195 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6196 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6197
6198 S.Diag(Param->getLocation(), diag::note_template_param_here);
6199 }
6200 }
6201 }
6202
6203 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6204 Arg, ArgType))
6205 return true;
6206
6207 // Create the template argument.
6208 Converted =
6209 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
6210 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6211 return false;
6212}
6213
6214/// Checks whether the given template argument is a pointer to
6215/// member constant according to C++ [temp.arg.nontype]p1.
6216static bool CheckTemplateArgumentPointerToMember(Sema &S,
6217 NonTypeTemplateParmDecl *Param,
6218 QualType ParamType,
6219 Expr *&ResultArg,
6220 TemplateArgument &Converted) {
6221 bool Invalid = false;
6222
6223 Expr *Arg = ResultArg;
6224 bool ObjCLifetimeConversion;
6225
6226 // C++ [temp.arg.nontype]p1:
6227 //
6228 // A template-argument for a non-type, non-template
6229 // template-parameter shall be one of: [...]
6230 //
6231 // -- a pointer to member expressed as described in 5.3.1.
6232 DeclRefExpr *DRE = nullptr;
6233
6234 // In C++98/03 mode, give an extension warning on any extra parentheses.
6235 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6236 bool ExtraParens = false;
6237 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6238 if (!Invalid && !ExtraParens) {
6239 S.Diag(Arg->getBeginLoc(),
6240 S.getLangOpts().CPlusPlus11
6241 ? diag::warn_cxx98_compat_template_arg_extra_parens
6242 : diag::ext_template_arg_extra_parens)
6243 << Arg->getSourceRange();
6244 ExtraParens = true;
6245 }
6246
6247 Arg = Parens->getSubExpr();
6248 }
6249
6250 while (SubstNonTypeTemplateParmExpr *subst =
6251 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6252 Arg = subst->getReplacement()->IgnoreImpCasts();
6253
6254 // A pointer-to-member constant written &Class::member.
6255 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6256 if (UnOp->getOpcode() == UO_AddrOf) {
6257 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6258 if (DRE && !DRE->getQualifier())
6259 DRE = nullptr;
6260 }
6261 }
6262 // A constant of pointer-to-member type.
6263 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6264 ValueDecl *VD = DRE->getDecl();
6265 if (VD->getType()->isMemberPointerType()) {
6266 if (isa<NonTypeTemplateParmDecl>(VD)) {
6267 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6268 Converted = TemplateArgument(Arg);
6269 } else {
6270 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6271 Converted = TemplateArgument(VD, ParamType);
6272 }
6273 return Invalid;
6274 }
6275 }
6276
6277 DRE = nullptr;
6278 }
6279
6280 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6281
6282 // Check for a null pointer value.
6283 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6284 Entity)) {
6285 case NPV_Error:
6286 return true;
6287 case NPV_NullPointer:
6288 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6289 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6290 /*isNullPtr*/true);
6291 return false;
6292 case NPV_NotNullPointer:
6293 break;
6294 }
6295
6296 if (S.IsQualificationConversion(ResultArg->getType(),
6297 ParamType.getNonReferenceType(), false,
6298 ObjCLifetimeConversion)) {
6299 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6300 ResultArg->getValueKind())
6301 .get();
6302 } else if (!S.Context.hasSameUnqualifiedType(
6303 ResultArg->getType(), ParamType.getNonReferenceType())) {
6304 // We can't perform this conversion.
6305 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6306 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6307 S.Diag(Param->getLocation(), diag::note_template_param_here);
6308 return true;
6309 }
6310
6311 if (!DRE)
6312 return S.Diag(Arg->getBeginLoc(),
6313 diag::err_template_arg_not_pointer_to_member_form)
6314 << Arg->getSourceRange();
6315
6316 if (isa<FieldDecl>(DRE->getDecl()) ||
6317 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6318 isa<CXXMethodDecl>(DRE->getDecl())) {
6319 assert((isa<FieldDecl>(DRE->getDecl()) ||(((isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl
>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->
getDecl())->isStatic()) && "Only non-static member pointers can make it here"
) ? static_cast<void> (0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6322, __PRETTY_FUNCTION__))
6320 isa<IndirectFieldDecl>(DRE->getDecl()) ||(((isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl
>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->
getDecl())->isStatic()) && "Only non-static member pointers can make it here"
) ? static_cast<void> (0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6322, __PRETTY_FUNCTION__))
6321 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&(((isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl
>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->
getDecl())->isStatic()) && "Only non-static member pointers can make it here"
) ? static_cast<void> (0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6322, __PRETTY_FUNCTION__))
6322 "Only non-static member pointers can make it here")(((isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl
>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->
getDecl())->isStatic()) && "Only non-static member pointers can make it here"
) ? static_cast<void> (0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6322, __PRETTY_FUNCTION__))
;
6323
6324 // Okay: this is the address of a non-static member, and therefore
6325 // a member pointer constant.
6326 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6327 Converted = TemplateArgument(Arg);
6328 } else {
6329 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
6330 Converted = TemplateArgument(D, ParamType);
6331 }
6332 return Invalid;
6333 }
6334
6335 // We found something else, but we don't know specifically what it is.
6336 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6337 << Arg->getSourceRange();
6338 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6339 return true;
6340}
6341
6342/// Check a template argument against its corresponding
6343/// non-type template parameter.
6344///
6345/// This routine implements the semantics of C++ [temp.arg.nontype].
6346/// If an error occurred, it returns ExprError(); otherwise, it
6347/// returns the converted template argument. \p ParamType is the
6348/// type of the non-type template parameter after it has been instantiated.
6349ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6350 QualType ParamType, Expr *Arg,
6351 TemplateArgument &Converted,
6352 CheckTemplateArgumentKind CTAK) {
6353 SourceLocation StartLoc = Arg->getBeginLoc();
6354
6355 // If the parameter type somehow involves auto, deduce the type now.
6356 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
6357 // During template argument deduction, we allow 'decltype(auto)' to
6358 // match an arbitrary dependent argument.
6359 // FIXME: The language rules don't say what happens in this case.
6360 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6361 // expression is merely instantiation-dependent; is this enough?
6362 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6363 auto *AT = dyn_cast<AutoType>(ParamType);
6364 if (AT && AT->isDecltypeAuto()) {
6365 Converted = TemplateArgument(Arg);
6366 return Arg;
6367 }
6368 }
6369
6370 // When checking a deduced template argument, deduce from its type even if
6371 // the type is dependent, in order to check the types of non-type template
6372 // arguments line up properly in partial ordering.
6373 Optional<unsigned> Depth = Param->getDepth() + 1;
6374 Expr *DeductionArg = Arg;
6375 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6376 DeductionArg = PE->getPattern();
6377 if (DeduceAutoType(
6378 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
6379 DeductionArg, ParamType, Depth) == DAR_Failed) {
6380 Diag(Arg->getExprLoc(),
6381 diag::err_non_type_template_parm_type_deduction_failure)
6382 << Param->getDeclName() << Param->getType() << Arg->getType()
6383 << Arg->getSourceRange();
6384 Diag(Param->getLocation(), diag::note_template_param_here);
6385 return ExprError();
6386 }
6387 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6388 // an error. The error message normally references the parameter
6389 // declaration, but here we'll pass the argument location because that's
6390 // where the parameter type is deduced.
6391 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6392 if (ParamType.isNull()) {
6393 Diag(Param->getLocation(), diag::note_template_param_here);
6394 return ExprError();
6395 }
6396 }
6397
6398 // We should have already dropped all cv-qualifiers by now.
6399 assert(!ParamType.hasQualifiers() &&((!ParamType.hasQualifiers() && "non-type template parameter type cannot be qualified"
) ? static_cast<void> (0) : __assert_fail ("!ParamType.hasQualifiers() && \"non-type template parameter type cannot be qualified\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6400, __PRETTY_FUNCTION__))
6400 "non-type template parameter type cannot be qualified")((!ParamType.hasQualifiers() && "non-type template parameter type cannot be qualified"
) ? static_cast<void> (0) : __assert_fail ("!ParamType.hasQualifiers() && \"non-type template parameter type cannot be qualified\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6400, __PRETTY_FUNCTION__))
;
6401
6402 if (CTAK == CTAK_Deduced &&
6403 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
6404 Arg->getType())) {
6405 // FIXME: If either type is dependent, we skip the check. This isn't
6406 // correct, since during deduction we're supposed to have replaced each
6407 // template parameter with some unique (non-dependent) placeholder.
6408 // FIXME: If the argument type contains 'auto', we carry on and fail the
6409 // type check in order to force specific types to be more specialized than
6410 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6411 // work.
6412 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6413 !Arg->getType()->getContainedAutoType()) {
6414 Converted = TemplateArgument(Arg);
6415 return Arg;
6416 }
6417 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6418 // we should actually be checking the type of the template argument in P,
6419 // not the type of the template argument deduced from A, against the
6420 // template parameter type.
6421 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6422 << Arg->getType()
6423 << ParamType.getUnqualifiedType();
6424 Diag(Param->getLocation(), diag::note_template_param_here);
6425 return ExprError();
6426 }
6427
6428 // If either the parameter has a dependent type or the argument is
6429 // type-dependent, there's nothing we can check now. The argument only
6430 // contains an unexpanded pack during partial ordering, and there's
6431 // nothing more we can check in that case.
6432 if (ParamType->isDependentType() || Arg->isTypeDependent() ||
6433 Arg->containsUnexpandedParameterPack()) {
6434 // Force the argument to the type of the parameter to maintain invariants.
6435 auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6436 if (PE)
6437 Arg = PE->getPattern();
6438 ExprResult E = ImpCastExprToType(
6439 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6440 ParamType->isLValueReferenceType() ? VK_LValue :
6441 ParamType->isRValueReferenceType() ? VK_XValue : VK_RValue);
6442 if (E.isInvalid())
6443 return ExprError();
6444 if (PE) {
6445 // Recreate a pack expansion if we unwrapped one.
6446 E = new (Context)
6447 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6448 PE->getNumExpansions());
6449 }
6450 Converted = TemplateArgument(E.get());
6451 return E;
6452 }
6453
6454 // The initialization of the parameter from the argument is
6455 // a constant-evaluated context.
6456 EnterExpressionEvaluationContext ConstantEvaluated(
6457 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6458
6459 if (getLangOpts().CPlusPlus17) {
6460 // C++17 [temp.arg.nontype]p1:
6461 // A template-argument for a non-type template parameter shall be
6462 // a converted constant expression of the type of the template-parameter.
6463 APValue Value;
6464 ExprResult ArgResult = CheckConvertedConstantExpression(
6465 Arg, ParamType, Value, CCEK_TemplateArg);
6466 if (ArgResult.isInvalid())
6467 return ExprError();
6468
6469 // For a value-dependent argument, CheckConvertedConstantExpression is
6470 // permitted (and expected) to be unable to determine a value.
6471 if (ArgResult.get()->isValueDependent()) {
6472 Converted = TemplateArgument(ArgResult.get());
6473 return ArgResult;
6474 }
6475
6476 QualType CanonParamType = Context.getCanonicalType(ParamType);
6477
6478 // Convert the APValue to a TemplateArgument.
6479 switch (Value.getKind()) {
6480 case APValue::None:
6481 assert(ParamType->isNullPtrType())((ParamType->isNullPtrType()) ? static_cast<void> (0
) : __assert_fail ("ParamType->isNullPtrType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6481, __PRETTY_FUNCTION__))
;
6482 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
6483 break;
6484 case APValue::Indeterminate:
6485 llvm_unreachable("result of constant evaluation should be initialized")::llvm::llvm_unreachable_internal("result of constant evaluation should be initialized"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6485)
;
6486 break;
6487 case APValue::Int:
6488 assert(ParamType->isIntegralOrEnumerationType())((ParamType->isIntegralOrEnumerationType()) ? static_cast<
void> (0) : __assert_fail ("ParamType->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6488, __PRETTY_FUNCTION__))
;
6489 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
6490 break;
6491 case APValue::MemberPointer: {
6492 assert(ParamType->isMemberPointerType())((ParamType->isMemberPointerType()) ? static_cast<void>
(0) : __assert_fail ("ParamType->isMemberPointerType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6492, __PRETTY_FUNCTION__))
;
6493
6494 // FIXME: We need TemplateArgument representation and mangling for these.
6495 if (!Value.getMemberPointerPath().empty()) {
6496 Diag(Arg->getBeginLoc(),
6497 diag::err_template_arg_member_ptr_base_derived_not_supported)
6498 << Value.getMemberPointerDecl() << ParamType
6499 << Arg->getSourceRange();
6500 return ExprError();
6501 }
6502
6503 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
6504 Converted = VD ? TemplateArgument(VD, CanonParamType)
6505 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6506 break;
6507 }
6508 case APValue::LValue: {
6509 // For a non-type template-parameter of pointer or reference type,
6510 // the value of the constant expression shall not refer to
6511 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||((ParamType->isPointerType() || ParamType->isReferenceType
() || ParamType->isNullPtrType()) ? static_cast<void>
(0) : __assert_fail ("ParamType->isPointerType() || ParamType->isReferenceType() || ParamType->isNullPtrType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6512, __PRETTY_FUNCTION__))
6512 ParamType->isNullPtrType())((ParamType->isPointerType() || ParamType->isReferenceType
() || ParamType->isNullPtrType()) ? static_cast<void>
(0) : __assert_fail ("ParamType->isPointerType() || ParamType->isReferenceType() || ParamType->isNullPtrType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6512, __PRETTY_FUNCTION__))
;
6513 // -- a temporary object
6514 // -- a string literal
6515 // -- the result of a typeid expression, or
6516 // -- a predefined __func__ variable
6517 APValue::LValueBase Base = Value.getLValueBase();
6518 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6519 if (Base && !VD) {
6520 auto *E = Base.dyn_cast<const Expr *>();
6521 if (E && isa<CXXUuidofExpr>(E)) {
6522 Converted = TemplateArgument(ArgResult.get()->IgnoreImpCasts());
6523 break;
6524 }
6525 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6526 << Arg->getSourceRange();
6527 return ExprError();
6528 }
6529 // -- a subobject
6530 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6531 VD && VD->getType()->isArrayType() &&
6532 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
6533 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6534 // Per defect report (no number yet):
6535 // ... other than a pointer to the first element of a complete array
6536 // object.
6537 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6538 Value.isLValueOnePastTheEnd()) {
6539 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6540 << Value.getAsString(Context, ParamType);
6541 return ExprError();
6542 }
6543 assert((VD || !ParamType->isReferenceType()) &&(((VD || !ParamType->isReferenceType()) && "null reference should not be a constant expression"
) ? static_cast<void> (0) : __assert_fail ("(VD || !ParamType->isReferenceType()) && \"null reference should not be a constant expression\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6544, __PRETTY_FUNCTION__))
6544 "null reference should not be a constant expression")(((VD || !ParamType->isReferenceType()) && "null reference should not be a constant expression"
) ? static_cast<void> (0) : __assert_fail ("(VD || !ParamType->isReferenceType()) && \"null reference should not be a constant expression\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6544, __PRETTY_FUNCTION__))
;
6545 assert((!VD || !ParamType->isNullPtrType()) &&(((!VD || !ParamType->isNullPtrType()) && "non-null value of type nullptr_t?"
) ? static_cast<void> (0) : __assert_fail ("(!VD || !ParamType->isNullPtrType()) && \"non-null value of type nullptr_t?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6546, __PRETTY_FUNCTION__))
6546 "non-null value of type nullptr_t?")(((!VD || !ParamType->isNullPtrType()) && "non-null value of type nullptr_t?"
) ? static_cast<void> (0) : __assert_fail ("(!VD || !ParamType->isNullPtrType()) && \"non-null value of type nullptr_t?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6546, __PRETTY_FUNCTION__))
;
6547 Converted = VD ? TemplateArgument(VD, CanonParamType)
6548 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6549 break;
6550 }
6551 case APValue::AddrLabelDiff:
6552 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6553 case APValue::FixedPoint:
6554 case APValue::Float:
6555 case APValue::ComplexInt:
6556 case APValue::ComplexFloat:
6557 case APValue::Vector:
6558 case APValue::Array:
6559 case APValue::Struct:
6560 case APValue::Union:
6561 llvm_unreachable("invalid kind for template argument")::llvm::llvm_unreachable_internal("invalid kind for template argument"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6561)
;
6562 }
6563
6564 return ArgResult.get();
6565 }
6566
6567 // C++ [temp.arg.nontype]p5:
6568 // The following conversions are performed on each expression used
6569 // as a non-type template-argument. If a non-type
6570 // template-argument cannot be converted to the type of the
6571 // corresponding template-parameter then the program is
6572 // ill-formed.
6573 if (ParamType->isIntegralOrEnumerationType()) {
6574 // C++11:
6575 // -- for a non-type template-parameter of integral or
6576 // enumeration type, conversions permitted in a converted
6577 // constant expression are applied.
6578 //
6579 // C++98:
6580 // -- for a non-type template-parameter of integral or
6581 // enumeration type, integral promotions (4.5) and integral
6582 // conversions (4.7) are applied.
6583
6584 if (getLangOpts().CPlusPlus11) {
6585 // C++ [temp.arg.nontype]p1:
6586 // A template-argument for a non-type, non-template template-parameter
6587 // shall be one of:
6588 //
6589 // -- for a non-type template-parameter of integral or enumeration
6590 // type, a converted constant expression of the type of the
6591 // template-parameter; or
6592 llvm::APSInt Value;
6593 ExprResult ArgResult =
6594 CheckConvertedConstantExpression(Arg, ParamType, Value,
6595 CCEK_TemplateArg);
6596 if (ArgResult.isInvalid())
6597 return ExprError();
6598
6599 // We can't check arbitrary value-dependent arguments.
6600 if (ArgResult.get()->isValueDependent()) {
6601 Converted = TemplateArgument(ArgResult.get());
6602 return ArgResult;
6603 }
6604
6605 // Widen the argument value to sizeof(parameter type). This is almost
6606 // always a no-op, except when the parameter type is bool. In
6607 // that case, this may extend the argument from 1 bit to 8 bits.
6608 QualType IntegerType = ParamType;
6609 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6610 IntegerType = Enum->getDecl()->getIntegerType();
6611 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6612
6613 Converted = TemplateArgument(Context, Value,
6614 Context.getCanonicalType(ParamType));
6615 return ArgResult;
6616 }
6617
6618 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6619 if (ArgResult.isInvalid())
6620 return ExprError();
6621 Arg = ArgResult.get();
6622
6623 QualType ArgType = Arg->getType();
6624
6625 // C++ [temp.arg.nontype]p1:
6626 // A template-argument for a non-type, non-template
6627 // template-parameter shall be one of:
6628 //
6629 // -- an integral constant-expression of integral or enumeration
6630 // type; or
6631 // -- the name of a non-type template-parameter; or
6632 llvm::APSInt Value;
6633 if (!ArgType->isIntegralOrEnumerationType()) {
6634 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6635 << ArgType << Arg->getSourceRange();
6636 Diag(Param->getLocation(), diag::note_template_param_here);
6637 return ExprError();
6638 } else if (!Arg->isValueDependent()) {
6639 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6640 QualType T;
6641
6642 public:
6643 TmplArgICEDiagnoser(QualType T) : T(T) { }
6644
6645 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6646 SourceRange SR) override {
6647 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6648 }
6649 } Diagnoser(ArgType);
6650
6651 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
6652 false).get();
6653 if (!Arg)
6654 return ExprError();
6655 }
6656
6657 // From here on out, all we care about is the unqualified form
6658 // of the argument type.
6659 ArgType = ArgType.getUnqualifiedType();
6660
6661 // Try to convert the argument to the parameter's type.
6662 if (Context.hasSameType(ParamType, ArgType)) {
6663 // Okay: no conversion necessary
6664 } else if (ParamType->isBooleanType()) {
6665 // This is an integral-to-boolean conversion.
6666 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6667 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6668 !ParamType->isEnumeralType()) {
6669 // This is an integral promotion or conversion.
6670 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6671 } else {
6672 // We can't perform this conversion.
6673 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6674 << Arg->getType() << ParamType << Arg->getSourceRange();
6675 Diag(Param->getLocation(), diag::note_template_param_here);
6676 return ExprError();
6677 }
6678
6679 // Add the value of this argument to the list of converted
6680 // arguments. We use the bitwidth and signedness of the template
6681 // parameter.
6682 if (Arg->isValueDependent()) {
6683 // The argument is value-dependent. Create a new
6684 // TemplateArgument with the converted expression.
6685 Converted = TemplateArgument(Arg);
6686 return Arg;
6687 }
6688
6689 QualType IntegerType = Context.getCanonicalType(ParamType);
6690 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6691 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
6692
6693 if (ParamType->isBooleanType()) {
6694 // Value must be zero or one.
6695 Value = Value != 0;
6696 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6697 if (Value.getBitWidth() != AllowedBits)
6698 Value = Value.extOrTrunc(AllowedBits);
6699 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6700 } else {
6701 llvm::APSInt OldValue = Value;
6702
6703 // Coerce the template argument's value to the value it will have
6704 // based on the template parameter's type.
6705 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6706 if (Value.getBitWidth() != AllowedBits)
6707 Value = Value.extOrTrunc(AllowedBits);
6708 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6709
6710 // Complain if an unsigned parameter received a negative value.
6711 if (IntegerType->isUnsignedIntegerOrEnumerationType()
6712 && (OldValue.isSigned() && OldValue.isNegative())) {
6713 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6714 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6715 << Arg->getSourceRange();
6716 Diag(Param->getLocation(), diag::note_template_param_here);
6717 }
6718
6719 // Complain if we overflowed the template parameter's type.
6720 unsigned RequiredBits;
6721 if (IntegerType->isUnsignedIntegerOrEnumerationType())
6722 RequiredBits = OldValue.getActiveBits();
6723 else if (OldValue.isUnsigned())
6724 RequiredBits = OldValue.getActiveBits() + 1;
6725 else
6726 RequiredBits = OldValue.getMinSignedBits();
6727 if (RequiredBits > AllowedBits) {
6728 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6729 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6730 << Arg->getSourceRange();
6731 Diag(Param->getLocation(), diag::note_template_param_here);
6732 }
6733 }
6734
6735 Converted = TemplateArgument(Context, Value,
6736 ParamType->isEnumeralType()
6737 ? Context.getCanonicalType(ParamType)
6738 : IntegerType);
6739 return Arg;
6740 }
6741
6742 QualType ArgType = Arg->getType();
6743 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6744
6745 // Handle pointer-to-function, reference-to-function, and
6746 // pointer-to-member-function all in (roughly) the same way.
6747 if (// -- For a non-type template-parameter of type pointer to
6748 // function, only the function-to-pointer conversion (4.3) is
6749 // applied. If the template-argument represents a set of
6750 // overloaded functions (or a pointer to such), the matching
6751 // function is selected from the set (13.4).
6752 (ParamType->isPointerType() &&
6753 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6754 // -- For a non-type template-parameter of type reference to
6755 // function, no conversions apply. If the template-argument
6756 // represents a set of overloaded functions, the matching
6757 // function is selected from the set (13.4).
6758 (ParamType->isReferenceType() &&
6759 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6760 // -- For a non-type template-parameter of type pointer to
6761 // member function, no conversions apply. If the
6762 // template-argument represents a set of overloaded member
6763 // functions, the matching member function is selected from
6764 // the set (13.4).
6765 (ParamType->isMemberPointerType() &&
6766 ParamType->getAs<MemberPointerType>()->getPointeeType()
6767 ->isFunctionType())) {
6768
6769 if (Arg->getType() == Context.OverloadTy) {
6770 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6771 true,
6772 FoundResult)) {
6773 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
6774 return ExprError();
6775
6776 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6777 ArgType = Arg->getType();
6778 } else
6779 return ExprError();
6780 }
6781
6782 if (!ParamType->isMemberPointerType()) {
6783 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6784 ParamType,
6785 Arg, Converted))
6786 return ExprError();
6787 return Arg;
6788 }
6789
6790 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6791 Converted))
6792 return ExprError();
6793 return Arg;
6794 }
6795
6796 if (ParamType->isPointerType()) {
6797 // -- for a non-type template-parameter of type pointer to
6798 // object, qualification conversions (4.4) and the
6799 // array-to-pointer conversion (4.2) are applied.
6800 // C++0x also allows a value of std::nullptr_t.
6801 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&((ParamType->getPointeeType()->isIncompleteOrObjectType
() && "Only object pointers allowed here") ? static_cast
<void> (0) : __assert_fail ("ParamType->getPointeeType()->isIncompleteOrObjectType() && \"Only object pointers allowed here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6802, __PRETTY_FUNCTION__))
6802 "Only object pointers allowed here")((ParamType->getPointeeType()->isIncompleteOrObjectType
() && "Only object pointers allowed here") ? static_cast
<void> (0) : __assert_fail ("ParamType->getPointeeType()->isIncompleteOrObjectType() && \"Only object pointers allowed here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6802, __PRETTY_FUNCTION__))
;
6803
6804 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6805 ParamType,
6806 Arg, Converted))
6807 return ExprError();
6808 return Arg;
6809 }
6810
6811 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
6812 // -- For a non-type template-parameter of type reference to
6813 // object, no conversions apply. The type referred to by the
6814 // reference may be more cv-qualified than the (otherwise
6815 // identical) type of the template-argument. The
6816 // template-parameter is bound directly to the
6817 // template-argument, which must be an lvalue.
6818 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&((ParamRefType->getPointeeType()->isIncompleteOrObjectType
() && "Only object references allowed here") ? static_cast
<void> (0) : __assert_fail ("ParamRefType->getPointeeType()->isIncompleteOrObjectType() && \"Only object references allowed here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6819, __PRETTY_FUNCTION__))
6819 "Only object references allowed here")((ParamRefType->getPointeeType()->isIncompleteOrObjectType
() && "Only object references allowed here") ? static_cast
<void> (0) : __assert_fail ("ParamRefType->getPointeeType()->isIncompleteOrObjectType() && \"Only object references allowed here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6819, __PRETTY_FUNCTION__))
;
6820
6821 if (Arg->getType() == Context.OverloadTy) {
6822 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6823 ParamRefType->getPointeeType(),
6824 true,
6825 FoundResult)) {
6826 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
6827 return ExprError();
6828
6829 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6830 ArgType = Arg->getType();
6831 } else
6832 return ExprError();
6833 }
6834
6835 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6836 ParamType,
6837 Arg, Converted))
6838 return ExprError();
6839 return Arg;
6840 }
6841
6842 // Deal with parameters of type std::nullptr_t.
6843 if (ParamType->isNullPtrType()) {
6844 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6845 Converted = TemplateArgument(Arg);
6846 return Arg;
6847 }
6848
6849 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6850 case NPV_NotNullPointer:
6851 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6852 << Arg->getType() << ParamType;
6853 Diag(Param->getLocation(), diag::note_template_param_here);
6854 return ExprError();
6855
6856 case NPV_Error:
6857 return ExprError();
6858
6859 case NPV_NullPointer:
6860 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6861 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6862 /*isNullPtr*/true);
6863 return Arg;
6864 }
6865 }
6866
6867 // -- For a non-type template-parameter of type pointer to data
6868 // member, qualification conversions (4.4) are applied.
6869 assert(ParamType->isMemberPointerType() && "Only pointers to members remain")((ParamType->isMemberPointerType() && "Only pointers to members remain"
) ? static_cast<void> (0) : __assert_fail ("ParamType->isMemberPointerType() && \"Only pointers to members remain\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6869, __PRETTY_FUNCTION__))
;
6870
6871 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6872 Converted))
6873 return ExprError();
6874 return Arg;
6875}
6876
6877static void DiagnoseTemplateParameterListArityMismatch(
6878 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6879 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6880
6881/// Check a template argument against its corresponding
6882/// template template parameter.
6883///
6884/// This routine implements the semantics of C++ [temp.arg.template].
6885/// It returns true if an error occurred, and false otherwise.
6886bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params,
6887 TemplateArgumentLoc &Arg) {
6888 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
6889 TemplateDecl *Template = Name.getAsTemplateDecl();
6890 if (!Template) {
6891 // Any dependent template name is fine.
6892 assert(Name.isDependent() && "Non-dependent template isn't a declaration?")((Name.isDependent() && "Non-dependent template isn't a declaration?"
) ? static_cast<void> (0) : __assert_fail ("Name.isDependent() && \"Non-dependent template isn't a declaration?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6892, __PRETTY_FUNCTION__))
;
6893 return false;
6894 }
6895
6896 if (Template->isInvalidDecl())
6897 return true;
6898
6899 // C++0x [temp.arg.template]p1:
6900 // A template-argument for a template template-parameter shall be
6901 // the name of a class template or an alias template, expressed as an
6902 // id-expression. When the template-argument names a class template, only
6903 // primary class templates are considered when matching the
6904 // template template argument with the corresponding parameter;
6905 // partial specializations are not considered even if their
6906 // parameter lists match that of the template template parameter.
6907 //
6908 // Note that we also allow template template parameters here, which
6909 // will happen when we are dealing with, e.g., class template
6910 // partial specializations.
6911 if (!isa<ClassTemplateDecl>(Template) &&
6912 !isa<TemplateTemplateParmDecl>(Template) &&
6913 !isa<TypeAliasTemplateDecl>(Template) &&
6914 !isa<BuiltinTemplateDecl>(Template)) {
6915 assert(isa<FunctionTemplateDecl>(Template) &&((isa<FunctionTemplateDecl>(Template) && "Only function templates are possible here"
) ? static_cast<void> (0) : __assert_fail ("isa<FunctionTemplateDecl>(Template) && \"Only function templates are possible here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6916, __PRETTY_FUNCTION__))
6916 "Only function templates are possible here")((isa<FunctionTemplateDecl>(Template) && "Only function templates are possible here"
) ? static_cast<void> (0) : __assert_fail ("isa<FunctionTemplateDecl>(Template) && \"Only function templates are possible here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6916, __PRETTY_FUNCTION__))
;
6917 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
6918 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6919 << Template;
6920 }
6921
6922 // C++1z [temp.arg.template]p3: (DR 150)
6923 // A template-argument matches a template template-parameter P when P
6924 // is at least as specialized as the template-argument A.
6925 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6926 // Quick check for the common case:
6927 // If P contains a parameter pack, then A [...] matches P if each of A's
6928 // template parameters matches the corresponding template parameter in
6929 // the template-parameter-list of P.
6930 if (TemplateParameterListsAreEqual(
6931 Template->getTemplateParameters(), Params, false,
6932 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6933 return false;
6934
6935 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6936 Arg.getLocation()))
6937 return false;
6938 // FIXME: Produce better diagnostics for deduction failures.
6939 }
6940
6941 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
6942 Params,
6943 true,
6944 TPL_TemplateTemplateArgumentMatch,
6945 Arg.getLocation());
6946}
6947
6948/// Given a non-type template argument that refers to a
6949/// declaration and the type of its corresponding non-type template
6950/// parameter, produce an expression that properly refers to that
6951/// declaration.
6952ExprResult
6953Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6954 QualType ParamType,
6955 SourceLocation Loc) {
6956 // C++ [temp.param]p8:
6957 //
6958 // A non-type template-parameter of type "array of T" or
6959 // "function returning T" is adjusted to be of type "pointer to
6960 // T" or "pointer to function returning T", respectively.
6961 if (ParamType->isArrayType())
6962 ParamType = Context.getArrayDecayedType(ParamType);
6963 else if (ParamType->isFunctionType())
6964 ParamType = Context.getPointerType(ParamType);
6965
6966 // For a NULL non-type template argument, return nullptr casted to the
6967 // parameter's type.
6968 if (Arg.getKind() == TemplateArgument::NullPtr) {
6969 return ImpCastExprToType(
6970 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6971 ParamType,
6972 ParamType->getAs<MemberPointerType>()
6973 ? CK_NullToMemberPointer
6974 : CK_NullToPointer);
6975 }
6976 assert(Arg.getKind() == TemplateArgument::Declaration &&((Arg.getKind() == TemplateArgument::Declaration && "Only declaration template arguments permitted here"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Declaration && \"Only declaration template arguments permitted here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6977, __PRETTY_FUNCTION__))
6977 "Only declaration template arguments permitted here")((Arg.getKind() == TemplateArgument::Declaration && "Only declaration template arguments permitted here"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Declaration && \"Only declaration template arguments permitted here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6977, __PRETTY_FUNCTION__))
;
6978
6979 ValueDecl *VD = Arg.getAsDecl();
6980
6981 if (VD->getDeclContext()->isRecord() &&
6982 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6983 isa<IndirectFieldDecl>(VD))) {
6984 // If the value is a class member, we might have a pointer-to-member.
6985 // Determine whether the non-type template template parameter is of
6986 // pointer-to-member type. If so, we need to build an appropriate
6987 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6988 // would refer to the member itself.
6989 if (ParamType->isMemberPointerType()) {
6990 QualType ClassType
6991 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6992 NestedNameSpecifier *Qualifier
6993 = NestedNameSpecifier::Create(Context, nullptr, false,
6994 ClassType.getTypePtr());
6995 CXXScopeSpec SS;
6996 SS.MakeTrivial(Context, Qualifier, Loc);
6997
6998 // The actual value-ness of this is unimportant, but for
6999 // internal consistency's sake, references to instance methods
7000 // are r-values.
7001 ExprValueKind VK = VK_LValue;
7002 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
7003 VK = VK_RValue;
7004
7005 ExprResult RefExpr = BuildDeclRefExpr(VD,
7006 VD->getType().getNonReferenceType(),
7007 VK,
7008 Loc,
7009 &SS);
7010 if (RefExpr.isInvalid())
7011 return ExprError();
7012
7013 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7014
7015 // We might need to perform a trailing qualification conversion, since
7016 // the element type on the parameter could be more qualified than the
7017 // element type in the expression we constructed.
7018 bool ObjCLifetimeConversion;
7019 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
7020 ParamType.getUnqualifiedType(), false,
7021 ObjCLifetimeConversion))
7022 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
7023
7024 assert(!RefExpr.isInvalid() &&((!RefExpr.isInvalid() && Context.hasSameType(((Expr*
) RefExpr.get())->getType(), ParamType.getUnqualifiedType(
))) ? static_cast<void> (0) : __assert_fail ("!RefExpr.isInvalid() && Context.hasSameType(((Expr*) RefExpr.get())->getType(), ParamType.getUnqualifiedType())"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7026, __PRETTY_FUNCTION__))
7025 Context.hasSameType(((Expr*) RefExpr.get())->getType(),((!RefExpr.isInvalid() && Context.hasSameType(((Expr*
) RefExpr.get())->getType(), ParamType.getUnqualifiedType(
))) ? static_cast<void> (0) : __assert_fail ("!RefExpr.isInvalid() && Context.hasSameType(((Expr*) RefExpr.get())->getType(), ParamType.getUnqualifiedType())"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7026, __PRETTY_FUNCTION__))
7026 ParamType.getUnqualifiedType()))((!RefExpr.isInvalid() && Context.hasSameType(((Expr*
) RefExpr.get())->getType(), ParamType.getUnqualifiedType(
))) ? static_cast<void> (0) : __assert_fail ("!RefExpr.isInvalid() && Context.hasSameType(((Expr*) RefExpr.get())->getType(), ParamType.getUnqualifiedType())"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7026, __PRETTY_FUNCTION__))
;
7027 return RefExpr;
7028 }
7029 }
7030
7031 QualType T = VD->getType().getNonReferenceType();
7032
7033 if (ParamType->isPointerType()) {
7034 // When the non-type template parameter is a pointer, take the
7035 // address of the declaration.
7036 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
7037 if (RefExpr.isInvalid())
7038 return ExprError();
7039
7040 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
7041 (T->isFunctionType() || T->isArrayType())) {
7042 // Decay functions and arrays unless we're forming a pointer to array.
7043 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7044 if (RefExpr.isInvalid())
7045 return ExprError();
7046
7047 return RefExpr;
7048 }
7049
7050 // Take the address of everything else
7051 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7052 }
7053
7054 ExprValueKind VK = VK_RValue;
7055
7056 // If the non-type template parameter has reference type, qualify the
7057 // resulting declaration reference with the extra qualifiers on the
7058 // type that the reference refers to.
7059 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
7060 VK = VK_LValue;
7061 T = Context.getQualifiedType(T,
7062 TargetRef->getPointeeType().getQualifiers());
7063 } else if (isa<FunctionDecl>(VD)) {
7064 // References to functions are always lvalues.
7065 VK = VK_LValue;
7066 }
7067
7068 return BuildDeclRefExpr(VD, T, VK, Loc);
7069}
7070
7071/// Construct a new expression that refers to the given
7072/// integral template argument with the given source-location
7073/// information.
7074///
7075/// This routine takes care of the mapping from an integral template
7076/// argument (which may have any integral type) to the appropriate
7077/// literal value.
7078ExprResult
7079Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7080 SourceLocation Loc) {
7081 assert(Arg.getKind() == TemplateArgument::Integral &&((Arg.getKind() == TemplateArgument::Integral && "Operation is only valid for integral template arguments"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Integral && \"Operation is only valid for integral template arguments\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7082, __PRETTY_FUNCTION__))
7082 "Operation is only valid for integral template arguments")((Arg.getKind() == TemplateArgument::Integral && "Operation is only valid for integral template arguments"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Integral && \"Operation is only valid for integral template arguments\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7082, __PRETTY_FUNCTION__))
;
7083 QualType OrigT = Arg.getIntegralType();
7084
7085 // If this is an enum type that we're instantiating, we need to use an integer
7086 // type the same size as the enumerator. We don't want to build an
7087 // IntegerLiteral with enum type. The integer type of an enum type can be of
7088 // any integral type with C++11 enum classes, make sure we create the right
7089 // type of literal for it.
7090 QualType T = OrigT;
7091 if (const EnumType *ET = OrigT->getAs<EnumType>())
7092 T = ET->getDecl()->getIntegerType();
7093
7094 Expr *E;
7095 if (T->isAnyCharacterType()) {
7096 CharacterLiteral::CharacterKind Kind;
7097 if (T->isWideCharType())
7098 Kind = CharacterLiteral::Wide;
7099 else if (T->isChar8Type() && getLangOpts().Char8)
7100 Kind = CharacterLiteral::UTF8;
7101 else if (T->isChar16Type())
7102 Kind = CharacterLiteral::UTF16;
7103 else if (T->isChar32Type())
7104 Kind = CharacterLiteral::UTF32;
7105 else
7106 Kind = CharacterLiteral::Ascii;
7107
7108 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
7109 Kind, T, Loc);
7110 } else if (T->isBooleanType()) {
7111 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
7112 T, Loc);
7113 } else if (T->isNullPtrType()) {
7114 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
7115 } else {
7116 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
7117 }
7118
7119 if (OrigT->isEnumeralType()) {
7120 // FIXME: This is a hack. We need a better way to handle substituted
7121 // non-type template parameters.
7122 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
7123 nullptr,
7124 Context.getTrivialTypeSourceInfo(OrigT, Loc),
7125 Loc, Loc);
7126 }
7127
7128 return E;
7129}
7130
7131/// Match two template parameters within template parameter lists.
7132static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
7133 bool Complain,
7134 Sema::TemplateParameterListEqualKind Kind,
7135 SourceLocation TemplateArgLoc) {
7136 // Check the actual kind (type, non-type, template).
7137 if (Old->getKind() != New->getKind()) {
7138 if (Complain) {
7139 unsigned NextDiag = diag::err_template_param_different_kind;
7140 if (TemplateArgLoc.isValid()) {
7141 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7142 NextDiag = diag::note_template_param_different_kind;
7143 }
7144 S.Diag(New->getLocation(), NextDiag)
7145 << (Kind != Sema::TPL_TemplateMatch);
7146 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7147 << (Kind != Sema::TPL_TemplateMatch);
7148 }
7149
7150 return false;
7151 }
7152
7153 // Check that both are parameter packs or neither are parameter packs.
7154 // However, if we are matching a template template argument to a
7155 // template template parameter, the template template parameter can have
7156 // a parameter pack where the template template argument does not.
7157 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7158 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
7159 Old->isTemplateParameterPack())) {
7160 if (Complain) {
7161 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7162 if (TemplateArgLoc.isValid()) {
7163 S.Diag(TemplateArgLoc,
7164 diag::err_template_arg_template_params_mismatch);
7165 NextDiag = diag::note_template_parameter_pack_non_pack;
7166 }
7167
7168 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7169 : isa<NonTypeTemplateParmDecl>(New)? 1
7170 : 2;
7171 S.Diag(New->getLocation(), NextDiag)
7172 << ParamKind << New->isParameterPack();
7173 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7174 << ParamKind << Old->isParameterPack();
7175 }
7176
7177 return false;
7178 }
7179
7180 // For non-type template parameters, check the type of the parameter.
7181 if (NonTypeTemplateParmDecl *OldNTTP
7182 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7183 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7184
7185 // If we are matching a template template argument to a template
7186 // template parameter and one of the non-type template parameter types
7187 // is dependent, then we must wait until template instantiation time
7188 // to actually compare the arguments.
7189 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
7190 (OldNTTP->getType()->isDependentType() ||
7191 NewNTTP->getType()->isDependentType()))
7192 return true;
7193
7194 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
7195 if (Complain) {
7196 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7197 if (TemplateArgLoc.isValid()) {
7198 S.Diag(TemplateArgLoc,
7199 diag::err_template_arg_template_params_mismatch);
7200 NextDiag = diag::note_template_nontype_parm_different_type;
7201 }
7202 S.Diag(NewNTTP->getLocation(), NextDiag)
7203 << NewNTTP->getType()
7204 << (Kind != Sema::TPL_TemplateMatch);
7205 S.Diag(OldNTTP->getLocation(),
7206 diag::note_template_nontype_parm_prev_declaration)
7207 << OldNTTP->getType();
7208 }
7209
7210 return false;
7211 }
7212
7213 return true;
7214 }
7215
7216 // For template template parameters, check the template parameter types.
7217 // The template parameter lists of template template
7218 // parameters must agree.
7219 if (TemplateTemplateParmDecl *OldTTP
7220 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
7221 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7222 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
7223 OldTTP->getTemplateParameters(),
7224 Complain,
7225 (Kind == Sema::TPL_TemplateMatch
7226 ? Sema::TPL_TemplateTemplateParmMatch
7227 : Kind),
7228 TemplateArgLoc);
7229 }
7230
7231 return true;
7232}
7233
7234/// Diagnose a known arity mismatch when comparing template argument
7235/// lists.
7236static
7237void DiagnoseTemplateParameterListArityMismatch(Sema &S,
7238 TemplateParameterList *New,
7239 TemplateParameterList *Old,
7240 Sema::TemplateParameterListEqualKind Kind,
7241 SourceLocation TemplateArgLoc) {
7242 unsigned NextDiag = diag::err_template_param_list_different_arity;
7243 if (TemplateArgLoc.isValid()) {
7244 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7245 NextDiag = diag::note_template_param_list_different_arity;
7246 }
7247 S.Diag(New->getTemplateLoc(), NextDiag)
7248 << (New->size() > Old->size())
7249 << (Kind != Sema::TPL_TemplateMatch)
7250 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7251 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7252 << (Kind != Sema::TPL_TemplateMatch)
7253 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7254}
7255
7256/// Determine whether the given template parameter lists are
7257/// equivalent.
7258///
7259/// \param New The new template parameter list, typically written in the
7260/// source code as part of a new template declaration.
7261///
7262/// \param Old The old template parameter list, typically found via
7263/// name lookup of the template declared with this template parameter
7264/// list.
7265///
7266/// \param Complain If true, this routine will produce a diagnostic if
7267/// the template parameter lists are not equivalent.
7268///
7269/// \param Kind describes how we are to match the template parameter lists.
7270///
7271/// \param TemplateArgLoc If this source location is valid, then we
7272/// are actually checking the template parameter list of a template
7273/// argument (New) against the template parameter list of its
7274/// corresponding template template parameter (Old). We produce
7275/// slightly different diagnostics in this scenario.
7276///
7277/// \returns True if the template parameter lists are equal, false
7278/// otherwise.
7279bool
7280Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7281 TemplateParameterList *Old,
7282 bool Complain,
7283 TemplateParameterListEqualKind Kind,
7284 SourceLocation TemplateArgLoc) {
7285 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7286 if (Complain)
7287 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7288 TemplateArgLoc);
7289
7290 return false;
7291 }
7292
7293 // C++0x [temp.arg.template]p3:
7294 // A template-argument matches a template template-parameter (call it P)
7295 // when each of the template parameters in the template-parameter-list of
7296 // the template-argument's corresponding class template or alias template
7297 // (call it A) matches the corresponding template parameter in the
7298 // template-parameter-list of P. [...]
7299 TemplateParameterList::iterator NewParm = New->begin();
7300 TemplateParameterList::iterator NewParmEnd = New->end();
7301 for (TemplateParameterList::iterator OldParm = Old->begin(),
7302 OldParmEnd = Old->end();
7303 OldParm != OldParmEnd; ++OldParm) {
7304 if (Kind != TPL_TemplateTemplateArgumentMatch ||
7305 !(*OldParm)->isTemplateParameterPack()) {
7306 if (NewParm == NewParmEnd) {
7307 if (Complain)
7308 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7309 TemplateArgLoc);
7310
7311 return false;
7312 }
7313
7314 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7315 Kind, TemplateArgLoc))
7316 return false;
7317
7318 ++NewParm;
7319 continue;
7320 }
7321
7322 // C++0x [temp.arg.template]p3:
7323 // [...] When P's template- parameter-list contains a template parameter
7324 // pack (14.5.3), the template parameter pack will match zero or more
7325 // template parameters or template parameter packs in the
7326 // template-parameter-list of A with the same type and form as the
7327 // template parameter pack in P (ignoring whether those template
7328 // parameters are template parameter packs).
7329 for (; NewParm != NewParmEnd; ++NewParm) {
7330 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7331 Kind, TemplateArgLoc))
7332 return false;
7333 }
7334 }
7335
7336 // Make sure we exhausted all of the arguments.
7337 if (NewParm != NewParmEnd) {
7338 if (Complain)
7339 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7340 TemplateArgLoc);
7341
7342 return false;
7343 }
7344
7345 return true;
7346}
7347
7348/// Check whether a template can be declared within this scope.
7349///
7350/// If the template declaration is valid in this scope, returns
7351/// false. Otherwise, issues a diagnostic and returns true.
7352bool
7353Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
7354 if (!S)
7355 return false;
7356
7357 // Find the nearest enclosing declaration scope.
7358 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7359 (S->getFlags() & Scope::TemplateParamScope) != 0)
7360 S = S->getParent();
7361
7362 // C++ [temp]p4:
7363 // A template [...] shall not have C linkage.
7364 DeclContext *Ctx = S->getEntity();
7365 if (Ctx && Ctx->isExternCContext()) {
7366 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7367 << TemplateParams->getSourceRange();
7368 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7369 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7370 return true;
7371 }
7372 Ctx = Ctx->getRedeclContext();
7373
7374 // C++ [temp]p2:
7375 // A template-declaration can appear only as a namespace scope or
7376 // class scope declaration.
7377 if (Ctx) {
7378 if (Ctx->isFileContext())
7379 return false;
7380 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7381 // C++ [temp.mem]p2:
7382 // A local class shall not have member templates.
7383 if (RD->isLocalClass())
7384 return Diag(TemplateParams->getTemplateLoc(),
7385 diag::err_template_inside_local_class)
7386 << TemplateParams->getSourceRange();
7387 else
7388 return false;
7389 }
7390 }
7391
7392 return Diag(TemplateParams->getTemplateLoc(),
7393 diag::err_template_outside_namespace_or_class_scope)
7394 << TemplateParams->getSourceRange();
7395}
7396
7397/// Determine what kind of template specialization the given declaration
7398/// is.
7399static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
7400 if (!D)
7401 return TSK_Undeclared;
7402
7403 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7404 return Record->getTemplateSpecializationKind();
7405 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7406 return Function->getTemplateSpecializationKind();
7407 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7408 return Var->getTemplateSpecializationKind();
7409
7410 return TSK_Undeclared;
7411}
7412
7413/// Check whether a specialization is well-formed in the current
7414/// context.
7415///
7416/// This routine determines whether a template specialization can be declared
7417/// in the current context (C++ [temp.expl.spec]p2).
7418///
7419/// \param S the semantic analysis object for which this check is being
7420/// performed.
7421///
7422/// \param Specialized the entity being specialized or instantiated, which
7423/// may be a kind of template (class template, function template, etc.) or
7424/// a member of a class template (member function, static data member,
7425/// member class).
7426///
7427/// \param PrevDecl the previous declaration of this entity, if any.
7428///
7429/// \param Loc the location of the explicit specialization or instantiation of
7430/// this entity.
7431///
7432/// \param IsPartialSpecialization whether this is a partial specialization of
7433/// a class template.
7434///
7435/// \returns true if there was an error that we cannot recover from, false
7436/// otherwise.
7437static bool CheckTemplateSpecializationScope(Sema &S,
7438 NamedDecl *Specialized,
7439 NamedDecl *PrevDecl,
7440 SourceLocation Loc,
7441 bool IsPartialSpecialization) {
7442 // Keep these "kind" numbers in sync with the %select statements in the
7443 // various diagnostics emitted by this routine.
7444 int EntityKind = 0;
7445 if (isa<ClassTemplateDecl>(Specialized))
7446 EntityKind = IsPartialSpecialization? 1 : 0;
7447 else if (isa<VarTemplateDecl>(Specialized))
7448 EntityKind = IsPartialSpecialization ? 3 : 2;
7449 else if (isa<FunctionTemplateDecl>(Specialized))
7450 EntityKind = 4;
7451 else if (isa<CXXMethodDecl>(Specialized))
7452 EntityKind = 5;
7453 else if (isa<VarDecl>(Specialized))
7454 EntityKind = 6;
7455 else if (isa<RecordDecl>(Specialized))
7456 EntityKind = 7;
7457 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7458 EntityKind = 8;
7459 else {
7460 S.Diag(Loc, diag::err_template_spec_unknown_kind)
7461 << S.getLangOpts().CPlusPlus11;
7462 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7463 return true;
7464 }
7465
7466 // C++ [temp.expl.spec]p2:
7467 // An explicit specialization may be declared in any scope in which
7468 // the corresponding primary template may be defined.
7469 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7470 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
7471 << Specialized;
7472 return true;
7473 }
7474
7475 // C++ [temp.class.spec]p6:
7476 // A class template partial specialization may be declared in any
7477 // scope in which the primary template may be defined.
7478 DeclContext *SpecializedContext =
7479 Specialized->getDeclContext()->getRedeclContext();
7480 DeclContext *DC = S.CurContext->getRedeclContext();
7481
7482 // Make sure that this redeclaration (or definition) occurs in the same
7483 // scope or an enclosing namespace.
7484 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7485 : DC->Equals(SpecializedContext))) {
7486 if (isa<TranslationUnitDecl>(SpecializedContext))
7487 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7488 << EntityKind << Specialized;
7489 else {
7490 auto *ND = cast<NamedDecl>(SpecializedContext);
7491 int Diag = diag::err_template_spec_redecl_out_of_scope;
7492 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
7493 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7494 S.Diag(Loc, Diag) << EntityKind << Specialized
7495 << ND << isa<CXXRecordDecl>(ND);
7496 }
7497
7498 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7499
7500 // Don't allow specializing in the wrong class during error recovery.
7501 // Otherwise, things can go horribly wrong.
7502 if (DC->isRecord())
7503 return true;
7504 }
7505
7506 return false;
7507}
7508
7509static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7510 if (!E->isTypeDependent())
7511 return SourceLocation();
7512 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7513 Checker.TraverseStmt(E);
7514 if (Checker.MatchLoc.isInvalid())
7515 return E->getSourceRange();
7516 return Checker.MatchLoc;
7517}
7518
7519static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7520 if (!TL.getType()->isDependentType())
7521 return SourceLocation();
7522 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7523 Checker.TraverseTypeLoc(TL);
7524 if (Checker.MatchLoc.isInvalid())
7525 return TL.getSourceRange();
7526 return Checker.MatchLoc;
7527}
7528
7529/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7530/// that checks non-type template partial specialization arguments.
7531static bool CheckNonTypeTemplatePartialSpecializationArgs(
7532 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7533 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7534 for (unsigned I = 0; I != NumArgs; ++I) {
7535 if (Args[I].getKind() == TemplateArgument::Pack) {
7536 if (CheckNonTypeTemplatePartialSpecializationArgs(
7537 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7538 Args[I].pack_size(), IsDefaultArgument))
7539 return true;
7540
7541 continue;
7542 }
7543
7544 if (Args[I].getKind() != TemplateArgument::Expression)
7545 continue;
7546
7547 Expr *ArgExpr = Args[I].getAsExpr();
7548
7549 // We can have a pack expansion of any of the bullets below.
7550 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7551 ArgExpr = Expansion->getPattern();
7552
7553 // Strip off any implicit casts we added as part of type checking.
7554 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7555 ArgExpr = ICE->getSubExpr();
7556
7557 // C++ [temp.class.spec]p8:
7558 // A non-type argument is non-specialized if it is the name of a
7559 // non-type parameter. All other non-type arguments are
7560 // specialized.
7561 //
7562 // Below, we check the two conditions that only apply to
7563 // specialized non-type arguments, so skip any non-specialized
7564 // arguments.
7565 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7566 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7567 continue;
7568
7569 // C++ [temp.class.spec]p9:
7570 // Within the argument list of a class template partial
7571 // specialization, the following restrictions apply:
7572 // -- A partially specialized non-type argument expression
7573 // shall not involve a template parameter of the partial
7574 // specialization except when the argument expression is a
7575 // simple identifier.
7576 // -- The type of a template parameter corresponding to a
7577 // specialized non-type argument shall not be dependent on a
7578 // parameter of the specialization.
7579 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7580 // We implement a compromise between the original rules and DR1315:
7581 // -- A specialized non-type template argument shall not be
7582 // type-dependent and the corresponding template parameter
7583 // shall have a non-dependent type.
7584 SourceRange ParamUseRange =
7585 findTemplateParameterInType(Param->getDepth(), ArgExpr);
7586 if (ParamUseRange.isValid()) {
7587 if (IsDefaultArgument) {
7588 S.Diag(TemplateNameLoc,
7589 diag::err_dependent_non_type_arg_in_partial_spec);
7590 S.Diag(ParamUseRange.getBegin(),
7591 diag::note_dependent_non_type_default_arg_in_partial_spec)
7592 << ParamUseRange;
7593 } else {
7594 S.Diag(ParamUseRange.getBegin(),
7595 diag::err_dependent_non_type_arg_in_partial_spec)
7596 << ParamUseRange;
7597 }
7598 return true;
7599 }
7600
7601 ParamUseRange = findTemplateParameter(
7602 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
7603 if (ParamUseRange.isValid()) {
7604 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
7605 diag::err_dependent_typed_non_type_arg_in_partial_spec)
7606 << Param->getType();
7607 S.Diag(Param->getLocation(), diag::note_template_param_here)
7608 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7609 << ParamUseRange;
7610 return true;
7611 }
7612 }
7613
7614 return false;
7615}
7616
7617/// Check the non-type template arguments of a class template
7618/// partial specialization according to C++ [temp.class.spec]p9.
7619///
7620/// \param TemplateNameLoc the location of the template name.
7621/// \param PrimaryTemplate the template parameters of the primary class
7622/// template.
7623/// \param NumExplicit the number of explicitly-specified template arguments.
7624/// \param TemplateArgs the template arguments of the class template
7625/// partial specialization.
7626///
7627/// \returns \c true if there was an error, \c false otherwise.
7628bool Sema::CheckTemplatePartialSpecializationArgs(
7629 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7630 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7631 // We have to be conservative when checking a template in a dependent
7632 // context.
7633 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7634 return false;
7635
7636 TemplateParameterList *TemplateParams =
7637 PrimaryTemplate->getTemplateParameters();
7638 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7639 NonTypeTemplateParmDecl *Param
7640 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7641 if (!Param)
7642 continue;
7643
7644 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7645 Param, &TemplateArgs[I],
7646 1, I >= NumExplicit))
7647 return true;
7648 }
7649
7650 return false;
7651}
7652
7653DeclResult Sema::ActOnClassTemplateSpecialization(
7654 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7655 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7656 const ParsedAttributesView &Attr,
7657 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
7658 assert(TUK != TUK_Reference && "References are not specializations")((TUK != TUK_Reference && "References are not specializations"
) ? static_cast<void> (0) : __assert_fail ("TUK != TUK_Reference && \"References are not specializations\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7658, __PRETTY_FUNCTION__))
;
7659
7660 CXXScopeSpec &SS = TemplateId.SS;
7661
7662 // NOTE: KWLoc is the location of the tag keyword. This will instead
7663 // store the location of the outermost template keyword in the declaration.
7664 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7665 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7666 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7667 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7668 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7669
7670 // Find the class template we're specializing
7671 TemplateName Name = TemplateId.Template.get();
7672 ClassTemplateDecl *ClassTemplate
7673 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7674
7675 if (!ClassTemplate) {
7676 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7677 << (Name.getAsTemplateDecl() &&
7678 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7679 return true;
7680 }
7681
7682 bool isMemberSpecialization = false;
7683 bool isPartialSpecialization = false;
7684
7685 // Check the validity of the template headers that introduce this
7686 // template.
7687 // FIXME: We probably shouldn't complain about these headers for
7688 // friend declarations.
7689 bool Invalid = false;
7690 TemplateParameterList *TemplateParams =
7691 MatchTemplateParametersToScopeSpecifier(
7692 KWLoc, TemplateNameLoc, SS, &TemplateId,
7693 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7694 Invalid);
7695 if (Invalid)
7696 return true;
7697
7698 if (TemplateParams && TemplateParams->size() > 0) {
7699 isPartialSpecialization = true;
7700
7701 if (TUK == TUK_Friend) {
7702 Diag(KWLoc, diag::err_partial_specialization_friend)
7703 << SourceRange(LAngleLoc, RAngleLoc);
7704 return true;
7705 }
7706
7707 // C++ [temp.class.spec]p10:
7708 // The template parameter list of a specialization shall not
7709 // contain default template argument values.
7710 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7711 Decl *Param = TemplateParams->getParam(I);
7712 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7713 if (TTP->hasDefaultArgument()) {
7714 Diag(TTP->getDefaultArgumentLoc(),
7715 diag::err_default_arg_in_partial_spec);
7716 TTP->removeDefaultArgument();
7717 }
7718 } else if (NonTypeTemplateParmDecl *NTTP
7719 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7720 if (Expr *DefArg = NTTP->getDefaultArgument()) {
7721 Diag(NTTP->getDefaultArgumentLoc(),
7722 diag::err_default_arg_in_partial_spec)
7723 << DefArg->getSourceRange();
7724 NTTP->removeDefaultArgument();
7725 }
7726 } else {
7727 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
7728 if (TTP->hasDefaultArgument()) {
7729 Diag(TTP->getDefaultArgument().getLocation(),
7730 diag::err_default_arg_in_partial_spec)
7731 << TTP->getDefaultArgument().getSourceRange();
7732 TTP->removeDefaultArgument();
7733 }
7734 }
7735 }
7736 } else if (TemplateParams) {
7737 if (TUK == TUK_Friend)
7738 Diag(KWLoc, diag::err_template_spec_friend)
7739 << FixItHint::CreateRemoval(
7740 SourceRange(TemplateParams->getTemplateLoc(),
7741 TemplateParams->getRAngleLoc()))
7742 << SourceRange(LAngleLoc, RAngleLoc);
7743 } else {
7744 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl")((TUK == TUK_Friend && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("TUK == TUK_Friend && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7744, __PRETTY_FUNCTION__))
;
7745 }
7746
7747 // Check that the specialization uses the same tag kind as the
7748 // original template.
7749 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7750 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!")((Kind != TTK_Enum && "Invalid enum tag in class template spec!"
) ? static_cast<void> (0) : __assert_fail ("Kind != TTK_Enum && \"Invalid enum tag in class template spec!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7750, __PRETTY_FUNCTION__))
;
7751 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7752 Kind, TUK == TUK_Definition, KWLoc,
7753 ClassTemplate->getIdentifier())) {
7754 Diag(KWLoc, diag::err_use_with_wrong_tag)
7755 << ClassTemplate
7756 << FixItHint::CreateReplacement(KWLoc,
7757 ClassTemplate->getTemplatedDecl()->getKindName());
7758 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7759 diag::note_previous_use);
7760 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7761 }
7762
7763 // Translate the parser's template argument list in our AST format.
7764 TemplateArgumentListInfo TemplateArgs =
7765 makeTemplateArgumentListInfo(*this, TemplateId);
7766
7767 // Check for unexpanded parameter packs in any of the template arguments.
7768 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7769 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
7770 UPPC_PartialSpecialization))
7771 return true;
7772
7773 // Check that the template argument list is well-formed for this
7774 // template.
7775 SmallVector<TemplateArgument, 4> Converted;
7776 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7777 TemplateArgs, false, Converted))
7778 return true;
7779
7780 // Find the class template (partial) specialization declaration that
7781 // corresponds to these arguments.
7782 if (isPartialSpecialization) {
7783 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7784 TemplateArgs.size(), Converted))
7785 return true;
7786
7787 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7788 // also do it during instantiation.
7789 bool InstantiationDependent;
7790 if (!Name.isDependent() &&
7791 !TemplateSpecializationType::anyDependentTemplateArguments(
7792 TemplateArgs.arguments(), InstantiationDependent)) {
7793 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7794 << ClassTemplate->getDeclName();
7795 isPartialSpecialization = false;
7796 }
7797 }
7798
7799 void *InsertPos = nullptr;
7800 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
7801
7802 if (isPartialSpecialization)
7803 // FIXME: Template parameter list matters, too
7804 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
7805 else
7806 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
7807
7808 ClassTemplateSpecializationDecl *Specialization = nullptr;
7809
7810 // Check whether we can declare a class template specialization in
7811 // the current scope.
7812 if (TUK != TUK_Friend &&
7813 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7814 TemplateNameLoc,
7815 isPartialSpecialization))
7816 return true;
7817
7818 // The canonical type
7819 QualType CanonType;
7820 if (isPartialSpecialization) {
7821 // Build the canonical type that describes the converted template
7822 // arguments of the class template partial specialization.
7823 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7824 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
7825 Converted);
7826
7827 if (Context.hasSameType(CanonType,
7828 ClassTemplate->getInjectedClassNameSpecialization())) {
7829 // C++ [temp.class.spec]p9b3:
7830 //
7831 // -- The argument list of the specialization shall not be identical
7832 // to the implicit argument list of the primary template.
7833 //
7834 // This rule has since been removed, because it's redundant given DR1495,
7835 // but we keep it because it produces better diagnostics and recovery.
7836 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
7837 << /*class template*/0 << (TUK == TUK_Definition)
7838 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
7839 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7840 ClassTemplate->getIdentifier(),
7841 TemplateNameLoc,
7842 Attr,
7843 TemplateParams,
7844 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
7845 /*FriendLoc*/SourceLocation(),
7846 TemplateParameterLists.size() - 1,
7847 TemplateParameterLists.data());
7848 }
7849
7850 // Create a new class template partial specialization declaration node.
7851 ClassTemplatePartialSpecializationDecl *PrevPartial
7852 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
7853 ClassTemplatePartialSpecializationDecl *Partial
7854 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
7855 ClassTemplate->getDeclContext(),
7856 KWLoc, TemplateNameLoc,
7857 TemplateParams,
7858 ClassTemplate,
7859 Converted,
7860 TemplateArgs,
7861 CanonType,
7862 PrevPartial);
7863 SetNestedNameSpecifier(*this, Partial, SS);
7864 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
7865 Partial->setTemplateParameterListsInfo(
7866 Context, TemplateParameterLists.drop_back(1));
7867 }
7868
7869 if (!PrevPartial)
7870 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
7871 Specialization = Partial;
7872
7873 // If we are providing an explicit specialization of a member class
7874 // template specialization, make a note of that.
7875 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7876 PrevPartial->setMemberSpecialization();
7877
7878 CheckTemplatePartialSpecialization(Partial);
7879 } else {
7880 // Create a new class template specialization declaration node for
7881 // this explicit specialization or friend declaration.
7882 Specialization
7883 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7884 ClassTemplate->getDeclContext(),
7885 KWLoc, TemplateNameLoc,
7886 ClassTemplate,
7887 Converted,
7888 PrevDecl);
7889 SetNestedNameSpecifier(*this, Specialization, SS);
7890 if (TemplateParameterLists.size() > 0) {
7891 Specialization->setTemplateParameterListsInfo(Context,
7892 TemplateParameterLists);
7893 }
7894
7895 if (!PrevDecl)
7896 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7897
7898 if (CurContext->isDependentContext()) {
7899 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7900 CanonType = Context.getTemplateSpecializationType(
7901 CanonTemplate, Converted);
7902 } else {
7903 CanonType = Context.getTypeDeclType(Specialization);
7904 }
7905 }
7906
7907 // C++ [temp.expl.spec]p6:
7908 // If a template, a member template or the member of a class template is
7909 // explicitly specialized then that specialization shall be declared
7910 // before the first use of that specialization that would cause an implicit
7911 // instantiation to take place, in every translation unit in which such a
7912 // use occurs; no diagnostic is required.
7913 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
7914 bool Okay = false;
7915 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7916 // Is there any previous explicit specialization declaration?
7917 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7918 Okay = true;
7919 break;
7920 }
7921 }
7922
7923 if (!Okay) {
7924 SourceRange Range(TemplateNameLoc, RAngleLoc);
7925 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7926 << Context.getTypeDeclType(Specialization) << Range;
7927
7928 Diag(PrevDecl->getPointOfInstantiation(),
7929 diag::note_instantiation_required_here)
7930 << (PrevDecl->getTemplateSpecializationKind()
7931 != TSK_ImplicitInstantiation);
7932 return true;
7933 }
7934 }
7935
7936 // If this is not a friend, note that this is an explicit specialization.
7937 if (TUK != TUK_Friend)
7938 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
7939
7940 // Check that this isn't a redefinition of this specialization.
7941 if (TUK == TUK_Definition) {
7942 RecordDecl *Def = Specialization->getDefinition();
7943 NamedDecl *Hidden = nullptr;
7944 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7945 SkipBody->ShouldSkip = true;
7946 SkipBody->Previous = Def;
7947 makeMergedDefinitionVisible(Hidden);
7948 } else if (Def) {
7949 SourceRange Range(TemplateNameLoc, RAngleLoc);
7950 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
7951 Diag(Def->getLocation(), diag::note_previous_definition);
7952 Specialization->setInvalidDecl();
7953 return true;
7954 }
7955 }
7956
7957 ProcessDeclAttributeList(S, Specialization, Attr);
7958
7959 // Add alignment attributes if necessary; these attributes are checked when
7960 // the ASTContext lays out the structure.
7961 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
7962 AddAlignmentAttributesForRecord(Specialization);
7963 AddMsStructLayoutForRecord(Specialization);
7964 }
7965
7966 if (ModulePrivateLoc.isValid())
7967 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7968 << (isPartialSpecialization? 1 : 0)
7969 << FixItHint::CreateRemoval(ModulePrivateLoc);
7970
7971 // Build the fully-sugared type for this class template
7972 // specialization as the user wrote in the specialization
7973 // itself. This means that we'll pretty-print the type retrieved
7974 // from the specialization's declaration the way that the user
7975 // actually wrote the specialization, rather than formatting the
7976 // name based on the "canonical" representation used to store the
7977 // template arguments in the specialization.
7978 TypeSourceInfo *WrittenTy
7979 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7980 TemplateArgs, CanonType);
7981 if (TUK != TUK_Friend) {
7982 Specialization->setTypeAsWritten(WrittenTy);
7983 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
7984 }
7985
7986 // C++ [temp.expl.spec]p9:
7987 // A template explicit specialization is in the scope of the
7988 // namespace in which the template was defined.
7989 //
7990 // We actually implement this paragraph where we set the semantic
7991 // context (in the creation of the ClassTemplateSpecializationDecl),
7992 // but we also maintain the lexical context where the actual
7993 // definition occurs.
7994 Specialization->setLexicalDeclContext(CurContext);
7995
7996 // We may be starting the definition of this specialization.
7997 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
7998 Specialization->startDefinition();
7999
8000 if (TUK == TUK_Friend) {
8001 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
8002 TemplateNameLoc,
8003 WrittenTy,
8004 /*FIXME:*/KWLoc);
8005 Friend->setAccess(AS_public);
8006 CurContext->addDecl(Friend);
8007 } else {
8008 // Add the specialization into its lexical context, so that it can
8009 // be seen when iterating through the list of declarations in that
8010 // context. However, specializations are not found by name lookup.
8011 CurContext->addDecl(Specialization);
8012 }
8013
8014 if (SkipBody && SkipBody->ShouldSkip)
8015 return SkipBody->Previous;
8016
8017 return Specialization;
8018}
8019
8020Decl *Sema::ActOnTemplateDeclarator(Scope *S,
8021 MultiTemplateParamsArg TemplateParameterLists,
8022 Declarator &D) {
8023 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8024 ActOnDocumentableDecl(NewDecl);
8025 return NewDecl;
8026}
8027
8028Decl *Sema::ActOnConceptDefinition(Scope *S,
8029 MultiTemplateParamsArg TemplateParameterLists,
8030 IdentifierInfo *Name, SourceLocation NameLoc,
8031 Expr *ConstraintExpr) {
8032 DeclContext *DC = CurContext;
8033
8034 if (!DC->getRedeclContext()->isFileContext()) {
8035 Diag(NameLoc,
8036 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8037 return nullptr;
8038 }
8039
8040 if (TemplateParameterLists.size() > 1) {
8041 Diag(NameLoc, diag::err_concept_extra_headers);
8042 return nullptr;
8043 }
8044
8045 if (TemplateParameterLists.front()->size() == 0) {
8046 Diag(NameLoc, diag::err_concept_no_parameters);
8047 return nullptr;
8048 }
8049
8050 ConceptDecl *NewDecl = ConceptDecl::Create(Context, DC, NameLoc, Name,
8051 TemplateParameterLists.front(),
8052 ConstraintExpr);
8053
8054 if (!ConstraintExpr->isTypeDependent() &&
8055 ConstraintExpr->getType() != Context.BoolTy) {
8056 // C++2a [temp.constr.atomic]p3:
8057 // E shall be a constant expression of type bool.
8058 // TODO: Do this check for individual atomic constraints
8059 // and not the constraint expression. Probably should do it in
8060 // ParseConstraintExpression.
8061 Diag(ConstraintExpr->getSourceRange().getBegin(),
8062 diag::err_concept_initialized_with_non_bool_type)
8063 << ConstraintExpr->getType();
8064 NewDecl->setInvalidDecl();
8065 }
8066
8067 if (NewDecl->getAssociatedConstraints()) {
8068 // C++2a [temp.concept]p4:
8069 // A concept shall not have associated constraints.
8070 // TODO: Make a test once we have actual associated constraints.
8071 Diag(NameLoc, diag::err_concept_no_associated_constraints);
8072 NewDecl->setInvalidDecl();
8073 }
8074
8075 // Check for conflicting previous declaration.
8076 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
8077 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8078 ForVisibleRedeclaration);
8079 LookupName(Previous, S);
8080
8081 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
8082 /*AllowInlineNamespace*/false);
8083 if (!Previous.empty()) {
8084 auto *Old = Previous.getRepresentativeDecl();
8085 Diag(NameLoc, isa<ConceptDecl>(Old) ? diag::err_redefinition :
8086 diag::err_redefinition_different_kind) << NewDecl->getDeclName();
8087 Diag(Old->getLocation(), diag::note_previous_definition);
8088 }
8089
8090 ActOnDocumentableDecl(NewDecl);
8091 PushOnScopeChains(NewDecl, S);
8092 return NewDecl;
8093}
8094
8095/// \brief Strips various properties off an implicit instantiation
8096/// that has just been explicitly specialized.
8097static void StripImplicitInstantiation(NamedDecl *D) {
8098 D->dropAttr<DLLImportAttr>();
8099 D->dropAttr<DLLExportAttr>();
8100
8101 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8102 FD->setInlineSpecified(false);
8103}
8104
8105/// Compute the diagnostic location for an explicit instantiation
8106// declaration or definition.
8107static SourceLocation DiagLocForExplicitInstantiation(
8108 NamedDecl* D, SourceLocation PointOfInstantiation) {
8109 // Explicit instantiations following a specialization have no effect and
8110 // hence no PointOfInstantiation. In that case, walk decl backwards
8111 // until a valid name loc is found.
8112 SourceLocation PrevDiagLoc = PointOfInstantiation;
8113 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8114 Prev = Prev->getPreviousDecl()) {
8115 PrevDiagLoc = Prev->getLocation();
8116 }
8117 assert(PrevDiagLoc.isValid() &&((PrevDiagLoc.isValid() && "Explicit instantiation without point of instantiation?"
) ? static_cast<void> (0) : __assert_fail ("PrevDiagLoc.isValid() && \"Explicit instantiation without point of instantiation?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8118, __PRETTY_FUNCTION__))
8118 "Explicit instantiation without point of instantiation?")((PrevDiagLoc.isValid() && "Explicit instantiation without point of instantiation?"
) ? static_cast<void> (0) : __assert_fail ("PrevDiagLoc.isValid() && \"Explicit instantiation without point of instantiation?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8118, __PRETTY_FUNCTION__))
;
8119 return PrevDiagLoc;
8120}
8121
8122/// Diagnose cases where we have an explicit template specialization
8123/// before/after an explicit template instantiation, producing diagnostics
8124/// for those cases where they are required and determining whether the
8125/// new specialization/instantiation will have any effect.
8126///
8127/// \param NewLoc the location of the new explicit specialization or
8128/// instantiation.
8129///
8130/// \param NewTSK the kind of the new explicit specialization or instantiation.
8131///
8132/// \param PrevDecl the previous declaration of the entity.
8133///
8134/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
8135///
8136/// \param PrevPointOfInstantiation if valid, indicates where the previus
8137/// declaration was instantiated (either implicitly or explicitly).
8138///
8139/// \param HasNoEffect will be set to true to indicate that the new
8140/// specialization or instantiation has no effect and should be ignored.
8141///
8142/// \returns true if there was an error that should prevent the introduction of
8143/// the new declaration into the AST, false otherwise.
8144bool
8145Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
8146 TemplateSpecializationKind NewTSK,
8147 NamedDecl *PrevDecl,
8148 TemplateSpecializationKind PrevTSK,
8149 SourceLocation PrevPointOfInstantiation,
8150 bool &HasNoEffect) {
8151 HasNoEffect = false;
8152
8153 switch (NewTSK) {
8154 case TSK_Undeclared:
8155 case TSK_ImplicitInstantiation:
8156 assert((((PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation
) && "previous declaration must be implicit!") ? static_cast
<void> (0) : __assert_fail ("(PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && \"previous declaration must be implicit!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8158, __PRETTY_FUNCTION__))
8157 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&(((PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation
) && "previous declaration must be implicit!") ? static_cast
<void> (0) : __assert_fail ("(PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && \"previous declaration must be implicit!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8158, __PRETTY_FUNCTION__))
8158 "previous declaration must be implicit!")(((PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation
) && "previous declaration must be implicit!") ? static_cast
<void> (0) : __assert_fail ("(PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && \"previous declaration must be implicit!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8158, __PRETTY_FUNCTION__))
;
8159 return false;
8160
8161 case TSK_ExplicitSpecialization:
8162 switch (PrevTSK) {
8163 case TSK_Undeclared:
8164 case TSK_ExplicitSpecialization:
8165 // Okay, we're just specializing something that is either already
8166 // explicitly specialized or has merely been mentioned without any
8167 // instantiation.
8168 return false;
8169
8170 case TSK_ImplicitInstantiation:
8171 if (PrevPointOfInstantiation.isInvalid()) {
8172 // The declaration itself has not actually been instantiated, so it is
8173 // still okay to specialize it.
8174 StripImplicitInstantiation(PrevDecl);
8175 return false;
8176 }
8177 // Fall through
8178 LLVM_FALLTHROUGH[[gnu::fallthrough]];
8179
8180 case TSK_ExplicitInstantiationDeclaration:
8181 case TSK_ExplicitInstantiationDefinition:
8182 assert((PrevTSK == TSK_ImplicitInstantiation ||(((PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation
.isValid()) && "Explicit instantiation without point of instantiation?"
) ? static_cast<void> (0) : __assert_fail ("(PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && \"Explicit instantiation without point of instantiation?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8184, __PRETTY_FUNCTION__))
8183 PrevPointOfInstantiation.isValid()) &&(((PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation
.isValid()) && "Explicit instantiation without point of instantiation?"
) ? static_cast<void> (0) : __assert_fail ("(PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && \"Explicit instantiation without point of instantiation?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8184, __PRETTY_FUNCTION__))
8184 "Explicit instantiation without point of instantiation?")(((PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation
.isValid()) && "Explicit instantiation without point of instantiation?"
) ? static_cast<void> (0) : __assert_fail ("(PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && \"Explicit instantiation without point of instantiation?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8184, __PRETTY_FUNCTION__))
;
8185
8186 // C++ [temp.expl.spec]p6:
8187 // If a template, a member template or the member of a class template
8188 // is explicitly specialized then that specialization shall be declared
8189 // before the first use of that specialization that would cause an
8190 // implicit instantiation to take place, in every translation unit in
8191 // which such a use occurs; no diagnostic is required.
8192 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8193 // Is there any previous explicit specialization declaration?
8194 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
8195 return false;
8196 }
8197
8198 Diag(NewLoc, diag::err_specialization_after_instantiation)
8199 << PrevDecl;
8200 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
8201 << (PrevTSK != TSK_ImplicitInstantiation);
8202
8203 return true;
8204 }
8205 llvm_unreachable("The switch over PrevTSK must be exhaustive.")::llvm::llvm_unreachable_internal("The switch over PrevTSK must be exhaustive."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8205)
;
8206
8207 case TSK_ExplicitInstantiationDeclaration:
8208 switch (PrevTSK) {
8209 case TSK_ExplicitInstantiationDeclaration:
8210 // This explicit instantiation declaration is redundant (that's okay).
8211 HasNoEffect = true;
8212 return false;
8213
8214 case TSK_Undeclared:
8215 case TSK_ImplicitInstantiation:
8216 // We're explicitly instantiating something that may have already been
8217 // implicitly instantiated; that's fine.
8218 return false;
8219
8220 case TSK_ExplicitSpecialization:
8221 // C++0x [temp.explicit]p4:
8222 // For a given set of template parameters, if an explicit instantiation
8223 // of a template appears after a declaration of an explicit
8224 // specialization for that template, the explicit instantiation has no
8225 // effect.
8226 HasNoEffect = true;
8227 return false;
8228
8229 case TSK_ExplicitInstantiationDefinition:
8230 // C++0x [temp.explicit]p10:
8231 // If an entity is the subject of both an explicit instantiation
8232 // declaration and an explicit instantiation definition in the same
8233 // translation unit, the definition shall follow the declaration.
8234 Diag(NewLoc,
8235 diag::err_explicit_instantiation_declaration_after_definition);
8236
8237 // Explicit instantiations following a specialization have no effect and
8238 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8239 // until a valid name loc is found.
8240 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8241 diag::note_explicit_instantiation_definition_here);
8242 HasNoEffect = true;
8243 return false;
8244 }
8245 llvm_unreachable("Unexpected TemplateSpecializationKind!")::llvm::llvm_unreachable_internal("Unexpected TemplateSpecializationKind!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8245)
;
8246
8247 case TSK_ExplicitInstantiationDefinition:
8248 switch (PrevTSK) {
8249 case TSK_Undeclared:
8250 case TSK_ImplicitInstantiation:
8251 // We're explicitly instantiating something that may have already been
8252 // implicitly instantiated; that's fine.
8253 return false;
8254
8255 case TSK_ExplicitSpecialization:
8256 // C++ DR 259, C++0x [temp.explicit]p4:
8257 // For a given set of template parameters, if an explicit
8258 // instantiation of a template appears after a declaration of
8259 // an explicit specialization for that template, the explicit
8260 // instantiation has no effect.
8261 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
8262 << PrevDecl;
8263 Diag(PrevDecl->getLocation(),
8264 diag::note_previous_template_specialization);
8265 HasNoEffect = true;
8266 return false;
8267
8268 case TSK_ExplicitInstantiationDeclaration:
8269 // We're explicitly instantiating a definition for something for which we
8270 // were previously asked to suppress instantiations. That's fine.
8271
8272 // C++0x [temp.explicit]p4:
8273 // For a given set of template parameters, if an explicit instantiation
8274 // of a template appears after a declaration of an explicit
8275 // specialization for that template, the explicit instantiation has no
8276 // effect.
8277 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8278 // Is there any previous explicit specialization declaration?
8279 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8280 HasNoEffect = true;
8281 break;
8282 }
8283 }
8284
8285 return false;
8286
8287 case TSK_ExplicitInstantiationDefinition:
8288 // C++0x [temp.spec]p5:
8289 // For a given template and a given set of template-arguments,
8290 // - an explicit instantiation definition shall appear at most once
8291 // in a program,
8292
8293 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8294 Diag(NewLoc, (getLangOpts().MSVCCompat)
8295 ? diag::ext_explicit_instantiation_duplicate
8296 : diag::err_explicit_instantiation_duplicate)
8297 << PrevDecl;
8298 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8299 diag::note_previous_explicit_instantiation);
8300 HasNoEffect = true;
8301 return false;
8302 }
8303 }
8304
8305 llvm_unreachable("Missing specialization/instantiation case?")::llvm::llvm_unreachable_internal("Missing specialization/instantiation case?"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8305)
;
8306}
8307
8308/// Perform semantic analysis for the given dependent function
8309/// template specialization.
8310///
8311/// The only possible way to get a dependent function template specialization
8312/// is with a friend declaration, like so:
8313///
8314/// \code
8315/// template \<class T> void foo(T);
8316/// template \<class T> class A {
8317/// friend void foo<>(T);
8318/// };
8319/// \endcode
8320///
8321/// There really isn't any useful analysis we can do here, so we
8322/// just store the information.
8323bool
8324Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8325 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8326 LookupResult &Previous) {
8327 // Remove anything from Previous that isn't a function template in
8328 // the correct context.
8329 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8330 LookupResult::Filter F = Previous.makeFilter();
8331 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8332 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
8333 while (F.hasNext()) {
8334 NamedDecl *D = F.next()->getUnderlyingDecl();
8335 if (!isa<FunctionTemplateDecl>(D)) {
8336 F.erase();
8337 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8338 continue;
8339 }
8340
8341 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8342 D->getDeclContext()->getRedeclContext())) {
8343 F.erase();
8344 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8345 continue;
8346 }
8347 }
8348 F.done();
8349
8350 if (Previous.empty()) {
8351 Diag(FD->getLocation(),
8352 diag::err_dependent_function_template_spec_no_match);
8353 for (auto &P : DiscardedCandidates)
8354 Diag(P.second->getLocation(),
8355 diag::note_dependent_function_template_spec_discard_reason)
8356 << P.first;
8357 return true;
8358 }
8359
8360 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8361 ExplicitTemplateArgs);
8362 return false;
8363}
8364
8365/// Perform semantic analysis for the given function template
8366/// specialization.
8367///
8368/// This routine performs all of the semantic analysis required for an
8369/// explicit function template specialization. On successful completion,
8370/// the function declaration \p FD will become a function template
8371/// specialization.
8372///
8373/// \param FD the function declaration, which will be updated to become a
8374/// function template specialization.
8375///
8376/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8377/// if any. Note that this may be valid info even when 0 arguments are
8378/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8379/// as it anyway contains info on the angle brackets locations.
8380///
8381/// \param Previous the set of declarations that may be specialized by
8382/// this function specialization.
8383///
8384/// \param QualifiedFriend whether this is a lookup for a qualified friend
8385/// declaration with no explicit template argument list that might be
8386/// befriending a function template specialization.
8387bool Sema::CheckFunctionTemplateSpecialization(
8388 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8389 LookupResult &Previous, bool QualifiedFriend) {
8390 // The set of function template specializations that could match this
8391 // explicit function template specialization.
8392 UnresolvedSet<8> Candidates;
8393 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8394 /*ForTakingAddress=*/false);
8395
8396 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8397 ConvertedTemplateArgs;
8398
8399 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8400 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8401 I != E; ++I) {
8402 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8403 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
8404 // Only consider templates found within the same semantic lookup scope as
8405 // FD.
8406 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8407 Ovl->getDeclContext()->getRedeclContext()))
8408 continue;
8409
8410 // When matching a constexpr member function template specialization
8411 // against the primary template, we don't yet know whether the
8412 // specialization has an implicit 'const' (because we don't know whether
8413 // it will be a static member function until we know which template it
8414 // specializes), so adjust it now assuming it specializes this template.
8415 QualType FT = FD->getType();
8416 if (FD->isConstexpr()) {
8417 CXXMethodDecl *OldMD =
8418 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
8419 if (OldMD && OldMD->isConst()) {
8420 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
8421 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8422 EPI.TypeQuals.addConst();
8423 FT = Context.getFunctionType(FPT->getReturnType(),
8424 FPT->getParamTypes(), EPI);
8425 }
8426 }
8427
8428 TemplateArgumentListInfo Args;
8429 if (ExplicitTemplateArgs)
8430 Args = *ExplicitTemplateArgs;
8431
8432 // C++ [temp.expl.spec]p11:
8433 // A trailing template-argument can be left unspecified in the
8434 // template-id naming an explicit function template specialization
8435 // provided it can be deduced from the function argument type.
8436 // Perform template argument deduction to determine whether we may be
8437 // specializing this template.
8438 // FIXME: It is somewhat wasteful to build
8439 TemplateDeductionInfo Info(FailedCandidates.getLocation());
8440 FunctionDecl *Specialization = nullptr;
8441 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8442 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
8443 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8444 Info)) {
8445 // Template argument deduction failed; record why it failed, so
8446 // that we can provide nifty diagnostics.
8447 FailedCandidates.addCandidate().set(
8448 I.getPair(), FunTmpl->getTemplatedDecl(),
8449 MakeDeductionFailureInfo(Context, TDK, Info));
8450 (void)TDK;
8451 continue;
8452 }
8453
8454 // Target attributes are part of the cuda function signature, so
8455 // the deduced template's cuda target must match that of the
8456 // specialization. Given that C++ template deduction does not
8457 // take target attributes into account, we reject candidates
8458 // here that have a different target.
8459 if (LangOpts.CUDA &&
8460 IdentifyCUDATarget(Specialization,
8461 /* IgnoreImplicitHDAttr = */ true) !=
8462 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
8463 FailedCandidates.addCandidate().set(
8464 I.getPair(), FunTmpl->getTemplatedDecl(),
8465 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8466 continue;
8467 }
8468
8469 // Record this candidate.
8470 if (ExplicitTemplateArgs)
8471 ConvertedTemplateArgs[Specialization] = std::move(Args);
8472 Candidates.addDecl(Specialization, I.getAccess());
8473 }
8474 }
8475
8476 // For a qualified friend declaration (with no explicit marker to indicate
8477 // that a template specialization was intended), note all (template and
8478 // non-template) candidates.
8479 if (QualifiedFriend && Candidates.empty()) {
8480 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
8481 << FD->getDeclName() << FDLookupContext;
8482 // FIXME: We should form a single candidate list and diagnose all
8483 // candidates at once, to get proper sorting and limiting.
8484 for (auto *OldND : Previous) {
8485 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
8486 NoteOverloadCandidate(OldND, OldFD, FD->getType(), false);
8487 }
8488 FailedCandidates.NoteCandidates(*this, FD->getLocation());
8489 return true;
8490 }
8491
8492 // Find the most specialized function template.
8493 UnresolvedSetIterator Result = getMostSpecialized(
8494 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
8495 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8496 PDiag(diag::err_function_template_spec_ambiguous)
8497 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
8498 PDiag(diag::note_function_template_spec_matched));
8499
8500 if (Result == Candidates.end())
8501 return true;
8502
8503 // Ignore access information; it doesn't figure into redeclaration checking.
8504 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8505
8506 FunctionTemplateSpecializationInfo *SpecInfo
8507 = Specialization->getTemplateSpecializationInfo();
8508 assert(SpecInfo && "Function template specialization info missing?")((SpecInfo && "Function template specialization info missing?"
) ? static_cast<void> (0) : __assert_fail ("SpecInfo && \"Function template specialization info missing?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8508, __PRETTY_FUNCTION__))
;
8509
8510 // Note: do not overwrite location info if previous template
8511 // specialization kind was explicit.
8512 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
8513 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
8514 Specialization->setLocation(FD->getLocation());
8515 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
8516 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8517 // function can differ from the template declaration with respect to
8518 // the constexpr specifier.
8519 // FIXME: We need an update record for this AST mutation.
8520 // FIXME: What if there are multiple such prior declarations (for instance,
8521 // from different modules)?
8522 Specialization->setConstexprKind(FD->getConstexprKind());
8523 }
8524
8525 // FIXME: Check if the prior specialization has a point of instantiation.
8526 // If so, we have run afoul of .
8527
8528 // If this is a friend declaration, then we're not really declaring
8529 // an explicit specialization.
8530 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
8531
8532 // Check the scope of this explicit specialization.
8533 if (!isFriend &&
8534 CheckTemplateSpecializationScope(*this,
8535 Specialization->getPrimaryTemplate(),
8536 Specialization, FD->getLocation(),
8537 false))
8538 return true;
8539
8540 // C++ [temp.expl.spec]p6:
8541 // If a template, a member template or the member of a class template is
8542 // explicitly specialized then that specialization shall be declared
8543 // before the first use of that specialization that would cause an implicit
8544 // instantiation to take place, in every translation unit in which such a
8545 // use occurs; no diagnostic is required.
8546 bool HasNoEffect = false;
8547 if (!isFriend &&
8548 CheckSpecializationInstantiationRedecl(FD->getLocation(),
8549 TSK_ExplicitSpecialization,
8550 Specialization,
8551 SpecInfo->getTemplateSpecializationKind(),
8552 SpecInfo->getPointOfInstantiation(),
8553 HasNoEffect))
8554 return true;
8555
8556 // Mark the prior declaration as an explicit specialization, so that later
8557 // clients know that this is an explicit specialization.
8558 if (!isFriend) {
8559 // Since explicit specializations do not inherit '=delete' from their
8560 // primary function template - check if the 'specialization' that was
8561 // implicitly generated (during template argument deduction for partial
8562 // ordering) from the most specialized of all the function templates that
8563 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8564 // first check that it was implicitly generated during template argument
8565 // deduction by making sure it wasn't referenced, and then reset the deleted
8566 // flag to not-deleted, so that we can inherit that information from 'FD'.
8567 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8568 !Specialization->getCanonicalDecl()->isReferenced()) {
8569 // FIXME: This assert will not hold in the presence of modules.
8570 assert(((Specialization->getCanonicalDecl() == Specialization &&
"This must be the only existing declaration of this specialization"
) ? static_cast<void> (0) : __assert_fail ("Specialization->getCanonicalDecl() == Specialization && \"This must be the only existing declaration of this specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8572, __PRETTY_FUNCTION__))
8571 Specialization->getCanonicalDecl() == Specialization &&((Specialization->getCanonicalDecl() == Specialization &&
"This must be the only existing declaration of this specialization"
) ? static_cast<void> (0) : __assert_fail ("Specialization->getCanonicalDecl() == Specialization && \"This must be the only existing declaration of this specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8572, __PRETTY_FUNCTION__))
8572 "This must be the only existing declaration of this specialization")((Specialization->getCanonicalDecl() == Specialization &&
"This must be the only existing declaration of this specialization"
) ? static_cast<void> (0) : __assert_fail ("Specialization->getCanonicalDecl() == Specialization && \"This must be the only existing declaration of this specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8572, __PRETTY_FUNCTION__))
;
8573 // FIXME: We need an update record for this AST mutation.
8574 Specialization->setDeletedAsWritten(false);
8575 }
8576 // FIXME: We need an update record for this AST mutation.
8577 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8578 MarkUnusedFileScopedDecl(Specialization);
8579 }
8580
8581 // Turn the given function declaration into a function template
8582 // specialization, with the template arguments from the previous
8583 // specialization.
8584 // Take copies of (semantic and syntactic) template argument lists.
8585 const TemplateArgumentList* TemplArgs = new (Context)
8586 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
8587 FD->setFunctionTemplateSpecialization(
8588 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8589 SpecInfo->getTemplateSpecializationKind(),
8590 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
8591
8592 // A function template specialization inherits the target attributes
8593 // of its template. (We require the attributes explicitly in the
8594 // code to match, but a template may have implicit attributes by
8595 // virtue e.g. of being constexpr, and it passes these implicit
8596 // attributes on to its specializations.)
8597 if (LangOpts.CUDA)
8598 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8599
8600 // The "previous declaration" for this function template specialization is
8601 // the prior function template specialization.
8602 Previous.clear();
8603 Previous.addDecl(Specialization);
8604 return false;
8605}
8606
8607/// Perform semantic analysis for the given non-template member
8608/// specialization.
8609///
8610/// This routine performs all of the semantic analysis required for an
8611/// explicit member function specialization. On successful completion,
8612/// the function declaration \p FD will become a member function
8613/// specialization.
8614///
8615/// \param Member the member declaration, which will be updated to become a
8616/// specialization.
8617///
8618/// \param Previous the set of declarations, one of which may be specialized
8619/// by this function specialization; the set will be modified to contain the
8620/// redeclared member.
8621bool
8622Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
8623 assert(!isa<TemplateDecl>(Member) && "Only for non-template members")((!isa<TemplateDecl>(Member) && "Only for non-template members"
) ? static_cast<void> (0) : __assert_fail ("!isa<TemplateDecl>(Member) && \"Only for non-template members\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8623, __PRETTY_FUNCTION__))
;
8624
8625 // Try to find the member we are instantiating.
8626 NamedDecl *FoundInstantiation = nullptr;
8627 NamedDecl *Instantiation = nullptr;
8628 NamedDecl *InstantiatedFrom = nullptr;
8629 MemberSpecializationInfo *MSInfo = nullptr;
8630
8631 if (Previous.empty()) {
8632 // Nowhere to look anyway.
8633 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
8634 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8635 I != E; ++I) {
8636 NamedDecl *D = (*I)->getUnderlyingDecl();
8637 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
8638 QualType Adjusted = Function->getType();
8639 if (!hasExplicitCallingConv(Adjusted))
8640 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8641 // This doesn't handle deduced return types, but both function
8642 // declarations should be undeduced at this point.
8643 if (Context.hasSameType(Adjusted, Method->getType())) {
8644 FoundInstantiation = *I;
8645 Instantiation = Method;
8646 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
8647 MSInfo = Method->getMemberSpecializationInfo();
8648 break;
8649 }
8650 }
8651 }
8652 } else if (isa<VarDecl>(Member)) {
8653 VarDecl *PrevVar;
8654 if (Previous.isSingleResult() &&
8655 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
8656 if (PrevVar->isStaticDataMember()) {
8657 FoundInstantiation = Previous.getRepresentativeDecl();
8658 Instantiation = PrevVar;
8659 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
8660 MSInfo = PrevVar->getMemberSpecializationInfo();
8661 }
8662 } else if (isa<RecordDecl>(Member)) {
8663 CXXRecordDecl *PrevRecord;
8664 if (Previous.isSingleResult() &&
8665 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
8666 FoundInstantiation = Previous.getRepresentativeDecl();
8667 Instantiation = PrevRecord;
8668 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
8669 MSInfo = PrevRecord->getMemberSpecializationInfo();
8670 }
8671 } else if (isa<EnumDecl>(Member)) {
8672 EnumDecl *PrevEnum;
8673 if (Previous.isSingleResult() &&
8674 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
8675 FoundInstantiation = Previous.getRepresentativeDecl();
8676 Instantiation = PrevEnum;
8677 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8678 MSInfo = PrevEnum->getMemberSpecializationInfo();
8679 }
8680 }
8681
8682 if (!Instantiation) {
8683 // There is no previous declaration that matches. Since member
8684 // specializations are always out-of-line, the caller will complain about
8685 // this mismatch later.
8686 return false;
8687 }
8688
8689 // A member specialization in a friend declaration isn't really declaring
8690 // an explicit specialization, just identifying a specific (possibly implicit)
8691 // specialization. Don't change the template specialization kind.
8692 //
8693 // FIXME: Is this really valid? Other compilers reject.
8694 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8695 // Preserve instantiation information.
8696 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8697 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8698 cast<CXXMethodDecl>(InstantiatedFrom),
8699 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8700 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8701 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8702 cast<CXXRecordDecl>(InstantiatedFrom),
8703 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8704 }
8705
8706 Previous.clear();
8707 Previous.addDecl(FoundInstantiation);
8708 return false;
8709 }
8710
8711 // Make sure that this is a specialization of a member.
8712 if (!InstantiatedFrom) {
8713 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8714 << Member;
8715 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8716 return true;
8717 }
8718
8719 // C++ [temp.expl.spec]p6:
8720 // If a template, a member template or the member of a class template is
8721 // explicitly specialized then that specialization shall be declared
8722 // before the first use of that specialization that would cause an implicit
8723 // instantiation to take place, in every translation unit in which such a
8724 // use occurs; no diagnostic is required.
8725 assert(MSInfo && "Member specialization info missing?")((MSInfo && "Member specialization info missing?") ? static_cast
<void> (0) : __assert_fail ("MSInfo && \"Member specialization info missing?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8725, __PRETTY_FUNCTION__))
;
8726
8727 bool HasNoEffect = false;
8728 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8729 TSK_ExplicitSpecialization,
8730 Instantiation,
8731 MSInfo->getTemplateSpecializationKind(),
8732 MSInfo->getPointOfInstantiation(),
8733 HasNoEffect))
8734 return true;
8735
8736 // Check the scope of this explicit specialization.
8737 if (CheckTemplateSpecializationScope(*this,
8738 InstantiatedFrom,
8739 Instantiation, Member->getLocation(),
8740 false))
8741 return true;
8742
8743 // Note that this member specialization is an "instantiation of" the
8744 // corresponding member of the original template.
8745 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
8746 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8747 if (InstantiationFunction->getTemplateSpecializationKind() ==
8748 TSK_ImplicitInstantiation) {
8749 // Explicit specializations of member functions of class templates do not
8750 // inherit '=delete' from the member function they are specializing.
8751 if (InstantiationFunction->isDeleted()) {
8752 // FIXME: This assert will not hold in the presence of modules.
8753 assert(InstantiationFunction->getCanonicalDecl() ==((InstantiationFunction->getCanonicalDecl() == InstantiationFunction
) ? static_cast<void> (0) : __assert_fail ("InstantiationFunction->getCanonicalDecl() == InstantiationFunction"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8754, __PRETTY_FUNCTION__))
8754 InstantiationFunction)((InstantiationFunction->getCanonicalDecl() == InstantiationFunction
) ? static_cast<void> (0) : __assert_fail ("InstantiationFunction->getCanonicalDecl() == InstantiationFunction"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8754, __PRETTY_FUNCTION__))
;
8755 // FIXME: We need an update record for this AST mutation.
8756 InstantiationFunction->setDeletedAsWritten(false);
8757 }
8758 }
8759
8760 MemberFunction->setInstantiationOfMemberFunction(
8761 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8762 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8763 MemberVar->setInstantiationOfStaticDataMember(
8764 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8765 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8766 MemberClass->setInstantiationOfMemberClass(
8767 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8768 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8769 MemberEnum->setInstantiationOfMemberEnum(
8770 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8771 } else {
8772 llvm_unreachable("unknown member specialization kind")::llvm::llvm_unreachable_internal("unknown member specialization kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8772)
;
8773 }
8774
8775 // Save the caller the trouble of having to figure out which declaration
8776 // this specialization matches.
8777 Previous.clear();
8778 Previous.addDecl(FoundInstantiation);
8779 return false;
8780}
8781
8782/// Complete the explicit specialization of a member of a class template by
8783/// updating the instantiated member to be marked as an explicit specialization.
8784///
8785/// \param OrigD The member declaration instantiated from the template.
8786/// \param Loc The location of the explicit specialization of the member.
8787template<typename DeclT>
8788static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8789 SourceLocation Loc) {
8790 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8791 return;
8792
8793 // FIXME: Inform AST mutation listeners of this AST mutation.
8794 // FIXME: If there are multiple in-class declarations of the member (from
8795 // multiple modules, or a declaration and later definition of a member type),
8796 // should we update all of them?
8797 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8798 OrigD->setLocation(Loc);
8799}
8800
8801void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8802 LookupResult &Previous) {
8803 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8804 if (Instantiation == Member)
8805 return;
8806
8807 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8808 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8809 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8810 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8811 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8812 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8813 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8814 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8815 else
8816 llvm_unreachable("unknown member specialization kind")::llvm::llvm_unreachable_internal("unknown member specialization kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8816)
;
8817}
8818
8819/// Check the scope of an explicit instantiation.
8820///
8821/// \returns true if a serious error occurs, false otherwise.
8822static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
8823 SourceLocation InstLoc,
8824 bool WasQualifiedName) {
8825 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8826 DeclContext *CurContext = S.CurContext->getRedeclContext();
8827
8828 if (CurContext->isRecord()) {
8829 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8830 << D;
8831 return true;
8832 }
8833
8834 // C++11 [temp.explicit]p3:
8835 // An explicit instantiation shall appear in an enclosing namespace of its
8836 // template. If the name declared in the explicit instantiation is an
8837 // unqualified name, the explicit instantiation shall appear in the
8838 // namespace where its template is declared or, if that namespace is inline
8839 // (7.3.1), any namespace from its enclosing namespace set.
8840 //
8841 // This is DR275, which we do not retroactively apply to C++98/03.
8842 if (WasQualifiedName) {
8843 if (CurContext->Encloses(OrigContext))
8844 return false;
8845 } else {
8846 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8847 return false;
8848 }
8849
8850 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8851 if (WasQualifiedName)
8852 S.Diag(InstLoc,
8853 S.getLangOpts().CPlusPlus11?
8854 diag::err_explicit_instantiation_out_of_scope :
8855 diag::warn_explicit_instantiation_out_of_scope_0x)
8856 << D << NS;
8857 else
8858 S.Diag(InstLoc,
8859 S.getLangOpts().CPlusPlus11?
8860 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8861 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8862 << D << NS;
8863 } else
8864 S.Diag(InstLoc,
8865 S.getLangOpts().CPlusPlus11?
8866 diag::err_explicit_instantiation_must_be_global :
8867 diag::warn_explicit_instantiation_must_be_global_0x)
8868 << D;
8869 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
8870 return false;
8871}
8872
8873/// Common checks for whether an explicit instantiation of \p D is valid.
8874static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
8875 SourceLocation InstLoc,
8876 bool WasQualifiedName,
8877 TemplateSpecializationKind TSK) {
8878 // C++ [temp.explicit]p13:
8879 // An explicit instantiation declaration shall not name a specialization of
8880 // a template with internal linkage.
8881 if (TSK == TSK_ExplicitInstantiationDeclaration &&
8882 D->getFormalLinkage() == InternalLinkage) {
8883 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
8884 return true;
8885 }
8886
8887 // C++11 [temp.explicit]p3: [DR 275]
8888 // An explicit instantiation shall appear in an enclosing namespace of its
8889 // template.
8890 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
8891 return true;
8892
8893 return false;
8894}
8895
8896/// Determine whether the given scope specifier has a template-id in it.
8897static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8898 if (!SS.isSet())
8899 return false;
8900
8901 // C++11 [temp.explicit]p3:
8902 // If the explicit instantiation is for a member function, a member class
8903 // or a static data member of a class template specialization, the name of
8904 // the class template specialization in the qualified-id for the member
8905 // name shall be a simple-template-id.
8906 //
8907 // C++98 has the same restriction, just worded differently.
8908 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8909 NNS = NNS->getPrefix())
8910 if (const Type *T = NNS->getAsType())
8911 if (isa<TemplateSpecializationType>(T))
8912 return true;
8913
8914 return false;
8915}
8916
8917/// Make a dllexport or dllimport attr on a class template specialization take
8918/// effect.
8919static void dllExportImportClassTemplateSpecialization(
8920 Sema &S, ClassTemplateSpecializationDecl *Def) {
8921 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8922 assert(A && "dllExportImportClassTemplateSpecialization called "((A && "dllExportImportClassTemplateSpecialization called "
"on Def without dllexport or dllimport") ? static_cast<void
> (0) : __assert_fail ("A && \"dllExportImportClassTemplateSpecialization called \" \"on Def without dllexport or dllimport\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8923, __PRETTY_FUNCTION__))
8923 "on Def without dllexport or dllimport")((A && "dllExportImportClassTemplateSpecialization called "
"on Def without dllexport or dllimport") ? static_cast<void
> (0) : __assert_fail ("A && \"dllExportImportClassTemplateSpecialization called \" \"on Def without dllexport or dllimport\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8923, __PRETTY_FUNCTION__))
;
8924
8925 // We reject explicit instantiations in class scope, so there should
8926 // never be any delayed exported classes to worry about.
8927 assert(S.DelayedDllExportClasses.empty() &&((S.DelayedDllExportClasses.empty() && "delayed exports present at explicit instantiation"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"delayed exports present at explicit instantiation\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8928, __PRETTY_FUNCTION__))
8928 "delayed exports present at explicit instantiation")((S.DelayedDllExportClasses.empty() && "delayed exports present at explicit instantiation"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"delayed exports present at explicit instantiation\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8928, __PRETTY_FUNCTION__))
;
8929 S.checkClassLevelDLLAttribute(Def);
8930
8931 // Propagate attribute to base class templates.
8932 for (auto &B : Def->bases()) {
8933 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8934 B.getType()->getAsCXXRecordDecl()))
8935 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
8936 }
8937
8938 S.referenceDLLExportedClassMethods();
8939}
8940
8941// Explicit instantiation of a class template specialization
8942DeclResult Sema::ActOnExplicitInstantiation(
8943 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8944 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8945 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
8946 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
8947 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
8948 // Find the class template we're specializing
8949 TemplateName Name = TemplateD.get();
8950 TemplateDecl *TD = Name.getAsTemplateDecl();
8951 // Check that the specialization uses the same tag kind as the
8952 // original template.
8953 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8954 assert(Kind != TTK_Enum &&((Kind != TTK_Enum && "Invalid enum tag in class template explicit instantiation!"
) ? static_cast<void> (0) : __assert_fail ("Kind != TTK_Enum && \"Invalid enum tag in class template explicit instantiation!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8955, __PRETTY_FUNCTION__))
8955 "Invalid enum tag in class template explicit instantiation!")((Kind != TTK_Enum && "Invalid enum tag in class template explicit instantiation!"
) ? static_cast<void> (0) : __assert_fail ("Kind != TTK_Enum && \"Invalid enum tag in class template explicit instantiation!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8955, __PRETTY_FUNCTION__))
;
8956
8957 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8958
8959 if (!ClassTemplate) {
8960 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8961 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
8962 Diag(TD->getLocation(), diag::note_previous_use);
8963 return true;
8964 }
8965
8966 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8967 Kind, /*isDefinition*/false, KWLoc,
8968 ClassTemplate->getIdentifier())) {
8969 Diag(KWLoc, diag::err_use_with_wrong_tag)
8970 << ClassTemplate
8971 << FixItHint::CreateReplacement(KWLoc,
8972 ClassTemplate->getTemplatedDecl()->getKindName());
8973 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8974 diag::note_previous_use);
8975 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8976 }
8977
8978 // C++0x [temp.explicit]p2:
8979 // There are two forms of explicit instantiation: an explicit instantiation
8980 // definition and an explicit instantiation declaration. An explicit
8981 // instantiation declaration begins with the extern keyword. [...]
8982 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8983 ? TSK_ExplicitInstantiationDefinition
8984 : TSK_ExplicitInstantiationDeclaration;
8985
8986 if (TSK == TSK_ExplicitInstantiationDeclaration &&
8987 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
8988 // Check for dllexport class template instantiation declarations,
8989 // except for MinGW mode.
8990 for (const ParsedAttr &AL : Attr) {
8991 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
8992 Diag(ExternLoc,
8993 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8994 Diag(AL.getLoc(), diag::note_attribute);
8995 break;
8996 }
8997 }
8998
8999 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9000 Diag(ExternLoc,
9001 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9002 Diag(A->getLocation(), diag::note_attribute);
9003 }
9004 }
9005
9006 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9007 // instantiation declarations for most purposes.
9008 bool DLLImportExplicitInstantiationDef = false;
9009 if (TSK == TSK_ExplicitInstantiationDefinition &&
9010 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9011 // Check for dllimport class template instantiation definitions.
9012 bool DLLImport =
9013 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9014 for (const ParsedAttr &AL : Attr) {
9015 if (AL.getKind() == ParsedAttr::AT_DLLImport)
9016 DLLImport = true;
9017 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9018 // dllexport trumps dllimport here.
9019 DLLImport = false;
9020 break;
9021 }
9022 }
9023 if (DLLImport) {
9024 TSK = TSK_ExplicitInstantiationDeclaration;
9025 DLLImportExplicitInstantiationDef = true;
9026 }
9027 }
9028
9029 // Translate the parser's template argument list in our AST format.
9030 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9031 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9032
9033 // Check that the template argument list is well-formed for this
9034 // template.
9035 SmallVector<TemplateArgument, 4> Converted;
9036 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
9037 TemplateArgs, false, Converted))
9038 return true;
9039
9040 // Find the class template specialization declaration that
9041 // corresponds to these arguments.
9042 void *InsertPos = nullptr;
9043 ClassTemplateSpecializationDecl *PrevDecl
9044 = ClassTemplate->findSpecialization(Converted, InsertPos);
9045
9046 TemplateSpecializationKind PrevDecl_TSK
9047 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9048
9049 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9050 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9051 // Check for dllexport class template instantiation definitions in MinGW
9052 // mode, if a previous declaration of the instantiation was seen.
9053 for (const ParsedAttr &AL : Attr) {
9054 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9055 Diag(AL.getLoc(),
9056 diag::warn_attribute_dllexport_explicit_instantiation_def);
9057 break;
9058 }
9059 }
9060 }
9061
9062 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9063 SS.isSet(), TSK))
9064 return true;
9065
9066 ClassTemplateSpecializationDecl *Specialization = nullptr;
9067
9068 bool HasNoEffect = false;
9069 if (PrevDecl) {
9070 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
9071 PrevDecl, PrevDecl_TSK,
9072 PrevDecl->getPointOfInstantiation(),
9073 HasNoEffect))
9074 return PrevDecl;
9075
9076 // Even though HasNoEffect == true means that this explicit instantiation
9077 // has no effect on semantics, we go on to put its syntax in the AST.
9078
9079 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9080 PrevDecl_TSK == TSK_Undeclared) {
9081 // Since the only prior class template specialization with these
9082 // arguments was referenced but not declared, reuse that
9083 // declaration node as our own, updating the source location
9084 // for the template name to reflect our new declaration.
9085 // (Other source locations will be updated later.)
9086 Specialization = PrevDecl;
9087 Specialization->setLocation(TemplateNameLoc);
9088 PrevDecl = nullptr;
9089 }
9090
9091 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9092 DLLImportExplicitInstantiationDef) {
9093 // The new specialization might add a dllimport attribute.
9094 HasNoEffect = false;
9095 }
9096 }
9097
9098 if (!Specialization) {
9099 // Create a new class template specialization declaration node for
9100 // this explicit specialization.
9101 Specialization
9102 = ClassTemplateSpecializationDecl::Create(Context, Kind,
9103 ClassTemplate->getDeclContext(),
9104 KWLoc, TemplateNameLoc,
9105 ClassTemplate,
9106 Converted,
9107 PrevDecl);
9108 SetNestedNameSpecifier(*this, Specialization, SS);
9109
9110 if (!HasNoEffect && !PrevDecl) {
9111 // Insert the new specialization.
9112 ClassTemplate->AddSpecialization(Specialization, InsertPos);
9113 }
9114 }
9115
9116 // Build the fully-sugared type for this explicit instantiation as
9117 // the user wrote in the explicit instantiation itself. This means
9118 // that we'll pretty-print the type retrieved from the
9119 // specialization's declaration the way that the user actually wrote
9120 // the explicit instantiation, rather than formatting the name based
9121 // on the "canonical" representation used to store the template
9122 // arguments in the specialization.
9123 TypeSourceInfo *WrittenTy
9124 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
9125 TemplateArgs,
9126 Context.getTypeDeclType(Specialization));
9127 Specialization->setTypeAsWritten(WrittenTy);
9128
9129 // Set source locations for keywords.
9130 Specialization->setExternLoc(ExternLoc);
9131 Specialization->setTemplateKeywordLoc(TemplateLoc);
9132 Specialization->setBraceRange(SourceRange());
9133
9134 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
9135 ProcessDeclAttributeList(S, Specialization, Attr);
9136
9137 // Add the explicit instantiation into its lexical context. However,
9138 // since explicit instantiations are never found by name lookup, we
9139 // just put it into the declaration context directly.
9140 Specialization->setLexicalDeclContext(CurContext);
9141 CurContext->addDecl(Specialization);
9142
9143 // Syntax is now OK, so return if it has no other effect on semantics.
9144 if (HasNoEffect) {
9145 // Set the template specialization kind.
9146 Specialization->setTemplateSpecializationKind(TSK);
9147 return Specialization;
9148 }
9149
9150 // C++ [temp.explicit]p3:
9151 // A definition of a class template or class member template
9152 // shall be in scope at the point of the explicit instantiation of
9153 // the class template or class member template.
9154 //
9155 // This check comes when we actually try to perform the
9156 // instantiation.
9157 ClassTemplateSpecializationDecl *Def
9158 = cast_or_null<ClassTemplateSpecializationDecl>(
9159 Specialization->getDefinition());
9160 if (!Def)
9161 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
9162 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9163 MarkVTableUsed(TemplateNameLoc, Specialization, true);
9164 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9165 }
9166
9167 // Instantiate the members of this class template specialization.
9168 Def = cast_or_null<ClassTemplateSpecializationDecl>(
9169 Specialization->getDefinition());
9170 if (Def) {
9171 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
9172 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9173 // TSK_ExplicitInstantiationDefinition
9174 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
9175 (TSK == TSK_ExplicitInstantiationDefinition ||
9176 DLLImportExplicitInstantiationDef)) {
9177 // FIXME: Need to notify the ASTMutationListener that we did this.
9178 Def->setTemplateSpecializationKind(TSK);
9179
9180 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
9181 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9182 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
9183 // In the MS ABI, an explicit instantiation definition can add a dll
9184 // attribute to a template with a previous instantiation declaration.
9185 // MinGW doesn't allow this.
9186 auto *A = cast<InheritableAttr>(
9187 getDLLAttr(Specialization)->clone(getASTContext()));
9188 A->setInherited(true);
9189 Def->addAttr(A);
9190 dllExportImportClassTemplateSpecialization(*this, Def);
9191 }
9192 }
9193
9194 // Fix a TSK_ImplicitInstantiation followed by a
9195 // TSK_ExplicitInstantiationDefinition
9196 bool NewlyDLLExported =
9197 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9198 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
9199 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9200 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
9201 // In the MS ABI, an explicit instantiation definition can add a dll
9202 // attribute to a template with a previous implicit instantiation.
9203 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
9204 // avoid potentially strange codegen behavior. For example, if we extend
9205 // this conditional to dllimport, and we have a source file calling a
9206 // method on an implicitly instantiated template class instance and then
9207 // declaring a dllimport explicit instantiation definition for the same
9208 // template class, the codegen for the method call will not respect the
9209 // dllimport, while it will with cl. The Def will already have the DLL
9210 // attribute, since the Def and Specialization will be the same in the
9211 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
9212 // attribute to the Specialization; we just need to make it take effect.
9213 assert(Def == Specialization &&((Def == Specialization && "Def and Specialization should match for implicit instantiation"
) ? static_cast<void> (0) : __assert_fail ("Def == Specialization && \"Def and Specialization should match for implicit instantiation\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9214, __PRETTY_FUNCTION__))
9214 "Def and Specialization should match for implicit instantiation")((Def == Specialization && "Def and Specialization should match for implicit instantiation"
) ? static_cast<void> (0) : __assert_fail ("Def == Specialization && \"Def and Specialization should match for implicit instantiation\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9214, __PRETTY_FUNCTION__))
;
9215 dllExportImportClassTemplateSpecialization(*this, Def);
9216 }
9217
9218 // In MinGW mode, export the template instantiation if the declaration
9219 // was marked dllexport.
9220 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9221 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
9222 PrevDecl->hasAttr<DLLExportAttr>()) {
9223 dllExportImportClassTemplateSpecialization(*this, Def);
9224 }
9225
9226 // Set the template specialization kind. Make sure it is set before
9227 // instantiating the members which will trigger ASTConsumer callbacks.
9228 Specialization->setTemplateSpecializationKind(TSK);
9229 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
9230 } else {
9231
9232 // Set the template specialization kind.
9233 Specialization->setTemplateSpecializationKind(TSK);
9234 }
9235
9236 return Specialization;
9237}
9238
9239// Explicit instantiation of a member class of a class template.
9240DeclResult
9241Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
9242 SourceLocation TemplateLoc, unsigned TagSpec,
9243 SourceLocation KWLoc, CXXScopeSpec &SS,
9244 IdentifierInfo *Name, SourceLocation NameLoc,
9245 const ParsedAttributesView &Attr) {
9246
9247 bool Owned = false;
9248 bool IsDependent = false;
9249 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
9250 KWLoc, SS, Name, NameLoc, Attr, AS_none,
9251 /*ModulePrivateLoc=*/SourceLocation(),
9252 MultiTemplateParamsArg(), Owned, IsDependent,
9253 SourceLocation(), false, TypeResult(),
9254 /*IsTypeSpecifier*/false,
9255 /*IsTemplateParamOrArg*/false);
9256 assert(!IsDependent && "explicit instantiation of dependent name not yet handled")((!IsDependent && "explicit instantiation of dependent name not yet handled"
) ? static_cast<void> (0) : __assert_fail ("!IsDependent && \"explicit instantiation of dependent name not yet handled\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9256, __PRETTY_FUNCTION__))
;
9257
9258 if (!TagD)
9259 return true;
9260
9261 TagDecl *Tag = cast<TagDecl>(TagD);
9262 assert(!Tag->isEnum() && "shouldn't see enumerations here")((!Tag->isEnum() && "shouldn't see enumerations here"
) ? static_cast<void> (0) : __assert_fail ("!Tag->isEnum() && \"shouldn't see enumerations here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9262, __PRETTY_FUNCTION__))
;
9263
9264 if (Tag->isInvalidDecl())
9265 return true;
9266
9267 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
9268 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
9269 if (!Pattern) {
9270 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
9271 << Context.getTypeDeclType(Record);
9272 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
9273 return true;
9274 }
9275
9276 // C++0x [temp.explicit]p2:
9277 // If the explicit instantiation is for a class or member class, the
9278 // elaborated-type-specifier in the declaration shall include a
9279 // simple-template-id.
9280 //
9281 // C++98 has the same restriction, just worded differently.
9282 if (!ScopeSpecifierHasTemplateId(SS))
9283 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
9284 << Record << SS.getRange();
9285
9286 // C++0x [temp.explicit]p2:
9287 // There are two forms of explicit instantiation: an explicit instantiation
9288 // definition and an explicit instantiation declaration. An explicit
9289 // instantiation declaration begins with the extern keyword. [...]
9290 TemplateSpecializationKind TSK
9291 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9292 : TSK_ExplicitInstantiationDeclaration;
9293
9294 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
9295
9296 // Verify that it is okay to explicitly instantiate here.
9297 CXXRecordDecl *PrevDecl
9298 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
9299 if (!PrevDecl && Record->getDefinition())
9300 PrevDecl = Record;
9301 if (PrevDecl) {
9302 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
9303 bool HasNoEffect = false;
9304 assert(MSInfo && "No member specialization information?")((MSInfo && "No member specialization information?") ?
static_cast<void> (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9304, __PRETTY_FUNCTION__))
;
9305 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
9306 PrevDecl,
9307 MSInfo->getTemplateSpecializationKind(),
9308 MSInfo->getPointOfInstantiation(),
9309 HasNoEffect))
9310 return true;
9311 if (HasNoEffect)
9312 return TagD;
9313 }
9314
9315 CXXRecordDecl *RecordDef
9316 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9317 if (!RecordDef) {
9318 // C++ [temp.explicit]p3:
9319 // A definition of a member class of a class template shall be in scope
9320 // at the point of an explicit instantiation of the member class.
9321 CXXRecordDecl *Def
9322 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
9323 if (!Def) {
9324 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
9325 << 0 << Record->getDeclName() << Record->getDeclContext();
9326 Diag(Pattern->getLocation(), diag::note_forward_declaration)
9327 << Pattern;
9328 return true;
9329 } else {
9330 if (InstantiateClass(NameLoc, Record, Def,
9331 getTemplateInstantiationArgs(Record),
9332 TSK))
9333 return true;
9334
9335 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9336 if (!RecordDef)
9337 return true;
9338 }
9339 }
9340
9341 // Instantiate all of the members of the class.
9342 InstantiateClassMembers(NameLoc, RecordDef,
9343 getTemplateInstantiationArgs(Record), TSK);
9344
9345 if (TSK == TSK_ExplicitInstantiationDefinition)
9346 MarkVTableUsed(NameLoc, RecordDef, true);
9347
9348 // FIXME: We don't have any representation for explicit instantiations of
9349 // member classes. Such a representation is not needed for compilation, but it
9350 // should be available for clients that want to see all of the declarations in
9351 // the source code.
9352 return TagD;
9353}
9354
9355DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
9356 SourceLocation ExternLoc,
9357 SourceLocation TemplateLoc,
9358 Declarator &D) {
9359 // Explicit instantiations always require a name.
9360 // TODO: check if/when DNInfo should replace Name.
9361 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9362 DeclarationName Name = NameInfo.getName();
9363 if (!Name) {
9364 if (!D.isInvalidType())
9365 Diag(D.getDeclSpec().getBeginLoc(),
9366 diag::err_explicit_instantiation_requires_name)
9367 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
9368
9369 return true;
9370 }
9371
9372 // The scope passed in may not be a decl scope. Zip up the scope tree until
9373 // we find one that is.
9374 while ((S->getFlags() & Scope::DeclScope) == 0 ||
9375 (S->getFlags() & Scope::TemplateParamScope) != 0)
9376 S = S->getParent();
9377
9378 // Determine the type of the declaration.
9379 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9380 QualType R = T->getType();
9381 if (R.isNull())
9382 return true;
9383
9384 // C++ [dcl.stc]p1:
9385 // A storage-class-specifier shall not be specified in [...] an explicit
9386 // instantiation (14.7.2) directive.
9387 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
9388 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9389 << Name;
9390 return true;
9391 } else if (D.getDeclSpec().getStorageClassSpec()
9392 != DeclSpec::SCS_unspecified) {
9393 // Complain about then remove the storage class specifier.
9394 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9395 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9396
9397 D.getMutableDeclSpec().ClearStorageClassSpecs();
9398 }
9399
9400 // C++0x [temp.explicit]p1:
9401 // [...] An explicit instantiation of a function template shall not use the
9402 // inline or constexpr specifiers.
9403 // Presumably, this also applies to member functions of class templates as
9404 // well.
9405 if (D.getDeclSpec().isInlineSpecified())
9406 Diag(D.getDeclSpec().getInlineSpecLoc(),
9407 getLangOpts().CPlusPlus11 ?
9408 diag::err_explicit_instantiation_inline :
9409 diag::warn_explicit_instantiation_inline_0x)
9410 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9411 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
9412 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9413 // not already specified.
9414 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9415 diag::err_explicit_instantiation_constexpr);
9416
9417 // A deduction guide is not on the list of entities that can be explicitly
9418 // instantiated.
9419 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9420 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9421 << /*explicit instantiation*/ 0;
9422 return true;
9423 }
9424
9425 // C++0x [temp.explicit]p2:
9426 // There are two forms of explicit instantiation: an explicit instantiation
9427 // definition and an explicit instantiation declaration. An explicit
9428 // instantiation declaration begins with the extern keyword. [...]
9429 TemplateSpecializationKind TSK
9430 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9431 : TSK_ExplicitInstantiationDeclaration;
9432
9433 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
9434 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
9435
9436 if (!R->isFunctionType()) {
9437 // C++ [temp.explicit]p1:
9438 // A [...] static data member of a class template can be explicitly
9439 // instantiated from the member definition associated with its class
9440 // template.
9441 // C++1y [temp.explicit]p1:
9442 // A [...] variable [...] template specialization can be explicitly
9443 // instantiated from its template.
9444 if (Previous.isAmbiguous())
9445 return true;
9446
9447 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
9448 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
9449
9450 if (!PrevTemplate) {
9451 if (!Prev || !Prev->isStaticDataMember()) {
9452 // We expect to see a static data member here.
9453 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9454 << Name;
9455 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9456 P != PEnd; ++P)
9457 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9458 return true;
9459 }
9460
9461 if (!Prev->getInstantiatedFromStaticDataMember()) {
9462 // FIXME: Check for explicit specialization?
9463 Diag(D.getIdentifierLoc(),
9464 diag::err_explicit_instantiation_data_member_not_instantiated)
9465 << Prev;
9466 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9467 // FIXME: Can we provide a note showing where this was declared?
9468 return true;
9469 }
9470 } else {
9471 // Explicitly instantiate a variable template.
9472
9473 // C++1y [dcl.spec.auto]p6:
9474 // ... A program that uses auto or decltype(auto) in a context not
9475 // explicitly allowed in this section is ill-formed.
9476 //
9477 // This includes auto-typed variable template instantiations.
9478 if (R->isUndeducedType()) {
9479 Diag(T->getTypeLoc().getBeginLoc(),
9480 diag::err_auto_not_allowed_var_inst);
9481 return true;
9482 }
9483
9484 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9485 // C++1y [temp.explicit]p3:
9486 // If the explicit instantiation is for a variable, the unqualified-id
9487 // in the declaration shall be a template-id.
9488 Diag(D.getIdentifierLoc(),
9489 diag::err_explicit_instantiation_without_template_id)
9490 << PrevTemplate;
9491 Diag(PrevTemplate->getLocation(),
9492 diag::note_explicit_instantiation_here);
9493 return true;
9494 }
9495
9496 // Translate the parser's template argument list into our AST format.
9497 TemplateArgumentListInfo TemplateArgs =
9498 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9499
9500 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9501 D.getIdentifierLoc(), TemplateArgs);
9502 if (Res.isInvalid())
9503 return true;
9504
9505 // Ignore access control bits, we don't need them for redeclaration
9506 // checking.
9507 Prev = cast<VarDecl>(Res.get());
9508 }
9509
9510 // C++0x [temp.explicit]p2:
9511 // If the explicit instantiation is for a member function, a member class
9512 // or a static data member of a class template specialization, the name of
9513 // the class template specialization in the qualified-id for the member
9514 // name shall be a simple-template-id.
9515 //
9516 // C++98 has the same restriction, just worded differently.
9517 //
9518 // This does not apply to variable template specializations, where the
9519 // template-id is in the unqualified-id instead.
9520 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
9521 Diag(D.getIdentifierLoc(),
9522 diag::ext_explicit_instantiation_without_qualified_id)
9523 << Prev << D.getCXXScopeSpec().getRange();
9524
9525 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
9526
9527 // Verify that it is okay to explicitly instantiate here.
9528 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9529 SourceLocation POI = Prev->getPointOfInstantiation();
9530 bool HasNoEffect = false;
9531 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
9532 PrevTSK, POI, HasNoEffect))
9533 return true;
9534
9535 if (!HasNoEffect) {
9536 // Instantiate static data member or variable template.
9537 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9538 // Merge attributes.
9539 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
9540 if (TSK == TSK_ExplicitInstantiationDefinition)
9541 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9542 }
9543
9544 // Check the new variable specialization against the parsed input.
9545 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9546 Diag(T->getTypeLoc().getBeginLoc(),
9547 diag::err_invalid_var_template_spec_type)
9548 << 0 << PrevTemplate << R << Prev->getType();
9549 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9550 << 2 << PrevTemplate->getDeclName();
9551 return true;
9552 }
9553
9554 // FIXME: Create an ExplicitInstantiation node?
9555 return (Decl*) nullptr;
9556 }
9557
9558 // If the declarator is a template-id, translate the parser's template
9559 // argument list into our AST format.
9560 bool HasExplicitTemplateArgs = false;
9561 TemplateArgumentListInfo TemplateArgs;
9562 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9563 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9564 HasExplicitTemplateArgs = true;
9565 }
9566
9567 // C++ [temp.explicit]p1:
9568 // A [...] function [...] can be explicitly instantiated from its template.
9569 // A member function [...] of a class template can be explicitly
9570 // instantiated from the member definition associated with its class
9571 // template.
9572 UnresolvedSet<8> TemplateMatches;
9573 FunctionDecl *NonTemplateMatch = nullptr;
9574 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
9575 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9576 P != PEnd; ++P) {
9577 NamedDecl *Prev = *P;
9578 if (!HasExplicitTemplateArgs) {
9579 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
9580 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9581 /*AdjustExceptionSpec*/true);
9582 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
9583 if (Method->getPrimaryTemplate()) {
9584 TemplateMatches.addDecl(Method, P.getAccess());
9585 } else {
9586 // FIXME: Can this assert ever happen? Needs a test.
9587 assert(!NonTemplateMatch && "Multiple NonTemplateMatches")((!NonTemplateMatch && "Multiple NonTemplateMatches")
? static_cast<void> (0) : __assert_fail ("!NonTemplateMatch && \"Multiple NonTemplateMatches\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9587, __PRETTY_FUNCTION__))
;
9588 NonTemplateMatch = Method;
9589 }
9590 }
9591 }
9592 }
9593
9594 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9595 if (!FunTmpl)
9596 continue;
9597
9598 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9599 FunctionDecl *Specialization = nullptr;
9600 if (TemplateDeductionResult TDK
9601 = DeduceTemplateArguments(FunTmpl,
9602 (HasExplicitTemplateArgs ? &TemplateArgs
9603 : nullptr),
9604 R, Specialization, Info)) {
9605 // Keep track of almost-matches.
9606 FailedCandidates.addCandidate()
9607 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
9608 MakeDeductionFailureInfo(Context, TDK, Info));
9609 (void)TDK;
9610 continue;
9611 }
9612
9613 // Target attributes are part of the cuda function signature, so
9614 // the cuda target of the instantiated function must match that of its
9615 // template. Given that C++ template deduction does not take
9616 // target attributes into account, we reject candidates here that
9617 // have a different target.
9618 if (LangOpts.CUDA &&
9619 IdentifyCUDATarget(Specialization,
9620 /* IgnoreImplicitHDAttr = */ true) !=
9621 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
9622 FailedCandidates.addCandidate().set(
9623 P.getPair(), FunTmpl->getTemplatedDecl(),
9624 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9625 continue;
9626 }
9627
9628 TemplateMatches.addDecl(Specialization, P.getAccess());
9629 }
9630
9631 FunctionDecl *Specialization = NonTemplateMatch;
9632 if (!Specialization) {
9633 // Find the most specialized function template specialization.
9634 UnresolvedSetIterator Result = getMostSpecialized(
9635 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9636 D.getIdentifierLoc(),
9637 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9638 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9639 PDiag(diag::note_explicit_instantiation_candidate));
9640
9641 if (Result == TemplateMatches.end())
9642 return true;
9643
9644 // Ignore access control bits, we don't need them for redeclaration checking.
9645 Specialization = cast<FunctionDecl>(*Result);
9646 }
9647
9648 // C++11 [except.spec]p4
9649 // In an explicit instantiation an exception-specification may be specified,
9650 // but is not required.
9651 // If an exception-specification is specified in an explicit instantiation
9652 // directive, it shall be compatible with the exception-specifications of
9653 // other declarations of that function.
9654 if (auto *FPT = R->getAs<FunctionProtoType>())
9655 if (FPT->hasExceptionSpec()) {
9656 unsigned DiagID =
9657 diag::err_mismatched_exception_spec_explicit_instantiation;
9658 if (getLangOpts().MicrosoftExt)
9659 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9660 bool Result = CheckEquivalentExceptionSpec(
9661 PDiag(DiagID) << Specialization->getType(),
9662 PDiag(diag::note_explicit_instantiation_here),
9663 Specialization->getType()->getAs<FunctionProtoType>(),
9664 Specialization->getLocation(), FPT, D.getBeginLoc());
9665 // In Microsoft mode, mismatching exception specifications just cause a
9666 // warning.
9667 if (!getLangOpts().MicrosoftExt && Result)
9668 return true;
9669 }
9670
9671 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
9672 Diag(D.getIdentifierLoc(),
9673 diag::err_explicit_instantiation_member_function_not_instantiated)
9674 << Specialization
9675 << (Specialization->getTemplateSpecializationKind() ==
9676 TSK_ExplicitSpecialization);
9677 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9678 return true;
9679 }
9680
9681 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
9682 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9683 PrevDecl = Specialization;
9684
9685 if (PrevDecl) {
9686 bool HasNoEffect = false;
9687 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
9688 PrevDecl,
9689 PrevDecl->getTemplateSpecializationKind(),
9690 PrevDecl->getPointOfInstantiation(),
9691 HasNoEffect))
9692 return true;
9693
9694 // FIXME: We may still want to build some representation of this
9695 // explicit specialization.
9696 if (HasNoEffect)
9697 return (Decl*) nullptr;
9698 }
9699
9700 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
9701 // functions
9702 // valarray<size_t>::valarray(size_t) and
9703 // valarray<size_t>::~valarray()
9704 // that it declared to have internal linkage with the internal_linkage
9705 // attribute. Ignore the explicit instantiation declaration in this case.
9706 if (Specialization->hasAttr<InternalLinkageAttr>() &&
9707 TSK == TSK_ExplicitInstantiationDeclaration) {
9708 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
9709 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
9710 RD->isInStdNamespace())
9711 return (Decl*) nullptr;
9712 }
9713
9714 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
9715
9716 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9717 // instantiation declarations.
9718 if (TSK == TSK_ExplicitInstantiationDefinition &&
9719 Specialization->hasAttr<DLLImportAttr>() &&
9720 Context.getTargetInfo().getCXXABI().isMicrosoft())
9721 TSK = TSK_ExplicitInstantiationDeclaration;
9722
9723 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9724
9725 if (Specialization->isDefined()) {
9726 // Let the ASTConsumer know that this function has been explicitly
9727 // instantiated now, and its linkage might have changed.
9728 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9729 } else if (TSK == TSK_ExplicitInstantiationDefinition)
9730 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
9731
9732 // C++0x [temp.explicit]p2:
9733 // If the explicit instantiation is for a member function, a member class
9734 // or a static data member of a class template specialization, the name of
9735 // the class template specialization in the qualified-id for the member
9736 // name shall be a simple-template-id.
9737 //
9738 // C++98 has the same restriction, just worded differently.
9739 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
9740 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
9741 D.getCXXScopeSpec().isSet() &&
9742 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
9743 Diag(D.getIdentifierLoc(),
9744 diag::ext_explicit_instantiation_without_qualified_id)
9745 << Specialization << D.getCXXScopeSpec().getRange();
9746
9747 CheckExplicitInstantiation(
9748 *this,
9749 FunTmpl ? (NamedDecl *)FunTmpl
9750 : Specialization->getInstantiatedFromMemberFunction(),
9751 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
9752
9753 // FIXME: Create some kind of ExplicitInstantiationDecl here.
9754 return (Decl*) nullptr;
9755}
9756
9757TypeResult
9758Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9759 const CXXScopeSpec &SS, IdentifierInfo *Name,
9760 SourceLocation TagLoc, SourceLocation NameLoc) {
9761 // This has to hold, because SS is expected to be defined.
9762 assert(Name && "Expected a name in a dependent tag")((Name && "Expected a name in a dependent tag") ? static_cast
<void> (0) : __assert_fail ("Name && \"Expected a name in a dependent tag\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9762, __PRETTY_FUNCTION__))
;
9763
9764 NestedNameSpecifier *NNS = SS.getScopeRep();
9765 if (!NNS)
9766 return true;
9767
9768 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9769
9770 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9771 Diag(NameLoc, diag::err_dependent_tag_decl)
9772 << (TUK == TUK_Definition) << Kind << SS.getRange();
9773 return true;
9774 }
9775
9776 // Create the resulting type.
9777 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9778 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
9779
9780 // Create type-source location information for this type.
9781 TypeLocBuilder TLB;
9782 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
9783 TL.setElaboratedKeywordLoc(TagLoc);
9784 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9785 TL.setNameLoc(NameLoc);
9786 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
9787}
9788
9789TypeResult
9790Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9791 const CXXScopeSpec &SS, const IdentifierInfo &II,
9792 SourceLocation IdLoc) {
9793 if (SS.isInvalid())
9794 return true;
9795
9796 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9797 Diag(TypenameLoc,
9798 getLangOpts().CPlusPlus11 ?
9799 diag::warn_cxx98_compat_typename_outside_of_template :
9800 diag::ext_typename_outside_of_template)
9801 << FixItHint::CreateRemoval(TypenameLoc);
9802
9803 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9804 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9805 TypenameLoc, QualifierLoc, II, IdLoc);
9806 if (T.isNull())
9807 return true;
9808
9809 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9810 if (isa<DependentNameType>(T)) {
9811 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
9812 TL.setElaboratedKeywordLoc(TypenameLoc);
9813 TL.setQualifierLoc(QualifierLoc);
9814 TL.setNameLoc(IdLoc);
9815 } else {
9816 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
9817 TL.setElaboratedKeywordLoc(TypenameLoc);
9818 TL.setQualifierLoc(QualifierLoc);
9819 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
9820 }
9821
9822 return CreateParsedType(T, TSI);
9823}
9824
9825TypeResult
9826Sema::ActOnTypenameType(Scope *S,
9827 SourceLocation TypenameLoc,
9828 const CXXScopeSpec &SS,
9829 SourceLocation TemplateKWLoc,
9830 TemplateTy TemplateIn,
9831 IdentifierInfo *TemplateII,
9832 SourceLocation TemplateIILoc,
9833 SourceLocation LAngleLoc,
9834 ASTTemplateArgsPtr TemplateArgsIn,
9835 SourceLocation RAngleLoc) {
9836 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9837 Diag(TypenameLoc,
9838 getLangOpts().CPlusPlus11 ?
9839 diag::warn_cxx98_compat_typename_outside_of_template :
9840 diag::ext_typename_outside_of_template)
9841 << FixItHint::CreateRemoval(TypenameLoc);
9842
9843 // Strangely, non-type results are not ignored by this lookup, so the
9844 // program is ill-formed if it finds an injected-class-name.
9845 if (TypenameLoc.isValid()) {
9846 auto *LookupRD =
9847 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9848 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9849 Diag(TemplateIILoc,
9850 diag::ext_out_of_line_qualified_id_type_names_constructor)
9851 << TemplateII << 0 /*injected-class-name used as template name*/
9852 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9853 }
9854 }
9855
9856 // Translate the parser's template argument list in our AST format.
9857 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9858 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9859
9860 TemplateName Template = TemplateIn.get();
9861 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9862 // Construct a dependent template specialization type.
9863 assert(DTN && "dependent template has non-dependent name?")((DTN && "dependent template has non-dependent name?"
) ? static_cast<void> (0) : __assert_fail ("DTN && \"dependent template has non-dependent name?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9863, __PRETTY_FUNCTION__))
;
9864 assert(DTN->getQualifier() == SS.getScopeRep())((DTN->getQualifier() == SS.getScopeRep()) ? static_cast<
void> (0) : __assert_fail ("DTN->getQualifier() == SS.getScopeRep()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9864, __PRETTY_FUNCTION__))
;
9865 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9866 DTN->getQualifier(),
9867 DTN->getIdentifier(),
9868 TemplateArgs);
9869
9870 // Create source-location information for this type.
9871 TypeLocBuilder Builder;
9872 DependentTemplateSpecializationTypeLoc SpecTL
9873 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
9874 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9875 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
9876 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9877 SpecTL.setTemplateNameLoc(TemplateIILoc);
9878 SpecTL.setLAngleLoc(LAngleLoc);
9879 SpecTL.setRAngleLoc(RAngleLoc);
9880 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9881 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9882 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
9883 }
9884
9885 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
9886 if (T.isNull())
9887 return true;
9888
9889 // Provide source-location information for the template specialization type.
9890 TypeLocBuilder Builder;
9891 TemplateSpecializationTypeLoc SpecTL
9892 = Builder.push<TemplateSpecializationTypeLoc>(T);
9893 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9894 SpecTL.setTemplateNameLoc(TemplateIILoc);
9895 SpecTL.setLAngleLoc(LAngleLoc);
9896 SpecTL.setRAngleLoc(RAngleLoc);
9897 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9898 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9899
9900 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9901 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
9902 TL.setElaboratedKeywordLoc(TypenameLoc);
9903 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9904
9905 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9906 return CreateParsedType(T, TSI);
9907}
9908
9909
9910/// Determine whether this failed name lookup should be treated as being
9911/// disabled by a usage of std::enable_if.
9912static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
9913 SourceRange &CondRange, Expr *&Cond) {
9914 // We must be looking for a ::type...
9915 if (!II.isStr("type"))
9916 return false;
9917
9918 // ... within an explicitly-written template specialization...
9919 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9920 return false;
9921 TypeLoc EnableIfTy = NNS.getTypeLoc();
9922 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9923 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9924 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
9925 return false;
9926 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
9927
9928 // ... which names a complete class template declaration...
9929 const TemplateDecl *EnableIfDecl =
9930 EnableIfTST->getTemplateName().getAsTemplateDecl();
9931 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9932 return false;
9933
9934 // ... called "enable_if".
9935 const IdentifierInfo *EnableIfII =
9936 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9937 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9938 return false;
9939
9940 // Assume the first template argument is the condition.
9941 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
9942
9943 // Dig out the condition.
9944 Cond = nullptr;
9945 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9946 != TemplateArgument::Expression)
9947 return true;
9948
9949 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9950
9951 // Ignore Boolean literals; they add no value.
9952 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9953 Cond = nullptr;
9954
9955 return true;
9956}
9957
9958/// Build the type that describes a C++ typename specifier,
9959/// e.g., "typename T::type".
9960QualType
9961Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
9962 SourceLocation KeywordLoc,
9963 NestedNameSpecifierLoc QualifierLoc,
9964 const IdentifierInfo &II,
9965 SourceLocation IILoc) {
9966 CXXScopeSpec SS;
9967 SS.Adopt(QualifierLoc);
9968
9969 DeclContext *Ctx = computeDeclContext(SS);
9970 if (!Ctx) {
9971 // If the nested-name-specifier is dependent and couldn't be
9972 // resolved to a type, build a typename type.
9973 assert(QualifierLoc.getNestedNameSpecifier()->isDependent())((QualifierLoc.getNestedNameSpecifier()->isDependent()) ? static_cast
<void> (0) : __assert_fail ("QualifierLoc.getNestedNameSpecifier()->isDependent()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9973, __PRETTY_FUNCTION__))
;
9974 return Context.getDependentNameType(Keyword,
9975 QualifierLoc.getNestedNameSpecifier(),
9976 &II);
9977 }
9978
9979 // If the nested-name-specifier refers to the current instantiation,
9980 // the "typename" keyword itself is superfluous. In C++03, the
9981 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9982 // allows such extraneous "typename" keywords, and we retroactively
9983 // apply this DR to C++03 code with only a warning. In any case we continue.
9984
9985 if (RequireCompleteDeclContext(SS, Ctx))
9986 return QualType();
9987
9988 DeclarationName Name(&II);
9989 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
9990 LookupQualifiedName(Result, Ctx, SS);
9991 unsigned DiagID = 0;
9992 Decl *Referenced = nullptr;
9993 switch (Result.getResultKind()) {
9994 case LookupResult::NotFound: {
9995 // If we're looking up 'type' within a template named 'enable_if', produce
9996 // a more specific diagnostic.
9997 SourceRange CondRange;
9998 Expr *Cond = nullptr;
9999 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10000 // If we have a condition, narrow it down to the specific failed
10001 // condition.
10002 if (Cond) {
10003 Expr *FailedCond;
10004 std::string FailedDescription;
10005 std::tie(FailedCond, FailedDescription) =
10006 findFailedBooleanCondition(Cond);
10007
10008 Diag(FailedCond->getExprLoc(),
10009 diag::err_typename_nested_not_found_requirement)
10010 << FailedDescription
10011 << FailedCond->getSourceRange();
10012 return QualType();
10013 }
10014
10015 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
10016 << Ctx << CondRange;
10017 return QualType();
10018 }
10019
10020 DiagID = diag::err_typename_nested_not_found;
10021 break;
10022 }
10023
10024 case LookupResult::FoundUnresolvedValue: {
10025 // We found a using declaration that is a value. Most likely, the using
10026 // declaration itself is meant to have the 'typename' keyword.
10027 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10028 IILoc);
10029 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10030 << Name << Ctx << FullRange;
10031 if (UnresolvedUsingValueDecl *Using
10032 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
10033 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
10034 Diag(Loc, diag::note_using_value_decl_missing_typename)
10035 << FixItHint::CreateInsertion(Loc, "typename ");
10036 }
10037 }
10038 // Fall through to create a dependent typename type, from which we can recover
10039 // better.
10040 LLVM_FALLTHROUGH[[gnu::fallthrough]];
10041
10042 case LookupResult::NotFoundInCurrentInstantiation:
10043 // Okay, it's a member of an unknown instantiation.
10044 return Context.getDependentNameType(Keyword,
10045 QualifierLoc.getNestedNameSpecifier(),
10046 &II);
10047
10048 case LookupResult::Found:
10049 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
10050 // C++ [class.qual]p2:
10051 // In a lookup in which function names are not ignored and the
10052 // nested-name-specifier nominates a class C, if the name specified
10053 // after the nested-name-specifier, when looked up in C, is the
10054 // injected-class-name of C [...] then the name is instead considered
10055 // to name the constructor of class C.
10056 //
10057 // Unlike in an elaborated-type-specifier, function names are not ignored
10058 // in typename-specifier lookup. However, they are ignored in all the
10059 // contexts where we form a typename type with no keyword (that is, in
10060 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10061 //
10062 // FIXME: That's not strictly true: mem-initializer-id lookup does not
10063 // ignore functions, but that appears to be an oversight.
10064 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10065 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10066 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
10067 FoundRD->isInjectedClassName() &&
10068 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10069 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10070 << &II << 1 << 0 /*'typename' keyword used*/;
10071
10072 // We found a type. Build an ElaboratedType, since the
10073 // typename-specifier was just sugar.
10074 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
10075 return Context.getElaboratedType(Keyword,
10076 QualifierLoc.getNestedNameSpecifier(),
10077 Context.getTypeDeclType(Type));
10078 }
10079
10080 // C++ [dcl.type.simple]p2:
10081 // A type-specifier of the form
10082 // typename[opt] nested-name-specifier[opt] template-name
10083 // is a placeholder for a deduced class type [...].
10084 if (getLangOpts().CPlusPlus17) {
10085 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10086 return Context.getElaboratedType(
10087 Keyword, QualifierLoc.getNestedNameSpecifier(),
10088 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
10089 QualType(), false));
10090 }
10091 }
10092
10093 DiagID = diag::err_typename_nested_not_type;
10094 Referenced = Result.getFoundDecl();
10095 break;
10096
10097 case LookupResult::FoundOverloaded:
10098 DiagID = diag::err_typename_nested_not_type;
10099 Referenced = *Result.begin();
10100 break;
10101
10102 case LookupResult::Ambiguous:
10103 return QualType();
10104 }
10105
10106 // If we get here, it's because name lookup did not find a
10107 // type. Emit an appropriate diagnostic and return an error.
10108 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10109 IILoc);
10110 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
10111 if (Referenced)
10112 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
10113 << Name;
10114 return QualType();
10115}
10116
10117namespace {
10118 // See Sema::RebuildTypeInCurrentInstantiation
10119 class CurrentInstantiationRebuilder
10120 : public TreeTransform<CurrentInstantiationRebuilder> {
10121 SourceLocation Loc;
10122 DeclarationName Entity;
10123
10124 public:
10125 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
10126
10127 CurrentInstantiationRebuilder(Sema &SemaRef,
10128 SourceLocation Loc,
10129 DeclarationName Entity)
10130 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
10131 Loc(Loc), Entity(Entity) { }
10132
10133 /// Determine whether the given type \p T has already been
10134 /// transformed.
10135 ///
10136 /// For the purposes of type reconstruction, a type has already been
10137 /// transformed if it is NULL or if it is not dependent.
10138 bool AlreadyTransformed(QualType T) {
10139 return T.isNull() || !T->isDependentType();
10140 }
10141
10142 /// Returns the location of the entity whose type is being
10143 /// rebuilt.
10144 SourceLocation getBaseLocation() { return Loc; }
10145
10146 /// Returns the name of the entity whose type is being rebuilt.
10147 DeclarationName getBaseEntity() { return Entity; }
10148
10149 /// Sets the "base" location and entity when that
10150 /// information is known based on another transformation.
10151 void setBase(SourceLocation Loc, DeclarationName Entity) {
10152 this->Loc = Loc;
10153 this->Entity = Entity;
10154 }
10155
10156 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10157 // Lambdas never need to be transformed.
10158 return E;
10159 }
10160 };
10161} // end anonymous namespace
10162
10163/// Rebuilds a type within the context of the current instantiation.
10164///
10165/// The type \p T is part of the type of an out-of-line member definition of
10166/// a class template (or class template partial specialization) that was parsed
10167/// and constructed before we entered the scope of the class template (or
10168/// partial specialization thereof). This routine will rebuild that type now
10169/// that we have entered the declarator's scope, which may produce different
10170/// canonical types, e.g.,
10171///
10172/// \code
10173/// template<typename T>
10174/// struct X {
10175/// typedef T* pointer;
10176/// pointer data();
10177/// };
10178///
10179/// template<typename T>
10180/// typename X<T>::pointer X<T>::data() { ... }
10181/// \endcode
10182///
10183/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
10184/// since we do not know that we can look into X<T> when we parsed the type.
10185/// This function will rebuild the type, performing the lookup of "pointer"
10186/// in X<T> and returning an ElaboratedType whose canonical type is the same
10187/// as the canonical type of T*, allowing the return types of the out-of-line
10188/// definition and the declaration to match.
10189TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
10190 SourceLocation Loc,
10191 DeclarationName Name) {
10192 if (!T || !T->getType()->isDependentType())
10193 return T;
10194
10195 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
10196 return Rebuilder.TransformType(T);
10197}
10198
10199ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
10200 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
10201 DeclarationName());
10202 return Rebuilder.TransformExpr(E);
10203}
10204
10205bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
10206 if (SS.isInvalid())
10207 return true;
10208
10209 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10210 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
10211 DeclarationName());
10212 NestedNameSpecifierLoc Rebuilt
10213 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
10214 if (!Rebuilt)
10215 return true;
10216
10217 SS.Adopt(Rebuilt);
10218 return false;
10219}
10220
10221/// Rebuild the template parameters now that we know we're in a current
10222/// instantiation.
10223bool Sema::RebuildTemplateParamsInCurrentInstantiation(
10224 TemplateParameterList *Params) {
10225 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10226 Decl *Param = Params->getParam(I);
10227
10228 // There is nothing to rebuild in a type parameter.
10229 if (isa<TemplateTypeParmDecl>(Param))
10230 continue;
10231
10232 // Rebuild the template parameter list of a template template parameter.
10233 if (TemplateTemplateParmDecl *TTP
10234 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
10235 if (RebuildTemplateParamsInCurrentInstantiation(
10236 TTP->getTemplateParameters()))
10237 return true;
10238
10239 continue;
10240 }
10241
10242 // Rebuild the type of a non-type template parameter.
10243 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
10244 TypeSourceInfo *NewTSI
10245 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
10246 NTTP->getLocation(),
10247 NTTP->getDeclName());
10248 if (!NewTSI)
10249 return true;
10250
10251 if (NewTSI->getType()->isUndeducedType()) {
10252 // C++17 [temp.dep.expr]p3:
10253 // An id-expression is type-dependent if it contains
10254 // - an identifier associated by name lookup with a non-type
10255 // template-parameter declared with a type that contains a
10256 // placeholder type (7.1.7.4),
10257 NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
10258 }
10259
10260 if (NewTSI != NTTP->getTypeSourceInfo()) {
10261 NTTP->setTypeSourceInfo(NewTSI);
10262 NTTP->setType(NewTSI->getType());
10263 }
10264 }
10265
10266 return false;
10267}
10268
10269/// Produces a formatted string that describes the binding of
10270/// template parameters to template arguments.
10271std::string
10272Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10273 const TemplateArgumentList &Args) {
10274 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
10275}
10276
10277std::string
10278Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10279 const TemplateArgument *Args,
10280 unsigned NumArgs) {
10281 SmallString<128> Str;
10282 llvm::raw_svector_ostream Out(Str);
10283
10284 if (!Params || Params->size() == 0 || NumArgs == 0)
10285 return std::string();
10286
10287 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10288 if (I >= NumArgs)
10289 break;
10290
10291 if (I == 0)
10292 Out << "[with ";
10293 else
10294 Out << ", ";
10295
10296 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
10297 Out << Id->getName();
10298 } else {
10299 Out << '$' << I;
10300 }
10301
10302 Out << " = ";
10303 Args[I].print(getPrintingPolicy(), Out);
10304 }
10305
10306 Out << ']';
10307 return Out.str();
10308}
10309
10310void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
10311 CachedTokens &Toks) {
10312 if (!FD)
10313 return;
10314
10315 auto LPT = std::make_unique<LateParsedTemplate>();
10316
10317 // Take tokens to avoid allocations
10318 LPT->Toks.swap(Toks);
10319 LPT->D = FnD;
10320 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
10321
10322 FD->setLateTemplateParsed(true);
10323}
10324
10325void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
10326 if (!FD)
10327 return;
10328 FD->setLateTemplateParsed(false);
10329}
10330
10331bool Sema::IsInsideALocalClassWithinATemplateFunction() {
10332 DeclContext *DC = CurContext;
10333
10334 while (DC) {
10335 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
10336 const FunctionDecl *FD = RD->isLocalClass();
10337 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
10338 } else if (DC->isTranslationUnit() || DC->isNamespace())
10339 return false;
10340
10341 DC = DC->getParent();
10342 }
10343 return false;
10344}
10345
10346namespace {
10347/// Walk the path from which a declaration was instantiated, and check
10348/// that every explicit specialization along that path is visible. This enforces
10349/// C++ [temp.expl.spec]/6:
10350///
10351/// If a template, a member template or a member of a class template is
10352/// explicitly specialized then that specialization shall be declared before
10353/// the first use of that specialization that would cause an implicit
10354/// instantiation to take place, in every translation unit in which such a
10355/// use occurs; no diagnostic is required.
10356///
10357/// and also C++ [temp.class.spec]/1:
10358///
10359/// A partial specialization shall be declared before the first use of a
10360/// class template specialization that would make use of the partial
10361/// specialization as the result of an implicit or explicit instantiation
10362/// in every translation unit in which such a use occurs; no diagnostic is
10363/// required.
10364class ExplicitSpecializationVisibilityChecker {
10365 Sema &S;
10366 SourceLocation Loc;
10367 llvm::SmallVector<Module *, 8> Modules;
10368
10369public:
10370 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
10371 : S(S), Loc(Loc) {}
10372
10373 void check(NamedDecl *ND) {
10374 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10375 return checkImpl(FD);
10376 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10377 return checkImpl(RD);
10378 if (auto *VD = dyn_cast<VarDecl>(ND))
10379 return checkImpl(VD);
10380 if (auto *ED = dyn_cast<EnumDecl>(ND))
10381 return checkImpl(ED);
10382 }
10383
10384private:
10385 void diagnose(NamedDecl *D, bool IsPartialSpec) {
10386 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10387 : Sema::MissingImportKind::ExplicitSpecialization;
10388 const bool Recover = true;
10389
10390 // If we got a custom set of modules (because only a subset of the
10391 // declarations are interesting), use them, otherwise let
10392 // diagnoseMissingImport intelligently pick some.
10393 if (Modules.empty())
10394 S.diagnoseMissingImport(Loc, D, Kind, Recover);
10395 else
10396 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10397 }
10398
10399 // Check a specific declaration. There are three problematic cases:
10400 //
10401 // 1) The declaration is an explicit specialization of a template
10402 // specialization.
10403 // 2) The declaration is an explicit specialization of a member of an
10404 // templated class.
10405 // 3) The declaration is an instantiation of a template, and that template
10406 // is an explicit specialization of a member of a templated class.
10407 //
10408 // We don't need to go any deeper than that, as the instantiation of the
10409 // surrounding class / etc is not triggered by whatever triggered this
10410 // instantiation, and thus should be checked elsewhere.
10411 template<typename SpecDecl>
10412 void checkImpl(SpecDecl *Spec) {
10413 bool IsHiddenExplicitSpecialization = false;
10414 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10415 IsHiddenExplicitSpecialization =
10416 Spec->getMemberSpecializationInfo()
10417 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
10418 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
10419 } else {
10420 checkInstantiated(Spec);
10421 }
10422
10423 if (IsHiddenExplicitSpecialization)
10424 diagnose(Spec->getMostRecentDecl(), false);
10425 }
10426
10427 void checkInstantiated(FunctionDecl *FD) {
10428 if (auto *TD = FD->getPrimaryTemplate())
10429 checkTemplate(TD);
10430 }
10431
10432 void checkInstantiated(CXXRecordDecl *RD) {
10433 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10434 if (!SD)
10435 return;
10436
10437 auto From = SD->getSpecializedTemplateOrPartial();
10438 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10439 checkTemplate(TD);
10440 else if (auto *TD =
10441 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10442 if (!S.hasVisibleDeclaration(TD))
10443 diagnose(TD, true);
10444 checkTemplate(TD);
10445 }
10446 }
10447
10448 void checkInstantiated(VarDecl *RD) {
10449 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10450 if (!SD)
10451 return;
10452
10453 auto From = SD->getSpecializedTemplateOrPartial();
10454 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10455 checkTemplate(TD);
10456 else if (auto *TD =
10457 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10458 if (!S.hasVisibleDeclaration(TD))
10459 diagnose(TD, true);
10460 checkTemplate(TD);
10461 }
10462 }
10463
10464 void checkInstantiated(EnumDecl *FD) {}
10465
10466 template<typename TemplDecl>
10467 void checkTemplate(TemplDecl *TD) {
10468 if (TD->isMemberSpecialization()) {
10469 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10470 diagnose(TD->getMostRecentDecl(), false);
10471 }
10472 }
10473};
10474} // end anonymous namespace
10475
10476void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10477 if (!getLangOpts().Modules)
10478 return;
10479
10480 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10481}
10482
10483/// Check whether a template partial specialization that we've discovered
10484/// is hidden, and produce suitable diagnostics if so.
10485void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10486 NamedDecl *Spec) {
10487 llvm::SmallVector<Module *, 8> Modules;
10488 if (!hasVisibleDeclaration(Spec, &Modules))
10489 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10490 MissingImportKind::PartialSpecialization,
10491 /*Recover*/true);
10492}

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h

1//===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements a semantic tree transformation that takes a given
9// AST and rebuilds it, possibly transforming some nodes in the process.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
14#define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15
16#include "CoroutineStmtBuilder.h"
17#include "TypeLocBuilder.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/ExprOpenMP.h"
25#include "clang/AST/Stmt.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/AST/StmtObjC.h"
28#include "clang/AST/StmtOpenMP.h"
29#include "clang/Sema/Designator.h"
30#include "clang/Sema/Lookup.h"
31#include "clang/Sema/Ownership.h"
32#include "clang/Sema/ParsedTemplate.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/SemaDiagnostic.h"
35#include "clang/Sema/SemaInternal.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/Support/ErrorHandling.h"
38#include <algorithm>
39
40namespace clang {
41using namespace sema;
42
43/// A semantic tree transformation that allows one to transform one
44/// abstract syntax tree into another.
45///
46/// A new tree transformation is defined by creating a new subclass \c X of
47/// \c TreeTransform<X> and then overriding certain operations to provide
48/// behavior specific to that transformation. For example, template
49/// instantiation is implemented as a tree transformation where the
50/// transformation of TemplateTypeParmType nodes involves substituting the
51/// template arguments for their corresponding template parameters; a similar
52/// transformation is performed for non-type template parameters and
53/// template template parameters.
54///
55/// This tree-transformation template uses static polymorphism to allow
56/// subclasses to customize any of its operations. Thus, a subclass can
57/// override any of the transformation or rebuild operators by providing an
58/// operation with the same signature as the default implementation. The
59/// overriding function should not be virtual.
60///
61/// Semantic tree transformations are split into two stages, either of which
62/// can be replaced by a subclass. The "transform" step transforms an AST node
63/// or the parts of an AST node using the various transformation functions,
64/// then passes the pieces on to the "rebuild" step, which constructs a new AST
65/// node of the appropriate kind from the pieces. The default transformation
66/// routines recursively transform the operands to composite AST nodes (e.g.,
67/// the pointee type of a PointerType node) and, if any of those operand nodes
68/// were changed by the transformation, invokes the rebuild operation to create
69/// a new AST node.
70///
71/// Subclasses can customize the transformation at various levels. The
72/// most coarse-grained transformations involve replacing TransformType(),
73/// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
74/// TransformTemplateName(), or TransformTemplateArgument() with entirely
75/// new implementations.
76///
77/// For more fine-grained transformations, subclasses can replace any of the
78/// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
79/// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
80/// replacing TransformTemplateTypeParmType() allows template instantiation
81/// to substitute template arguments for their corresponding template
82/// parameters. Additionally, subclasses can override the \c RebuildXXX
83/// functions to control how AST nodes are rebuilt when their operands change.
84/// By default, \c TreeTransform will invoke semantic analysis to rebuild
85/// AST nodes. However, certain other tree transformations (e.g, cloning) may
86/// be able to use more efficient rebuild steps.
87///
88/// There are a handful of other functions that can be overridden, allowing one
89/// to avoid traversing nodes that don't need any transformation
90/// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
91/// operands have not changed (\c AlwaysRebuild()), and customize the
92/// default locations and entity names used for type-checking
93/// (\c getBaseLocation(), \c getBaseEntity()).
94template<typename Derived>
95class TreeTransform {
96 /// Private RAII object that helps us forget and then re-remember
97 /// the template argument corresponding to a partially-substituted parameter
98 /// pack.
99 class ForgetPartiallySubstitutedPackRAII {
100 Derived &Self;
101 TemplateArgument Old;
102
103 public:
104 ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
105 Old = Self.ForgetPartiallySubstitutedPack();
106 }
107
108 ~ForgetPartiallySubstitutedPackRAII() {
109 Self.RememberPartiallySubstitutedPack(Old);
110 }
111 };
112
113protected:
114 Sema &SemaRef;
115
116 /// The set of local declarations that have been transformed, for
117 /// cases where we are forced to build new declarations within the transformer
118 /// rather than in the subclass (e.g., lambda closure types).
119 llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
120
121public:
122 /// Initializes a new tree transformer.
123 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
124
125 /// Retrieves a reference to the derived class.
126 Derived &getDerived() { return static_cast<Derived&>(*this); }
127
128 /// Retrieves a reference to the derived class.
129 const Derived &getDerived() const {
130 return static_cast<const Derived&>(*this);
131 }
132
133 static inline ExprResult Owned(Expr *E) { return E; }
134 static inline StmtResult Owned(Stmt *S) { return S; }
135
136 /// Retrieves a reference to the semantic analysis object used for
137 /// this tree transform.
138 Sema &getSema() const { return SemaRef; }
139
140 /// Whether the transformation should always rebuild AST nodes, even
141 /// if none of the children have changed.
142 ///
143 /// Subclasses may override this function to specify when the transformation
144 /// should rebuild all AST nodes.
145 ///
146 /// We must always rebuild all AST nodes when performing variadic template
147 /// pack expansion, in order to avoid violating the AST invariant that each
148 /// statement node appears at most once in its containing declaration.
149 bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
150
151 /// Whether the transformation is forming an expression or statement that
152 /// replaces the original. In this case, we'll reuse mangling numbers from
153 /// existing lambdas.
154 bool ReplacingOriginal() { return false; }
155
156 /// Returns the location of the entity being transformed, if that
157 /// information was not available elsewhere in the AST.
158 ///
159 /// By default, returns no source-location information. Subclasses can
160 /// provide an alternative implementation that provides better location
161 /// information.
162 SourceLocation getBaseLocation() { return SourceLocation(); }
163
164 /// Returns the name of the entity being transformed, if that
165 /// information was not available elsewhere in the AST.
166 ///
167 /// By default, returns an empty name. Subclasses can provide an alternative
168 /// implementation with a more precise name.
169 DeclarationName getBaseEntity() { return DeclarationName(); }
170
171 /// Sets the "base" location and entity when that
172 /// information is known based on another transformation.
173 ///
174 /// By default, the source location and entity are ignored. Subclasses can
175 /// override this function to provide a customized implementation.
176 void setBase(SourceLocation Loc, DeclarationName Entity) { }
177
178 /// RAII object that temporarily sets the base location and entity
179 /// used for reporting diagnostics in types.
180 class TemporaryBase {
181 TreeTransform &Self;
182 SourceLocation OldLocation;
183 DeclarationName OldEntity;
184
185 public:
186 TemporaryBase(TreeTransform &Self, SourceLocation Location,
187 DeclarationName Entity) : Self(Self) {
188 OldLocation = Self.getDerived().getBaseLocation();
189 OldEntity = Self.getDerived().getBaseEntity();
190
191 if (Location.isValid())
192 Self.getDerived().setBase(Location, Entity);
193 }
194
195 ~TemporaryBase() {
196 Self.getDerived().setBase(OldLocation, OldEntity);
197 }
198 };
199
200 /// Determine whether the given type \p T has already been
201 /// transformed.
202 ///
203 /// Subclasses can provide an alternative implementation of this routine
204 /// to short-circuit evaluation when it is known that a given type will
205 /// not change. For example, template instantiation need not traverse
206 /// non-dependent types.
207 bool AlreadyTransformed(QualType T) {
208 return T.isNull();
209 }
210
211 /// Determine whether the given call argument should be dropped, e.g.,
212 /// because it is a default argument.
213 ///
214 /// Subclasses can provide an alternative implementation of this routine to
215 /// determine which kinds of call arguments get dropped. By default,
216 /// CXXDefaultArgument nodes are dropped (prior to transformation).
217 bool DropCallArgument(Expr *E) {
218 return E->isDefaultArgument();
219 }
220
221 /// Determine whether we should expand a pack expansion with the
222 /// given set of parameter packs into separate arguments by repeatedly
223 /// transforming the pattern.
224 ///
225 /// By default, the transformer never tries to expand pack expansions.
226 /// Subclasses can override this routine to provide different behavior.
227 ///
228 /// \param EllipsisLoc The location of the ellipsis that identifies the
229 /// pack expansion.
230 ///
231 /// \param PatternRange The source range that covers the entire pattern of
232 /// the pack expansion.
233 ///
234 /// \param Unexpanded The set of unexpanded parameter packs within the
235 /// pattern.
236 ///
237 /// \param ShouldExpand Will be set to \c true if the transformer should
238 /// expand the corresponding pack expansions into separate arguments. When
239 /// set, \c NumExpansions must also be set.
240 ///
241 /// \param RetainExpansion Whether the caller should add an unexpanded
242 /// pack expansion after all of the expanded arguments. This is used
243 /// when extending explicitly-specified template argument packs per
244 /// C++0x [temp.arg.explicit]p9.
245 ///
246 /// \param NumExpansions The number of separate arguments that will be in
247 /// the expanded form of the corresponding pack expansion. This is both an
248 /// input and an output parameter, which can be set by the caller if the
249 /// number of expansions is known a priori (e.g., due to a prior substitution)
250 /// and will be set by the callee when the number of expansions is known.
251 /// The callee must set this value when \c ShouldExpand is \c true; it may
252 /// set this value in other cases.
253 ///
254 /// \returns true if an error occurred (e.g., because the parameter packs
255 /// are to be instantiated with arguments of different lengths), false
256 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
257 /// must be set.
258 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
259 SourceRange PatternRange,
260 ArrayRef<UnexpandedParameterPack> Unexpanded,
261 bool &ShouldExpand,
262 bool &RetainExpansion,
263 Optional<unsigned> &NumExpansions) {
264 ShouldExpand = false;
265 return false;
266 }
267
268 /// "Forget" about the partially-substituted pack template argument,
269 /// when performing an instantiation that must preserve the parameter pack
270 /// use.
271 ///
272 /// This routine is meant to be overridden by the template instantiator.
273 TemplateArgument ForgetPartiallySubstitutedPack() {
274 return TemplateArgument();
275 }
276
277 /// "Remember" the partially-substituted pack template argument
278 /// after performing an instantiation that must preserve the parameter pack
279 /// use.
280 ///
281 /// This routine is meant to be overridden by the template instantiator.
282 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
283
284 /// Note to the derived class when a function parameter pack is
285 /// being expanded.
286 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
287
288 /// Transforms the given type into another type.
289 ///
290 /// By default, this routine transforms a type by creating a
291 /// TypeSourceInfo for it and delegating to the appropriate
292 /// function. This is expensive, but we don't mind, because
293 /// this method is deprecated anyway; all users should be
294 /// switched to storing TypeSourceInfos.
295 ///
296 /// \returns the transformed type.
297 QualType TransformType(QualType T);
298
299 /// Transforms the given type-with-location into a new
300 /// type-with-location.
301 ///
302 /// By default, this routine transforms a type by delegating to the
303 /// appropriate TransformXXXType to build a new type. Subclasses
304 /// may override this function (to take over all type
305 /// transformations) or some set of the TransformXXXType functions
306 /// to alter the transformation.
307 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
308
309 /// Transform the given type-with-location into a new
310 /// type, collecting location information in the given builder
311 /// as necessary.
312 ///
313 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
314
315 /// Transform a type that is permitted to produce a
316 /// DeducedTemplateSpecializationType.
317 ///
318 /// This is used in the (relatively rare) contexts where it is acceptable
319 /// for transformation to produce a class template type with deduced
320 /// template arguments.
321 /// @{
322 QualType TransformTypeWithDeducedTST(QualType T);
323 TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
324 /// @}
325
326 /// The reason why the value of a statement is not discarded, if any.
327 enum StmtDiscardKind {
328 SDK_Discarded,
329 SDK_NotDiscarded,
330 SDK_StmtExprResult,
331 };
332
333 /// Transform the given statement.
334 ///
335 /// By default, this routine transforms a statement by delegating to the
336 /// appropriate TransformXXXStmt function to transform a specific kind of
337 /// statement or the TransformExpr() function to transform an expression.
338 /// Subclasses may override this function to transform statements using some
339 /// other mechanism.
340 ///
341 /// \returns the transformed statement.
342 StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
343
344 /// Transform the given statement.
345 ///
346 /// By default, this routine transforms a statement by delegating to the
347 /// appropriate TransformOMPXXXClause function to transform a specific kind
348 /// of clause. Subclasses may override this function to transform statements
349 /// using some other mechanism.
350 ///
351 /// \returns the transformed OpenMP clause.
352 OMPClause *TransformOMPClause(OMPClause *S);
353
354 /// Transform the given attribute.
355 ///
356 /// By default, this routine transforms a statement by delegating to the
357 /// appropriate TransformXXXAttr function to transform a specific kind
358 /// of attribute. Subclasses may override this function to transform
359 /// attributed statements using some other mechanism.
360 ///
361 /// \returns the transformed attribute
362 const Attr *TransformAttr(const Attr *S);
363
364/// Transform the specified attribute.
365///
366/// Subclasses should override the transformation of attributes with a pragma
367/// spelling to transform expressions stored within the attribute.
368///
369/// \returns the transformed attribute.
370#define ATTR(X)
371#define PRAGMA_SPELLING_ATTR(X) \
372 const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
373#include "clang/Basic/AttrList.inc"
374
375 /// Transform the given expression.
376 ///
377 /// By default, this routine transforms an expression by delegating to the
378 /// appropriate TransformXXXExpr function to build a new expression.
379 /// Subclasses may override this function to transform expressions using some
380 /// other mechanism.
381 ///
382 /// \returns the transformed expression.
383 ExprResult TransformExpr(Expr *E);
384
385 /// Transform the given initializer.
386 ///
387 /// By default, this routine transforms an initializer by stripping off the
388 /// semantic nodes added by initialization, then passing the result to
389 /// TransformExpr or TransformExprs.
390 ///
391 /// \returns the transformed initializer.
392 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
393
394 /// Transform the given list of expressions.
395 ///
396 /// This routine transforms a list of expressions by invoking
397 /// \c TransformExpr() for each subexpression. However, it also provides
398 /// support for variadic templates by expanding any pack expansions (if the
399 /// derived class permits such expansion) along the way. When pack expansions
400 /// are present, the number of outputs may not equal the number of inputs.
401 ///
402 /// \param Inputs The set of expressions to be transformed.
403 ///
404 /// \param NumInputs The number of expressions in \c Inputs.
405 ///
406 /// \param IsCall If \c true, then this transform is being performed on
407 /// function-call arguments, and any arguments that should be dropped, will
408 /// be.
409 ///
410 /// \param Outputs The transformed input expressions will be added to this
411 /// vector.
412 ///
413 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
414 /// due to transformation.
415 ///
416 /// \returns true if an error occurred, false otherwise.
417 bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
418 SmallVectorImpl<Expr *> &Outputs,
419 bool *ArgChanged = nullptr);
420
421 /// Transform the given declaration, which is referenced from a type
422 /// or expression.
423 ///
424 /// By default, acts as the identity function on declarations, unless the
425 /// transformer has had to transform the declaration itself. Subclasses
426 /// may override this function to provide alternate behavior.
427 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
428 llvm::DenseMap<Decl *, Decl *>::iterator Known
429 = TransformedLocalDecls.find(D);
430 if (Known != TransformedLocalDecls.end())
431 return Known->second;
432
433 return D;
434 }
435
436 /// Transform the specified condition.
437 ///
438 /// By default, this transforms the variable and expression and rebuilds
439 /// the condition.
440 Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
441 Expr *Expr,
442 Sema::ConditionKind Kind);
443
444 /// Transform the attributes associated with the given declaration and
445 /// place them on the new declaration.
446 ///
447 /// By default, this operation does nothing. Subclasses may override this
448 /// behavior to transform attributes.
449 void transformAttrs(Decl *Old, Decl *New) { }
450
451 /// Note that a local declaration has been transformed by this
452 /// transformer.
453 ///
454 /// Local declarations are typically transformed via a call to
455 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
456 /// the transformer itself has to transform the declarations. This routine
457 /// can be overridden by a subclass that keeps track of such mappings.
458 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
459 assert(New.size() == 1 &&((New.size() == 1 && "must override transformedLocalDecl if performing pack expansion"
) ? static_cast<void> (0) : __assert_fail ("New.size() == 1 && \"must override transformedLocalDecl if performing pack expansion\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 460, __PRETTY_FUNCTION__))
460 "must override transformedLocalDecl if performing pack expansion")((New.size() == 1 && "must override transformedLocalDecl if performing pack expansion"
) ? static_cast<void> (0) : __assert_fail ("New.size() == 1 && \"must override transformedLocalDecl if performing pack expansion\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 460, __PRETTY_FUNCTION__))
;
461 TransformedLocalDecls[Old] = New.front();
462 }
463
464 /// Transform the definition of the given declaration.
465 ///
466 /// By default, invokes TransformDecl() to transform the declaration.
467 /// Subclasses may override this function to provide alternate behavior.
468 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
469 return getDerived().TransformDecl(Loc, D);
470 }
471
472 /// Transform the given declaration, which was the first part of a
473 /// nested-name-specifier in a member access expression.
474 ///
475 /// This specific declaration transformation only applies to the first
476 /// identifier in a nested-name-specifier of a member access expression, e.g.,
477 /// the \c T in \c x->T::member
478 ///
479 /// By default, invokes TransformDecl() to transform the declaration.
480 /// Subclasses may override this function to provide alternate behavior.
481 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
482 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
483 }
484
485 /// Transform the set of declarations in an OverloadExpr.
486 bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
487 LookupResult &R);
488
489 /// Transform the given nested-name-specifier with source-location
490 /// information.
491 ///
492 /// By default, transforms all of the types and declarations within the
493 /// nested-name-specifier. Subclasses may override this function to provide
494 /// alternate behavior.
495 NestedNameSpecifierLoc
496 TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
497 QualType ObjectType = QualType(),
498 NamedDecl *FirstQualifierInScope = nullptr);
499
500 /// Transform the given declaration name.
501 ///
502 /// By default, transforms the types of conversion function, constructor,
503 /// and destructor names and then (if needed) rebuilds the declaration name.
504 /// Identifiers and selectors are returned unmodified. Sublcasses may
505 /// override this function to provide alternate behavior.
506 DeclarationNameInfo
507 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
508
509 /// Transform the given template name.
510 ///
511 /// \param SS The nested-name-specifier that qualifies the template
512 /// name. This nested-name-specifier must already have been transformed.
513 ///
514 /// \param Name The template name to transform.
515 ///
516 /// \param NameLoc The source location of the template name.
517 ///
518 /// \param ObjectType If we're translating a template name within a member
519 /// access expression, this is the type of the object whose member template
520 /// is being referenced.
521 ///
522 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
523 /// also refers to a name within the current (lexical) scope, this is the
524 /// declaration it refers to.
525 ///
526 /// By default, transforms the template name by transforming the declarations
527 /// and nested-name-specifiers that occur within the template name.
528 /// Subclasses may override this function to provide alternate behavior.
529 TemplateName
530 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
531 SourceLocation NameLoc,
532 QualType ObjectType = QualType(),
533 NamedDecl *FirstQualifierInScope = nullptr,
534 bool AllowInjectedClassName = false);
535
536 /// Transform the given template argument.
537 ///
538 /// By default, this operation transforms the type, expression, or
539 /// declaration stored within the template argument and constructs a
540 /// new template argument from the transformed result. Subclasses may
541 /// override this function to provide alternate behavior.
542 ///
543 /// Returns true if there was an error.
544 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
545 TemplateArgumentLoc &Output,
546 bool Uneval = false);
547
548 /// Transform the given set of template arguments.
549 ///
550 /// By default, this operation transforms all of the template arguments
551 /// in the input set using \c TransformTemplateArgument(), and appends
552 /// the transformed arguments to the output list.
553 ///
554 /// Note that this overload of \c TransformTemplateArguments() is merely
555 /// a convenience function. Subclasses that wish to override this behavior
556 /// should override the iterator-based member template version.
557 ///
558 /// \param Inputs The set of template arguments to be transformed.
559 ///
560 /// \param NumInputs The number of template arguments in \p Inputs.
561 ///
562 /// \param Outputs The set of transformed template arguments output by this
563 /// routine.
564 ///
565 /// Returns true if an error occurred.
566 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
567 unsigned NumInputs,
568 TemplateArgumentListInfo &Outputs,
569 bool Uneval = false) {
570 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
571 Uneval);
572 }
573
574 /// Transform the given set of template arguments.
575 ///
576 /// By default, this operation transforms all of the template arguments
577 /// in the input set using \c TransformTemplateArgument(), and appends
578 /// the transformed arguments to the output list.
579 ///
580 /// \param First An iterator to the first template argument.
581 ///
582 /// \param Last An iterator one step past the last template argument.
583 ///
584 /// \param Outputs The set of transformed template arguments output by this
585 /// routine.
586 ///
587 /// Returns true if an error occurred.
588 template<typename InputIterator>
589 bool TransformTemplateArguments(InputIterator First,
590 InputIterator Last,
591 TemplateArgumentListInfo &Outputs,
592 bool Uneval = false);
593
594 /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
595 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
596 TemplateArgumentLoc &ArgLoc);
597
598 /// Fakes up a TypeSourceInfo for a type.
599 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
600 return SemaRef.Context.getTrivialTypeSourceInfo(T,
601 getDerived().getBaseLocation());
602 }
603
604#define ABSTRACT_TYPELOC(CLASS, PARENT)
605#define TYPELOC(CLASS, PARENT) \
606 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
607#include "clang/AST/TypeLocNodes.def"
608
609 template<typename Fn>
610 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
611 FunctionProtoTypeLoc TL,
612 CXXRecordDecl *ThisContext,
613 Qualifiers ThisTypeQuals,
614 Fn TransformExceptionSpec);
615
616 bool TransformExceptionSpec(SourceLocation Loc,
617 FunctionProtoType::ExceptionSpecInfo &ESI,
618 SmallVectorImpl<QualType> &Exceptions,
619 bool &Changed);
620
621 StmtResult TransformSEHHandler(Stmt *Handler);
622
623 QualType
624 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
625 TemplateSpecializationTypeLoc TL,
626 TemplateName Template);
627
628 QualType
629 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
630 DependentTemplateSpecializationTypeLoc TL,
631 TemplateName Template,
632 CXXScopeSpec &SS);
633
634 QualType TransformDependentTemplateSpecializationType(
635 TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
636 NestedNameSpecifierLoc QualifierLoc);
637
638 /// Transforms the parameters of a function type into the
639 /// given vectors.
640 ///
641 /// The result vectors should be kept in sync; null entries in the
642 /// variables vector are acceptable.
643 ///
644 /// Return true on error.
645 bool TransformFunctionTypeParams(
646 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
647 const QualType *ParamTypes,
648 const FunctionProtoType::ExtParameterInfo *ParamInfos,
649 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
650 Sema::ExtParameterInfoBuilder &PInfos);
651
652 /// Transforms a single function-type parameter. Return null
653 /// on error.
654 ///
655 /// \param indexAdjustment - A number to add to the parameter's
656 /// scope index; can be negative
657 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
658 int indexAdjustment,
659 Optional<unsigned> NumExpansions,
660 bool ExpectParameterPack);
661
662 /// Transform the body of a lambda-expression.
663 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
664 /// Alternative implementation of TransformLambdaBody that skips transforming
665 /// the body.
666 StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
667
668 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
669
670 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
671 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
672
673 TemplateParameterList *TransformTemplateParameterList(
674 TemplateParameterList *TPL) {
675 return TPL;
676 }
677
678 ExprResult TransformAddressOfOperand(Expr *E);
679
680 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
681 bool IsAddressOfOperand,
682 TypeSourceInfo **RecoveryTSI);
683
684 ExprResult TransformParenDependentScopeDeclRefExpr(
685 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
686 TypeSourceInfo **RecoveryTSI);
687
688 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
689
690// FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
691// amount of stack usage with clang.
692#define STMT(Node, Parent) \
693 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
694 StmtResult Transform##Node(Node *S);
695#define VALUESTMT(Node, Parent) \
696 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
697 StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
698#define EXPR(Node, Parent) \
699 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
700 ExprResult Transform##Node(Node *E);
701#define ABSTRACT_STMT(Stmt)
702#include "clang/AST/StmtNodes.inc"
703
704#define OPENMP_CLAUSE(Name, Class) \
705 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
706 OMPClause *Transform ## Class(Class *S);
707#include "clang/Basic/OpenMPKinds.def"
708
709 /// Build a new qualified type given its unqualified type and type location.
710 ///
711 /// By default, this routine adds type qualifiers only to types that can
712 /// have qualifiers, and silently suppresses those qualifiers that are not
713 /// permitted. Subclasses may override this routine to provide different
714 /// behavior.
715 QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
716
717 /// Build a new pointer type given its pointee type.
718 ///
719 /// By default, performs semantic analysis when building the pointer type.
720 /// Subclasses may override this routine to provide different behavior.
721 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
722
723 /// Build a new block pointer type given its pointee type.
724 ///
725 /// By default, performs semantic analysis when building the block pointer
726 /// type. Subclasses may override this routine to provide different behavior.
727 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
728
729 /// Build a new reference type given the type it references.
730 ///
731 /// By default, performs semantic analysis when building the
732 /// reference type. Subclasses may override this routine to provide
733 /// different behavior.
734 ///
735 /// \param LValue whether the type was written with an lvalue sigil
736 /// or an rvalue sigil.
737 QualType RebuildReferenceType(QualType ReferentType,
738 bool LValue,
739 SourceLocation Sigil);
740
741 /// Build a new member pointer type given the pointee type and the
742 /// class type it refers into.
743 ///
744 /// By default, performs semantic analysis when building the member pointer
745 /// type. Subclasses may override this routine to provide different behavior.
746 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
747 SourceLocation Sigil);
748
749 QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
750 SourceLocation ProtocolLAngleLoc,
751 ArrayRef<ObjCProtocolDecl *> Protocols,
752 ArrayRef<SourceLocation> ProtocolLocs,
753 SourceLocation ProtocolRAngleLoc);
754
755 /// Build an Objective-C object type.
756 ///
757 /// By default, performs semantic analysis when building the object type.
758 /// Subclasses may override this routine to provide different behavior.
759 QualType RebuildObjCObjectType(QualType BaseType,
760 SourceLocation Loc,
761 SourceLocation TypeArgsLAngleLoc,
762 ArrayRef<TypeSourceInfo *> TypeArgs,
763 SourceLocation TypeArgsRAngleLoc,
764 SourceLocation ProtocolLAngleLoc,
765 ArrayRef<ObjCProtocolDecl *> Protocols,
766 ArrayRef<SourceLocation> ProtocolLocs,
767 SourceLocation ProtocolRAngleLoc);
768
769 /// Build a new Objective-C object pointer type given the pointee type.
770 ///
771 /// By default, directly builds the pointer type, with no additional semantic
772 /// analysis.
773 QualType RebuildObjCObjectPointerType(QualType PointeeType,
774 SourceLocation Star);
775
776 /// Build a new array type given the element type, size
777 /// modifier, size of the array (if known), size expression, and index type
778 /// qualifiers.
779 ///
780 /// By default, performs semantic analysis when building the array type.
781 /// Subclasses may override this routine to provide different behavior.
782 /// Also by default, all of the other Rebuild*Array
783 QualType RebuildArrayType(QualType ElementType,
784 ArrayType::ArraySizeModifier SizeMod,
785 const llvm::APInt *Size,
786 Expr *SizeExpr,
787 unsigned IndexTypeQuals,
788 SourceRange BracketsRange);
789
790 /// Build a new constant array type given the element type, size
791 /// modifier, (known) size of the array, and index type qualifiers.
792 ///
793 /// By default, performs semantic analysis when building the array type.
794 /// Subclasses may override this routine to provide different behavior.
795 QualType RebuildConstantArrayType(QualType ElementType,
796 ArrayType::ArraySizeModifier SizeMod,
797 const llvm::APInt &Size,
798 unsigned IndexTypeQuals,
799 SourceRange BracketsRange);
800
801 /// Build a new incomplete array type given the element type, size
802 /// modifier, and index type qualifiers.
803 ///
804 /// By default, performs semantic analysis when building the array type.
805 /// Subclasses may override this routine to provide different behavior.
806 QualType RebuildIncompleteArrayType(QualType ElementType,
807 ArrayType::ArraySizeModifier SizeMod,
808 unsigned IndexTypeQuals,
809 SourceRange BracketsRange);
810
811 /// Build a new variable-length array type given the element type,
812 /// size modifier, size expression, and index type qualifiers.
813 ///
814 /// By default, performs semantic analysis when building the array type.
815 /// Subclasses may override this routine to provide different behavior.
816 QualType RebuildVariableArrayType(QualType ElementType,
817 ArrayType::ArraySizeModifier SizeMod,
818 Expr *SizeExpr,
819 unsigned IndexTypeQuals,
820 SourceRange BracketsRange);
821
822 /// Build a new dependent-sized array type given the element type,
823 /// size modifier, size expression, and index type qualifiers.
824 ///
825 /// By default, performs semantic analysis when building the array type.
826 /// Subclasses may override this routine to provide different behavior.
827 QualType RebuildDependentSizedArrayType(QualType ElementType,
828 ArrayType::ArraySizeModifier SizeMod,
829 Expr *SizeExpr,
830 unsigned IndexTypeQuals,
831 SourceRange BracketsRange);
832
833 /// Build a new vector type given the element type and
834 /// number of elements.
835 ///
836 /// By default, performs semantic analysis when building the vector type.
837 /// Subclasses may override this routine to provide different behavior.
838 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
839 VectorType::VectorKind VecKind);
840
841 /// Build a new potentially dependently-sized extended vector type
842 /// given the element type and number of elements.
843 ///
844 /// By default, performs semantic analysis when building the vector type.
845 /// Subclasses may override this routine to provide different behavior.
846 QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
847 SourceLocation AttributeLoc,
848 VectorType::VectorKind);
849
850 /// Build a new extended vector type given the element type and
851 /// number of elements.
852 ///
853 /// By default, performs semantic analysis when building the vector type.
854 /// Subclasses may override this routine to provide different behavior.
855 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
856 SourceLocation AttributeLoc);
857
858 /// Build a new potentially dependently-sized extended vector type
859 /// given the element type and number of elements.
860 ///
861 /// By default, performs semantic analysis when building the vector type.
862 /// Subclasses may override this routine to provide different behavior.
863 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
864 Expr *SizeExpr,
865 SourceLocation AttributeLoc);
866
867 /// Build a new DependentAddressSpaceType or return the pointee
868 /// type variable with the correct address space (retrieved from
869 /// AddrSpaceExpr) applied to it. The former will be returned in cases
870 /// where the address space remains dependent.
871 ///
872 /// By default, performs semantic analysis when building the type with address
873 /// space applied. Subclasses may override this routine to provide different
874 /// behavior.
875 QualType RebuildDependentAddressSpaceType(QualType PointeeType,
876 Expr *AddrSpaceExpr,
877 SourceLocation AttributeLoc);
878
879 /// Build a new function type.
880 ///
881 /// By default, performs semantic analysis when building the function type.
882 /// Subclasses may override this routine to provide different behavior.
883 QualType RebuildFunctionProtoType(QualType T,
884 MutableArrayRef<QualType> ParamTypes,
885 const FunctionProtoType::ExtProtoInfo &EPI);
886
887 /// Build a new unprototyped function type.
888 QualType RebuildFunctionNoProtoType(QualType ResultType);
889
890 /// Rebuild an unresolved typename type, given the decl that
891 /// the UnresolvedUsingTypenameDecl was transformed to.
892 QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
893
894 /// Build a new typedef type.
895 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
896 return SemaRef.Context.getTypeDeclType(Typedef);
897 }
898
899 /// Build a new MacroDefined type.
900 QualType RebuildMacroQualifiedType(QualType T,
901 const IdentifierInfo *MacroII) {
902 return SemaRef.Context.getMacroQualifiedType(T, MacroII);
903 }
904
905 /// Build a new class/struct/union type.
906 QualType RebuildRecordType(RecordDecl *Record) {
907 return SemaRef.Context.getTypeDeclType(Record);
908 }
909
910 /// Build a new Enum type.
911 QualType RebuildEnumType(EnumDecl *Enum) {
912 return SemaRef.Context.getTypeDeclType(Enum);
913 }
914
915 /// Build a new typeof(expr) type.
916 ///
917 /// By default, performs semantic analysis when building the typeof type.
918 /// Subclasses may override this routine to provide different behavior.
919 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
920
921 /// Build a new typeof(type) type.
922 ///
923 /// By default, builds a new TypeOfType with the given underlying type.
924 QualType RebuildTypeOfType(QualType Underlying);
925
926 /// Build a new unary transform type.
927 QualType RebuildUnaryTransformType(QualType BaseType,
928 UnaryTransformType::UTTKind UKind,
929 SourceLocation Loc);
930
931 /// Build a new C++11 decltype type.
932 ///
933 /// By default, performs semantic analysis when building the decltype type.
934 /// Subclasses may override this routine to provide different behavior.
935 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
936
937 /// Build a new C++11 auto type.
938 ///
939 /// By default, builds a new AutoType with the given deduced type.
940 QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword) {
941 // Note, IsDependent is always false here: we implicitly convert an 'auto'
942 // which has been deduced to a dependent type into an undeduced 'auto', so
943 // that we'll retry deduction after the transformation.
944 return SemaRef.Context.getAutoType(Deduced, Keyword,
945 /*IsDependent*/ false);
946 }
947
948 /// By default, builds a new DeducedTemplateSpecializationType with the given
949 /// deduced type.
950 QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
951 QualType Deduced) {
952 return SemaRef.Context.getDeducedTemplateSpecializationType(
953 Template, Deduced, /*IsDependent*/ false);
954 }
955
956 /// Build a new template specialization type.
957 ///
958 /// By default, performs semantic analysis when building the template
959 /// specialization type. Subclasses may override this routine to provide
960 /// different behavior.
961 QualType RebuildTemplateSpecializationType(TemplateName Template,
962 SourceLocation TemplateLoc,
963 TemplateArgumentListInfo &Args);
964
965 /// Build a new parenthesized type.
966 ///
967 /// By default, builds a new ParenType type from the inner type.
968 /// Subclasses may override this routine to provide different behavior.
969 QualType RebuildParenType(QualType InnerType) {
970 return SemaRef.BuildParenType(InnerType);
971 }
972
973 /// Build a new qualified name type.
974 ///
975 /// By default, builds a new ElaboratedType type from the keyword,
976 /// the nested-name-specifier and the named type.
977 /// Subclasses may override this routine to provide different behavior.
978 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
979 ElaboratedTypeKeyword Keyword,
980 NestedNameSpecifierLoc QualifierLoc,
981 QualType Named) {
982 return SemaRef.Context.getElaboratedType(Keyword,
983 QualifierLoc.getNestedNameSpecifier(),
984 Named);
985 }
986
987 /// Build a new typename type that refers to a template-id.
988 ///
989 /// By default, builds a new DependentNameType type from the
990 /// nested-name-specifier and the given type. Subclasses may override
991 /// this routine to provide different behavior.
992 QualType RebuildDependentTemplateSpecializationType(
993 ElaboratedTypeKeyword Keyword,
994 NestedNameSpecifierLoc QualifierLoc,
995 SourceLocation TemplateKWLoc,
996 const IdentifierInfo *Name,
997 SourceLocation NameLoc,
998 TemplateArgumentListInfo &Args,
999 bool AllowInjectedClassName) {
1000 // Rebuild the template name.
1001 // TODO: avoid TemplateName abstraction
1002 CXXScopeSpec SS;
1003 SS.Adopt(QualifierLoc);
1004 TemplateName InstName = getDerived().RebuildTemplateName(
1005 SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1006 AllowInjectedClassName);
1007
1008 if (InstName.isNull())
1009 return QualType();
1010
1011 // If it's still dependent, make a dependent specialization.
1012 if (InstName.getAsDependentTemplateName())
1013 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1014 QualifierLoc.getNestedNameSpecifier(),
1015 Name,
1016 Args);
1017
1018 // Otherwise, make an elaborated type wrapping a non-dependent
1019 // specialization.
1020 QualType T =
1021 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1022 if (T.isNull()) return QualType();
1023
1024 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1025 return T;
1026
1027 return SemaRef.Context.getElaboratedType(Keyword,
1028 QualifierLoc.getNestedNameSpecifier(),
1029 T);
1030 }
1031
1032 /// Build a new typename type that refers to an identifier.
1033 ///
1034 /// By default, performs semantic analysis when building the typename type
1035 /// (or elaborated type). Subclasses may override this routine to provide
1036 /// different behavior.
1037 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1038 SourceLocation KeywordLoc,
1039 NestedNameSpecifierLoc QualifierLoc,
1040 const IdentifierInfo *Id,
1041 SourceLocation IdLoc,
1042 bool DeducedTSTContext) {
1043 CXXScopeSpec SS;
1044 SS.Adopt(QualifierLoc);
1045
1046 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1047 // If the name is still dependent, just build a new dependent name type.
1048 if (!SemaRef.computeDeclContext(SS))
1049 return SemaRef.Context.getDependentNameType(Keyword,
1050 QualifierLoc.getNestedNameSpecifier(),
1051 Id);
1052 }
1053
1054 if (Keyword == ETK_None || Keyword == ETK_Typename) {
1055 QualType T = SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1056 *Id, IdLoc);
1057 // If a dependent name resolves to a deduced template specialization type,
1058 // check that we're in one of the syntactic contexts permitting it.
1059 if (!DeducedTSTContext) {
1060 if (auto *Deduced = dyn_cast_or_null<DeducedTemplateSpecializationType>(
1061 T.isNull() ? nullptr : T->getContainedDeducedType())) {
1062 SemaRef.Diag(IdLoc, diag::err_dependent_deduced_tst)
1063 << (int)SemaRef.getTemplateNameKindForDiagnostics(
1064 Deduced->getTemplateName())
1065 << QualType(QualifierLoc.getNestedNameSpecifier()->getAsType(), 0);
1066 if (auto *TD = Deduced->getTemplateName().getAsTemplateDecl())
1067 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
1068 return QualType();
1069 }
1070 }
1071 return T;
1072 }
1073
1074 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1075
1076 // We had a dependent elaborated-type-specifier that has been transformed
1077 // into a non-dependent elaborated-type-specifier. Find the tag we're
1078 // referring to.
1079 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1080 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1081 if (!DC)
1082 return QualType();
1083
1084 if (SemaRef.RequireCompleteDeclContext(SS, DC))
1085 return QualType();
1086
1087 TagDecl *Tag = nullptr;
1088 SemaRef.LookupQualifiedName(Result, DC);
1089 switch (Result.getResultKind()) {
1090 case LookupResult::NotFound:
1091 case LookupResult::NotFoundInCurrentInstantiation:
1092 break;
1093
1094 case LookupResult::Found:
1095 Tag = Result.getAsSingle<TagDecl>();
1096 break;
1097
1098 case LookupResult::FoundOverloaded:
1099 case LookupResult::FoundUnresolvedValue:
1100 llvm_unreachable("Tag lookup cannot find non-tags")::llvm::llvm_unreachable_internal("Tag lookup cannot find non-tags"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 1100)
;
1101
1102 case LookupResult::Ambiguous:
1103 // Let the LookupResult structure handle ambiguities.
1104 return QualType();
1105 }
1106
1107 if (!Tag) {
1108 // Check where the name exists but isn't a tag type and use that to emit
1109 // better diagnostics.
1110 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1111 SemaRef.LookupQualifiedName(Result, DC);
1112 switch (Result.getResultKind()) {
1113 case LookupResult::Found:
1114 case LookupResult::FoundOverloaded:
1115 case LookupResult::FoundUnresolvedValue: {
1116 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1117 Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1118 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1119 << NTK << Kind;
1120 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1121 break;
1122 }
1123 default:
1124 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1125 << Kind << Id << DC << QualifierLoc.getSourceRange();
1126 break;
1127 }
1128 return QualType();
1129 }
1130
1131 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1132 IdLoc, Id)) {
1133 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1134 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1135 return QualType();
1136 }
1137
1138 // Build the elaborated-type-specifier type.
1139 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1140 return SemaRef.Context.getElaboratedType(Keyword,
1141 QualifierLoc.getNestedNameSpecifier(),
1142 T);
1143 }
1144
1145 /// Build a new pack expansion type.
1146 ///
1147 /// By default, builds a new PackExpansionType type from the given pattern.
1148 /// Subclasses may override this routine to provide different behavior.
1149 QualType RebuildPackExpansionType(QualType Pattern,
1150 SourceRange PatternRange,
1151 SourceLocation EllipsisLoc,
1152 Optional<unsigned> NumExpansions) {
1153 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1154 NumExpansions);
1155 }
1156
1157 /// Build a new atomic type given its value type.
1158 ///
1159 /// By default, performs semantic analysis when building the atomic type.
1160 /// Subclasses may override this routine to provide different behavior.
1161 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1162
1163 /// Build a new pipe type given its value type.
1164 QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1165 bool isReadPipe);
1166
1167 /// Build a new template name given a nested name specifier, a flag
1168 /// indicating whether the "template" keyword was provided, and the template
1169 /// that the template name refers to.
1170 ///
1171 /// By default, builds the new template name directly. Subclasses may override
1172 /// this routine to provide different behavior.
1173 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1174 bool TemplateKW,
1175 TemplateDecl *Template);
1176
1177 /// Build a new template name given a nested name specifier and the
1178 /// name that is referred to as a template.
1179 ///
1180 /// By default, performs semantic analysis to determine whether the name can
1181 /// be resolved to a specific template, then builds the appropriate kind of
1182 /// template name. Subclasses may override this routine to provide different
1183 /// behavior.
1184 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1185 SourceLocation TemplateKWLoc,
1186 const IdentifierInfo &Name,
1187 SourceLocation NameLoc, QualType ObjectType,
1188 NamedDecl *FirstQualifierInScope,
1189 bool AllowInjectedClassName);
1190
1191 /// Build a new template name given a nested name specifier and the
1192 /// overloaded operator name that is referred to as a template.
1193 ///
1194 /// By default, performs semantic analysis to determine whether the name can
1195 /// be resolved to a specific template, then builds the appropriate kind of
1196 /// template name. Subclasses may override this routine to provide different
1197 /// behavior.
1198 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1199 SourceLocation TemplateKWLoc,
1200 OverloadedOperatorKind Operator,
1201 SourceLocation NameLoc, QualType ObjectType,
1202 bool AllowInjectedClassName);
1203
1204 /// Build a new template name given a template template parameter pack
1205 /// and the
1206 ///
1207 /// By default, performs semantic analysis to determine whether the name can
1208 /// be resolved to a specific template, then builds the appropriate kind of
1209 /// template name. Subclasses may override this routine to provide different
1210 /// behavior.
1211 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1212 const TemplateArgument &ArgPack) {
1213 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1214 }
1215
1216 /// Build a new compound statement.
1217 ///
1218 /// By default, performs semantic analysis to build the new statement.
1219 /// Subclasses may override this routine to provide different behavior.
1220 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1221 MultiStmtArg Statements,
1222 SourceLocation RBraceLoc,
1223 bool IsStmtExpr) {
1224 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1225 IsStmtExpr);
1226 }
1227
1228 /// Build a new case statement.
1229 ///
1230 /// By default, performs semantic analysis to build the new statement.
1231 /// Subclasses may override this routine to provide different behavior.
1232 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1233 Expr *LHS,
1234 SourceLocation EllipsisLoc,
1235 Expr *RHS,
1236 SourceLocation ColonLoc) {
1237 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1238 ColonLoc);
1239 }
1240
1241 /// Attach the body to a new case statement.
1242 ///
1243 /// By default, performs semantic analysis to build the new statement.
1244 /// Subclasses may override this routine to provide different behavior.
1245 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1246 getSema().ActOnCaseStmtBody(S, Body);
1247 return S;
1248 }
1249
1250 /// Build a new default statement.
1251 ///
1252 /// By default, performs semantic analysis to build the new statement.
1253 /// Subclasses may override this routine to provide different behavior.
1254 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1255 SourceLocation ColonLoc,
1256 Stmt *SubStmt) {
1257 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1258 /*CurScope=*/nullptr);
1259 }
1260
1261 /// Build a new label statement.
1262 ///
1263 /// By default, performs semantic analysis to build the new statement.
1264 /// Subclasses may override this routine to provide different behavior.
1265 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1266 SourceLocation ColonLoc, Stmt *SubStmt) {
1267 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1268 }
1269
1270 /// Build a new label statement.
1271 ///
1272 /// By default, performs semantic analysis to build the new statement.
1273 /// Subclasses may override this routine to provide different behavior.
1274 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1275 ArrayRef<const Attr*> Attrs,
1276 Stmt *SubStmt) {
1277 return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1278 }
1279
1280 /// Build a new "if" statement.
1281 ///
1282 /// By default, performs semantic analysis to build the new statement.
1283 /// Subclasses may override this routine to provide different behavior.
1284 StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1285 Sema::ConditionResult Cond, Stmt *Init, Stmt *Then,
1286 SourceLocation ElseLoc, Stmt *Else) {
1287 return getSema().ActOnIfStmt(IfLoc, IsConstexpr, Init, Cond, Then,
1288 ElseLoc, Else);
1289 }
1290
1291 /// Start building a new switch statement.
1292 ///
1293 /// By default, performs semantic analysis to build the new statement.
1294 /// Subclasses may override this routine to provide different behavior.
1295 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc, Stmt *Init,
1296 Sema::ConditionResult Cond) {
1297 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Init, Cond);
1298 }
1299
1300 /// Attach the body to the switch statement.
1301 ///
1302 /// By default, performs semantic analysis to build the new statement.
1303 /// Subclasses may override this routine to provide different behavior.
1304 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1305 Stmt *Switch, Stmt *Body) {
1306 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1307 }
1308
1309 /// Build a new while statement.
1310 ///
1311 /// By default, performs semantic analysis to build the new statement.
1312 /// Subclasses may override this routine to provide different behavior.
1313 StmtResult RebuildWhileStmt(SourceLocation WhileLoc,
1314 Sema::ConditionResult Cond, Stmt *Body) {
1315 return getSema().ActOnWhileStmt(WhileLoc, Cond, Body);
1316 }
1317
1318 /// Build a new do-while statement.
1319 ///
1320 /// By default, performs semantic analysis to build the new statement.
1321 /// Subclasses may override this routine to provide different behavior.
1322 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1323 SourceLocation WhileLoc, SourceLocation LParenLoc,
1324 Expr *Cond, SourceLocation RParenLoc) {
1325 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1326 Cond, RParenLoc);
1327 }
1328
1329 /// Build a new for statement.
1330 ///
1331 /// By default, performs semantic analysis to build the new statement.
1332 /// Subclasses may override this routine to provide different behavior.
1333 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1334 Stmt *Init, Sema::ConditionResult Cond,
1335 Sema::FullExprArg Inc, SourceLocation RParenLoc,
1336 Stmt *Body) {
1337 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1338 Inc, RParenLoc, Body);
1339 }
1340
1341 /// Build a new goto statement.
1342 ///
1343 /// By default, performs semantic analysis to build the new statement.
1344 /// Subclasses may override this routine to provide different behavior.
1345 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1346 LabelDecl *Label) {
1347 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1348 }
1349
1350 /// Build a new indirect goto statement.
1351 ///
1352 /// By default, performs semantic analysis to build the new statement.
1353 /// Subclasses may override this routine to provide different behavior.
1354 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1355 SourceLocation StarLoc,
1356 Expr *Target) {
1357 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1358 }
1359
1360 /// Build a new return statement.
1361 ///
1362 /// By default, performs semantic analysis to build the new statement.
1363 /// Subclasses may override this routine to provide different behavior.
1364 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1365 return getSema().BuildReturnStmt(ReturnLoc, Result);
1366 }
1367
1368 /// Build a new declaration statement.
1369 ///
1370 /// By default, performs semantic analysis to build the new statement.
1371 /// Subclasses may override this routine to provide different behavior.
1372 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1373 SourceLocation StartLoc, SourceLocation EndLoc) {
1374 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1375 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1376 }
1377
1378 /// Build a new inline asm statement.
1379 ///
1380 /// By default, performs semantic analysis to build the new statement.
1381 /// Subclasses may override this routine to provide different behavior.
1382 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1383 bool IsVolatile, unsigned NumOutputs,
1384 unsigned NumInputs, IdentifierInfo **Names,
1385 MultiExprArg Constraints, MultiExprArg Exprs,
1386 Expr *AsmString, MultiExprArg Clobbers,
1387 unsigned NumLabels,
1388 SourceLocation RParenLoc) {
1389 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1390 NumInputs, Names, Constraints, Exprs,
1391 AsmString, Clobbers, NumLabels, RParenLoc);
1392 }
1393
1394 /// Build a new MS style inline asm statement.
1395 ///
1396 /// By default, performs semantic analysis to build the new statement.
1397 /// Subclasses may override this routine to provide different behavior.
1398 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1399 ArrayRef<Token> AsmToks,
1400 StringRef AsmString,
1401 unsigned NumOutputs, unsigned NumInputs,
1402 ArrayRef<StringRef> Constraints,
1403 ArrayRef<StringRef> Clobbers,
1404 ArrayRef<Expr*> Exprs,
1405 SourceLocation EndLoc) {
1406 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1407 NumOutputs, NumInputs,
1408 Constraints, Clobbers, Exprs, EndLoc);
1409 }
1410
1411 /// Build a new co_return statement.
1412 ///
1413 /// By default, performs semantic analysis to build the new statement.
1414 /// Subclasses may override this routine to provide different behavior.
1415 StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1416 bool IsImplicit) {
1417 return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1418 }
1419
1420 /// Build a new co_await expression.
1421 ///
1422 /// By default, performs semantic analysis to build the new expression.
1423 /// Subclasses may override this routine to provide different behavior.
1424 ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1425 bool IsImplicit) {
1426 return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1427 }
1428
1429 /// Build a new co_await expression.
1430 ///
1431 /// By default, performs semantic analysis to build the new expression.
1432 /// Subclasses may override this routine to provide different behavior.
1433 ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1434 Expr *Result,
1435 UnresolvedLookupExpr *Lookup) {
1436 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1437 }
1438
1439 /// Build a new co_yield expression.
1440 ///
1441 /// By default, performs semantic analysis to build the new expression.
1442 /// Subclasses may override this routine to provide different behavior.
1443 ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1444 return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1445 }
1446
1447 StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1448 return getSema().BuildCoroutineBodyStmt(Args);
1449 }
1450
1451 /// Build a new Objective-C \@try statement.
1452 ///
1453 /// By default, performs semantic analysis to build the new statement.
1454 /// Subclasses may override this routine to provide different behavior.
1455 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1456 Stmt *TryBody,
1457 MultiStmtArg CatchStmts,
1458 Stmt *Finally) {
1459 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1460 Finally);
1461 }
1462
1463 /// Rebuild an Objective-C exception declaration.
1464 ///
1465 /// By default, performs semantic analysis to build the new declaration.
1466 /// Subclasses may override this routine to provide different behavior.
1467 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1468 TypeSourceInfo *TInfo, QualType T) {
1469 return getSema().BuildObjCExceptionDecl(TInfo, T,
1470 ExceptionDecl->getInnerLocStart(),
1471 ExceptionDecl->getLocation(),
1472 ExceptionDecl->getIdentifier());
1473 }
1474
1475 /// Build a new Objective-C \@catch statement.
1476 ///
1477 /// By default, performs semantic analysis to build the new statement.
1478 /// Subclasses may override this routine to provide different behavior.
1479 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1480 SourceLocation RParenLoc,
1481 VarDecl *Var,
1482 Stmt *Body) {
1483 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1484 Var, Body);
1485 }
1486
1487 /// Build a new Objective-C \@finally statement.
1488 ///
1489 /// By default, performs semantic analysis to build the new statement.
1490 /// Subclasses may override this routine to provide different behavior.
1491 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1492 Stmt *Body) {
1493 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1494 }
1495
1496 /// Build a new Objective-C \@throw statement.
1497 ///
1498 /// By default, performs semantic analysis to build the new statement.
1499 /// Subclasses may override this routine to provide different behavior.
1500 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1501 Expr *Operand) {
1502 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1503 }
1504
1505 /// Build a new OpenMP executable directive.
1506 ///
1507 /// By default, performs semantic analysis to build the new statement.
1508 /// Subclasses may override this routine to provide different behavior.
1509 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1510 DeclarationNameInfo DirName,
1511 OpenMPDirectiveKind CancelRegion,
1512 ArrayRef<OMPClause *> Clauses,
1513 Stmt *AStmt, SourceLocation StartLoc,
1514 SourceLocation EndLoc) {
1515 return getSema().ActOnOpenMPExecutableDirective(
1516 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1517 }
1518
1519 /// Build a new OpenMP 'if' clause.
1520 ///
1521 /// By default, performs semantic analysis to build the new OpenMP clause.
1522 /// Subclasses may override this routine to provide different behavior.
1523 OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1524 Expr *Condition, SourceLocation StartLoc,
1525 SourceLocation LParenLoc,
1526 SourceLocation NameModifierLoc,
1527 SourceLocation ColonLoc,
1528 SourceLocation EndLoc) {
1529 return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1530 LParenLoc, NameModifierLoc, ColonLoc,
1531 EndLoc);
1532 }
1533
1534 /// Build a new OpenMP 'final' clause.
1535 ///
1536 /// By default, performs semantic analysis to build the new OpenMP clause.
1537 /// Subclasses may override this routine to provide different behavior.
1538 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1539 SourceLocation LParenLoc,
1540 SourceLocation EndLoc) {
1541 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1542 EndLoc);
1543 }
1544
1545 /// Build a new OpenMP 'num_threads' clause.
1546 ///
1547 /// By default, performs semantic analysis to build the new OpenMP clause.
1548 /// Subclasses may override this routine to provide different behavior.
1549 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1550 SourceLocation StartLoc,
1551 SourceLocation LParenLoc,
1552 SourceLocation EndLoc) {
1553 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1554 LParenLoc, EndLoc);
1555 }
1556
1557 /// Build a new OpenMP 'safelen' clause.
1558 ///
1559 /// By default, performs semantic analysis to build the new OpenMP clause.
1560 /// Subclasses may override this routine to provide different behavior.
1561 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1562 SourceLocation LParenLoc,
1563 SourceLocation EndLoc) {
1564 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1565 }
1566
1567 /// Build a new OpenMP 'simdlen' clause.
1568 ///
1569 /// By default, performs semantic analysis to build the new OpenMP clause.
1570 /// Subclasses may override this routine to provide different behavior.
1571 OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1572 SourceLocation LParenLoc,
1573 SourceLocation EndLoc) {
1574 return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1575 }
1576
1577 /// Build a new OpenMP 'allocator' clause.
1578 ///
1579 /// By default, performs semantic analysis to build the new OpenMP clause.
1580 /// Subclasses may override this routine to provide different behavior.
1581 OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1582 SourceLocation LParenLoc,
1583 SourceLocation EndLoc) {
1584 return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1585 }
1586
1587 /// Build a new OpenMP 'collapse' clause.
1588 ///
1589 /// By default, performs semantic analysis to build the new OpenMP clause.
1590 /// Subclasses may override this routine to provide different behavior.
1591 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1592 SourceLocation LParenLoc,
1593 SourceLocation EndLoc) {
1594 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1595 EndLoc);
1596 }
1597
1598 /// Build a new OpenMP 'default' clause.
1599 ///
1600 /// By default, performs semantic analysis to build the new OpenMP clause.
1601 /// Subclasses may override this routine to provide different behavior.
1602 OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1603 SourceLocation KindKwLoc,
1604 SourceLocation StartLoc,
1605 SourceLocation LParenLoc,
1606 SourceLocation EndLoc) {
1607 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1608 StartLoc, LParenLoc, EndLoc);
1609 }
1610
1611 /// Build a new OpenMP 'proc_bind' clause.
1612 ///
1613 /// By default, performs semantic analysis to build the new OpenMP clause.
1614 /// Subclasses may override this routine to provide different behavior.
1615 OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
1616 SourceLocation KindKwLoc,
1617 SourceLocation StartLoc,
1618 SourceLocation LParenLoc,
1619 SourceLocation EndLoc) {
1620 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1621 StartLoc, LParenLoc, EndLoc);
1622 }
1623
1624 /// Build a new OpenMP 'schedule' clause.
1625 ///
1626 /// By default, performs semantic analysis to build the new OpenMP clause.
1627 /// Subclasses may override this routine to provide different behavior.
1628 OMPClause *RebuildOMPScheduleClause(
1629 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1630 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1631 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1632 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1633 return getSema().ActOnOpenMPScheduleClause(
1634 M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1635 CommaLoc, EndLoc);
1636 }
1637
1638 /// Build a new OpenMP 'ordered' clause.
1639 ///
1640 /// By default, performs semantic analysis to build the new OpenMP clause.
1641 /// Subclasses may override this routine to provide different behavior.
1642 OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1643 SourceLocation EndLoc,
1644 SourceLocation LParenLoc, Expr *Num) {
1645 return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1646 }
1647
1648 /// Build a new OpenMP 'private' clause.
1649 ///
1650 /// By default, performs semantic analysis to build the new OpenMP clause.
1651 /// Subclasses may override this routine to provide different behavior.
1652 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1653 SourceLocation StartLoc,
1654 SourceLocation LParenLoc,
1655 SourceLocation EndLoc) {
1656 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1657 EndLoc);
1658 }
1659
1660 /// Build a new OpenMP 'firstprivate' clause.
1661 ///
1662 /// By default, performs semantic analysis to build the new OpenMP clause.
1663 /// Subclasses may override this routine to provide different behavior.
1664 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1665 SourceLocation StartLoc,
1666 SourceLocation LParenLoc,
1667 SourceLocation EndLoc) {
1668 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1669 EndLoc);
1670 }
1671
1672 /// Build a new OpenMP 'lastprivate' clause.
1673 ///
1674 /// By default, performs semantic analysis to build the new OpenMP clause.
1675 /// Subclasses may override this routine to provide different behavior.
1676 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1677 SourceLocation StartLoc,
1678 SourceLocation LParenLoc,
1679 SourceLocation EndLoc) {
1680 return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
1681 EndLoc);
1682 }
1683
1684 /// Build a new OpenMP 'shared' clause.
1685 ///
1686 /// By default, performs semantic analysis to build the new OpenMP clause.
1687 /// Subclasses may override this routine to provide different behavior.
1688 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1689 SourceLocation StartLoc,
1690 SourceLocation LParenLoc,
1691 SourceLocation EndLoc) {
1692 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1693 EndLoc);
1694 }
1695
1696 /// Build a new OpenMP 'reduction' clause.
1697 ///
1698 /// By default, performs semantic analysis to build the new statement.
1699 /// Subclasses may override this routine to provide different behavior.
1700 OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1701 SourceLocation StartLoc,
1702 SourceLocation LParenLoc,
1703 SourceLocation ColonLoc,
1704 SourceLocation EndLoc,
1705 CXXScopeSpec &ReductionIdScopeSpec,
1706 const DeclarationNameInfo &ReductionId,
1707 ArrayRef<Expr *> UnresolvedReductions) {
1708 return getSema().ActOnOpenMPReductionClause(
1709 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1710 ReductionId, UnresolvedReductions);
1711 }
1712
1713 /// Build a new OpenMP 'task_reduction' clause.
1714 ///
1715 /// By default, performs semantic analysis to build the new statement.
1716 /// Subclasses may override this routine to provide different behavior.
1717 OMPClause *RebuildOMPTaskReductionClause(
1718 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1719 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1720 CXXScopeSpec &ReductionIdScopeSpec,
1721 const DeclarationNameInfo &ReductionId,
1722 ArrayRef<Expr *> UnresolvedReductions) {
1723 return getSema().ActOnOpenMPTaskReductionClause(
1724 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1725 ReductionId, UnresolvedReductions);
1726 }
1727
1728 /// Build a new OpenMP 'in_reduction' clause.
1729 ///
1730 /// By default, performs semantic analysis to build the new statement.
1731 /// Subclasses may override this routine to provide different behavior.
1732 OMPClause *
1733 RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1734 SourceLocation LParenLoc, SourceLocation ColonLoc,
1735 SourceLocation EndLoc,
1736 CXXScopeSpec &ReductionIdScopeSpec,
1737 const DeclarationNameInfo &ReductionId,
1738 ArrayRef<Expr *> UnresolvedReductions) {
1739 return getSema().ActOnOpenMPInReductionClause(
1740 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1741 ReductionId, UnresolvedReductions);
1742 }
1743
1744 /// Build a new OpenMP 'linear' clause.
1745 ///
1746 /// By default, performs semantic analysis to build the new OpenMP clause.
1747 /// Subclasses may override this routine to provide different behavior.
1748 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1749 SourceLocation StartLoc,
1750 SourceLocation LParenLoc,
1751 OpenMPLinearClauseKind Modifier,
1752 SourceLocation ModifierLoc,
1753 SourceLocation ColonLoc,
1754 SourceLocation EndLoc) {
1755 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1756 Modifier, ModifierLoc, ColonLoc,
1757 EndLoc);
1758 }
1759
1760 /// Build a new OpenMP 'aligned' clause.
1761 ///
1762 /// By default, performs semantic analysis to build the new OpenMP clause.
1763 /// Subclasses may override this routine to provide different behavior.
1764 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1765 SourceLocation StartLoc,
1766 SourceLocation LParenLoc,
1767 SourceLocation ColonLoc,
1768 SourceLocation EndLoc) {
1769 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1770 LParenLoc, ColonLoc, EndLoc);
1771 }
1772
1773 /// Build a new OpenMP 'copyin' clause.
1774 ///
1775 /// By default, performs semantic analysis to build the new OpenMP clause.
1776 /// Subclasses may override this routine to provide different behavior.
1777 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1778 SourceLocation StartLoc,
1779 SourceLocation LParenLoc,
1780 SourceLocation EndLoc) {
1781 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1782 EndLoc);
1783 }
1784
1785 /// Build a new OpenMP 'copyprivate' clause.
1786 ///
1787 /// By default, performs semantic analysis to build the new OpenMP clause.
1788 /// Subclasses may override this routine to provide different behavior.
1789 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1790 SourceLocation StartLoc,
1791 SourceLocation LParenLoc,
1792 SourceLocation EndLoc) {
1793 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1794 EndLoc);
1795 }
1796
1797 /// Build a new OpenMP 'flush' pseudo clause.
1798 ///
1799 /// By default, performs semantic analysis to build the new OpenMP clause.
1800 /// Subclasses may override this routine to provide different behavior.
1801 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1802 SourceLocation StartLoc,
1803 SourceLocation LParenLoc,
1804 SourceLocation EndLoc) {
1805 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1806 EndLoc);
1807 }
1808
1809 /// Build a new OpenMP 'depend' pseudo clause.
1810 ///
1811 /// By default, performs semantic analysis to build the new OpenMP clause.
1812 /// Subclasses may override this routine to provide different behavior.
1813 OMPClause *
1814 RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
1815 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1816 SourceLocation StartLoc, SourceLocation LParenLoc,
1817 SourceLocation EndLoc) {
1818 return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
1819 StartLoc, LParenLoc, EndLoc);
1820 }
1821
1822 /// Build a new OpenMP 'device' clause.
1823 ///
1824 /// By default, performs semantic analysis to build the new statement.
1825 /// Subclasses may override this routine to provide different behavior.
1826 OMPClause *RebuildOMPDeviceClause(Expr *Device, SourceLocation StartLoc,
1827 SourceLocation LParenLoc,
1828 SourceLocation EndLoc) {
1829 return getSema().ActOnOpenMPDeviceClause(Device, StartLoc, LParenLoc,
1830 EndLoc);
1831 }
1832
1833 /// Build a new OpenMP 'map' clause.
1834 ///
1835 /// By default, performs semantic analysis to build the new OpenMP clause.
1836 /// Subclasses may override this routine to provide different behavior.
1837 OMPClause *RebuildOMPMapClause(
1838 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1839 ArrayRef<SourceLocation> MapTypeModifiersLoc,
1840 CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1841 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1842 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1843 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1844 return getSema().ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
1845 MapperIdScopeSpec, MapperId, MapType,
1846 IsMapTypeImplicit, MapLoc, ColonLoc,
1847 VarList, Locs, UnresolvedMappers);
1848 }
1849
1850 /// Build a new OpenMP 'allocate' clause.
1851 ///
1852 /// By default, performs semantic analysis to build the new OpenMP clause.
1853 /// Subclasses may override this routine to provide different behavior.
1854 OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1855 SourceLocation StartLoc,
1856 SourceLocation LParenLoc,
1857 SourceLocation ColonLoc,
1858 SourceLocation EndLoc) {
1859 return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1860 LParenLoc, ColonLoc, EndLoc);
1861 }
1862
1863 /// Build a new OpenMP 'num_teams' clause.
1864 ///
1865 /// By default, performs semantic analysis to build the new statement.
1866 /// Subclasses may override this routine to provide different behavior.
1867 OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1868 SourceLocation LParenLoc,
1869 SourceLocation EndLoc) {
1870 return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1871 EndLoc);
1872 }
1873
1874 /// Build a new OpenMP 'thread_limit' clause.
1875 ///
1876 /// By default, performs semantic analysis to build the new statement.
1877 /// Subclasses may override this routine to provide different behavior.
1878 OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1879 SourceLocation StartLoc,
1880 SourceLocation LParenLoc,
1881 SourceLocation EndLoc) {
1882 return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1883 LParenLoc, EndLoc);
1884 }
1885
1886 /// Build a new OpenMP 'priority' clause.
1887 ///
1888 /// By default, performs semantic analysis to build the new statement.
1889 /// Subclasses may override this routine to provide different behavior.
1890 OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1891 SourceLocation LParenLoc,
1892 SourceLocation EndLoc) {
1893 return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1894 EndLoc);
1895 }
1896
1897 /// Build a new OpenMP 'grainsize' clause.
1898 ///
1899 /// By default, performs semantic analysis to build the new statement.
1900 /// Subclasses may override this routine to provide different behavior.
1901 OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1902 SourceLocation LParenLoc,
1903 SourceLocation EndLoc) {
1904 return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1905 EndLoc);
1906 }
1907
1908 /// Build a new OpenMP 'num_tasks' clause.
1909 ///
1910 /// By default, performs semantic analysis to build the new statement.
1911 /// Subclasses may override this routine to provide different behavior.
1912 OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1913 SourceLocation LParenLoc,
1914 SourceLocation EndLoc) {
1915 return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1916 EndLoc);
1917 }
1918
1919 /// Build a new OpenMP 'hint' clause.
1920 ///
1921 /// By default, performs semantic analysis to build the new statement.
1922 /// Subclasses may override this routine to provide different behavior.
1923 OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1924 SourceLocation LParenLoc,
1925 SourceLocation EndLoc) {
1926 return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1927 }
1928
1929 /// Build a new OpenMP 'dist_schedule' clause.
1930 ///
1931 /// By default, performs semantic analysis to build the new OpenMP clause.
1932 /// Subclasses may override this routine to provide different behavior.
1933 OMPClause *
1934 RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
1935 Expr *ChunkSize, SourceLocation StartLoc,
1936 SourceLocation LParenLoc, SourceLocation KindLoc,
1937 SourceLocation CommaLoc, SourceLocation EndLoc) {
1938 return getSema().ActOnOpenMPDistScheduleClause(
1939 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1940 }
1941
1942 /// Build a new OpenMP 'to' clause.
1943 ///
1944 /// By default, performs semantic analysis to build the new statement.
1945 /// Subclasses may override this routine to provide different behavior.
1946 OMPClause *RebuildOMPToClause(ArrayRef<Expr *> VarList,
1947 CXXScopeSpec &MapperIdScopeSpec,
1948 DeclarationNameInfo &MapperId,
1949 const OMPVarListLocTy &Locs,
1950 ArrayRef<Expr *> UnresolvedMappers) {
1951 return getSema().ActOnOpenMPToClause(VarList, MapperIdScopeSpec, MapperId,
1952 Locs, UnresolvedMappers);
1953 }
1954
1955 /// Build a new OpenMP 'from' clause.
1956 ///
1957 /// By default, performs semantic analysis to build the new statement.
1958 /// Subclasses may override this routine to provide different behavior.
1959 OMPClause *RebuildOMPFromClause(ArrayRef<Expr *> VarList,
1960 CXXScopeSpec &MapperIdScopeSpec,
1961 DeclarationNameInfo &MapperId,
1962 const OMPVarListLocTy &Locs,
1963 ArrayRef<Expr *> UnresolvedMappers) {
1964 return getSema().ActOnOpenMPFromClause(VarList, MapperIdScopeSpec, MapperId,
1965 Locs, UnresolvedMappers);
1966 }
1967
1968 /// Build a new OpenMP 'use_device_ptr' clause.
1969 ///
1970 /// By default, performs semantic analysis to build the new OpenMP clause.
1971 /// Subclasses may override this routine to provide different behavior.
1972 OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
1973 const OMPVarListLocTy &Locs) {
1974 return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
1975 }
1976
1977 /// Build a new OpenMP 'is_device_ptr' clause.
1978 ///
1979 /// By default, performs semantic analysis to build the new OpenMP clause.
1980 /// Subclasses may override this routine to provide different behavior.
1981 OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
1982 const OMPVarListLocTy &Locs) {
1983 return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
1984 }
1985
1986 /// Rebuild the operand to an Objective-C \@synchronized statement.
1987 ///
1988 /// By default, performs semantic analysis to build the new statement.
1989 /// Subclasses may override this routine to provide different behavior.
1990 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
1991 Expr *object) {
1992 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
1993 }
1994
1995 /// Build a new Objective-C \@synchronized statement.
1996 ///
1997 /// By default, performs semantic analysis to build the new statement.
1998 /// Subclasses may override this routine to provide different behavior.
1999 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2000 Expr *Object, Stmt *Body) {
2001 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2002 }
2003
2004 /// Build a new Objective-C \@autoreleasepool statement.
2005 ///
2006 /// By default, performs semantic analysis to build the new statement.
2007 /// Subclasses may override this routine to provide different behavior.
2008 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2009 Stmt *Body) {
2010 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2011 }
2012
2013 /// Build a new Objective-C fast enumeration statement.
2014 ///
2015 /// By default, performs semantic analysis to build the new statement.
2016 /// Subclasses may override this routine to provide different behavior.
2017 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2018 Stmt *Element,
2019 Expr *Collection,
2020 SourceLocation RParenLoc,
2021 Stmt *Body) {
2022 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2023 Element,
2024 Collection,
2025 RParenLoc);
2026 if (ForEachStmt.isInvalid())
2027 return StmtError();
2028
2029 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2030 }
2031
2032 /// Build a new C++ exception declaration.
2033 ///
2034 /// By default, performs semantic analysis to build the new decaration.
2035 /// Subclasses may override this routine to provide different behavior.
2036 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2037 TypeSourceInfo *Declarator,
2038 SourceLocation StartLoc,
2039 SourceLocation IdLoc,
2040 IdentifierInfo *Id) {
2041 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2042 StartLoc, IdLoc, Id);
2043 if (Var)
2044 getSema().CurContext->addDecl(Var);
2045 return Var;
2046 }
2047
2048 /// Build a new C++ catch statement.
2049 ///
2050 /// By default, performs semantic analysis to build the new statement.
2051 /// Subclasses may override this routine to provide different behavior.
2052 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2053 VarDecl *ExceptionDecl,
2054 Stmt *Handler) {
2055 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2056 Handler));
2057 }
2058
2059 /// Build a new C++ try statement.
2060 ///
2061 /// By default, performs semantic analysis to build the new statement.
2062 /// Subclasses may override this routine to provide different behavior.
2063 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2064 ArrayRef<Stmt *> Handlers) {
2065 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2066 }
2067
2068 /// Build a new C++0x range-based for statement.
2069 ///
2070 /// By default, performs semantic analysis to build the new statement.
2071 /// Subclasses may override this routine to provide different behavior.
2072 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2073 SourceLocation CoawaitLoc, Stmt *Init,
2074 SourceLocation ColonLoc, Stmt *Range,
2075 Stmt *Begin, Stmt *End, Expr *Cond,
2076 Expr *Inc, Stmt *LoopVar,
2077 SourceLocation RParenLoc) {
2078 // If we've just learned that the range is actually an Objective-C
2079 // collection, treat this as an Objective-C fast enumeration loop.
2080 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2081 if (RangeStmt->isSingleDecl()) {
2082 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2083 if (RangeVar->isInvalidDecl())
2084 return StmtError();
2085
2086 Expr *RangeExpr = RangeVar->getInit();
2087 if (!RangeExpr->isTypeDependent() &&
2088 RangeExpr->getType()->isObjCObjectPointerType()) {
2089 // FIXME: Support init-statements in Objective-C++20 ranged for
2090 // statement.
2091 if (Init) {
2092 return SemaRef.Diag(Init->getBeginLoc(),
2093 diag::err_objc_for_range_init_stmt)
2094 << Init->getSourceRange();
2095 }
2096 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2097 RangeExpr, RParenLoc);
2098 }
2099 }
2100 }
2101 }
2102
2103 return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2104 Range, Begin, End, Cond, Inc, LoopVar,
2105 RParenLoc, Sema::BFRK_Rebuild);
2106 }
2107
2108 /// Build a new C++0x range-based for statement.
2109 ///
2110 /// By default, performs semantic analysis to build the new statement.
2111 /// Subclasses may override this routine to provide different behavior.
2112 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2113 bool IsIfExists,
2114 NestedNameSpecifierLoc QualifierLoc,
2115 DeclarationNameInfo NameInfo,
2116 Stmt *Nested) {
2117 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2118 QualifierLoc, NameInfo, Nested);
2119 }
2120
2121 /// Attach body to a C++0x range-based for statement.
2122 ///
2123 /// By default, performs semantic analysis to finish the new statement.
2124 /// Subclasses may override this routine to provide different behavior.
2125 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2126 return getSema().FinishCXXForRangeStmt(ForRange, Body);
2127 }
2128
2129 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2130 Stmt *TryBlock, Stmt *Handler) {
2131 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2132 }
2133
2134 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2135 Stmt *Block) {
2136 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2137 }
2138
2139 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2140 return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2141 }
2142
2143 /// Build a new predefined expression.
2144 ///
2145 /// By default, performs semantic analysis to build the new expression.
2146 /// Subclasses may override this routine to provide different behavior.
2147 ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2148 PredefinedExpr::IdentKind IK) {
2149 return getSema().BuildPredefinedExpr(Loc, IK);
2150 }
2151
2152 /// Build a new expression that references a declaration.
2153 ///
2154 /// By default, performs semantic analysis to build the new expression.
2155 /// Subclasses may override this routine to provide different behavior.
2156 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2157 LookupResult &R,
2158 bool RequiresADL) {
2159 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2160 }
2161
2162
2163 /// Build a new expression that references a declaration.
2164 ///
2165 /// By default, performs semantic analysis to build the new expression.
2166 /// Subclasses may override this routine to provide different behavior.
2167 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2168 ValueDecl *VD,
2169 const DeclarationNameInfo &NameInfo,
2170 NamedDecl *Found,
2171 TemplateArgumentListInfo *TemplateArgs) {
2172 CXXScopeSpec SS;
2173 SS.Adopt(QualifierLoc);
2174 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2175 TemplateArgs);
2176 }
2177
2178 /// Build a new expression in parentheses.
2179 ///
2180 /// By default, performs semantic analysis to build the new expression.
2181 /// Subclasses may override this routine to provide different behavior.
2182 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2183 SourceLocation RParen) {
2184 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2185 }
2186
2187 /// Build a new pseudo-destructor expression.
2188 ///
2189 /// By default, performs semantic analysis to build the new expression.
2190 /// Subclasses may override this routine to provide different behavior.
2191 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2192 SourceLocation OperatorLoc,
2193 bool isArrow,
2194 CXXScopeSpec &SS,
2195 TypeSourceInfo *ScopeType,
2196 SourceLocation CCLoc,
2197 SourceLocation TildeLoc,
2198 PseudoDestructorTypeStorage Destroyed);
2199
2200 /// Build a new unary operator expression.
2201 ///
2202 /// By default, performs semantic analysis to build the new expression.
2203 /// Subclasses may override this routine to provide different behavior.
2204 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2205 UnaryOperatorKind Opc,
2206 Expr *SubExpr) {
2207 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2208 }
2209
2210 /// Build a new builtin offsetof expression.
2211 ///
2212 /// By default, performs semantic analysis to build the new expression.
2213 /// Subclasses may override this routine to provide different behavior.
2214 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2215 TypeSourceInfo *Type,
2216 ArrayRef<Sema::OffsetOfComponent> Components,
2217 SourceLocation RParenLoc) {
2218 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2219 RParenLoc);
2220 }
2221
2222 /// Build a new sizeof, alignof or vec_step expression with a
2223 /// type argument.
2224 ///
2225 /// By default, performs semantic analysis to build the new expression.
2226 /// Subclasses may override this routine to provide different behavior.
2227 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2228 SourceLocation OpLoc,
2229 UnaryExprOrTypeTrait ExprKind,
2230 SourceRange R) {
2231 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2232 }
2233
2234 /// Build a new sizeof, alignof or vec step expression with an
2235 /// expression argument.
2236 ///
2237 /// By default, performs semantic analysis to build the new expression.
2238 /// Subclasses may override this routine to provide different behavior.
2239 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2240 UnaryExprOrTypeTrait ExprKind,
2241 SourceRange R) {
2242 ExprResult Result
2243 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2244 if (Result.isInvalid())
2245 return ExprError();
2246
2247 return Result;
2248 }
2249
2250 /// Build a new array subscript expression.
2251 ///
2252 /// By default, performs semantic analysis to build the new expression.
2253 /// Subclasses may override this routine to provide different behavior.
2254 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2255 SourceLocation LBracketLoc,
2256 Expr *RHS,
2257 SourceLocation RBracketLoc) {
2258 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2259 LBracketLoc, RHS,
2260 RBracketLoc);
2261 }
2262
2263 /// Build a new array section expression.
2264 ///
2265 /// By default, performs semantic analysis to build the new expression.
2266 /// Subclasses may override this routine to provide different behavior.
2267 ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2268 Expr *LowerBound,
2269 SourceLocation ColonLoc, Expr *Length,
2270 SourceLocation RBracketLoc) {
2271 return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2272 ColonLoc, Length, RBracketLoc);
2273 }
2274
2275 /// Build a new call expression.
2276 ///
2277 /// By default, performs semantic analysis to build the new expression.
2278 /// Subclasses may override this routine to provide different behavior.
2279 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2280 MultiExprArg Args,
2281 SourceLocation RParenLoc,
2282 Expr *ExecConfig = nullptr) {
2283 return getSema().BuildCallExpr(/*Scope=*/nullptr, Callee, LParenLoc, Args,
2284 RParenLoc, ExecConfig);
2285 }
2286
2287 /// Build a new member access expression.
2288 ///
2289 /// By default, performs semantic analysis to build the new expression.
2290 /// Subclasses may override this routine to provide different behavior.
2291 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2292 bool isArrow,
2293 NestedNameSpecifierLoc QualifierLoc,
2294 SourceLocation TemplateKWLoc,
2295 const DeclarationNameInfo &MemberNameInfo,
2296 ValueDecl *Member,
2297 NamedDecl *FoundDecl,
2298 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2299 NamedDecl *FirstQualifierInScope) {
2300 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2301 isArrow);
2302 if (!Member->getDeclName()) {
2303 // We have a reference to an unnamed field. This is always the
2304 // base of an anonymous struct/union member access, i.e. the
2305 // field is always of record type.
2306 assert(Member->getType()->isRecordType() &&((Member->getType()->isRecordType() && "unnamed member not of record type?"
) ? static_cast<void> (0) : __assert_fail ("Member->getType()->isRecordType() && \"unnamed member not of record type?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 2307, __PRETTY_FUNCTION__))
2307 "unnamed member not of record type?")((Member->getType()->isRecordType() && "unnamed member not of record type?"
) ? static_cast<void> (0) : __assert_fail ("Member->getType()->isRecordType() && \"unnamed member not of record type?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 2307, __PRETTY_FUNCTION__))
;
2308
2309 BaseResult =
2310 getSema().PerformObjectMemberConversion(BaseResult.get(),
2311 QualifierLoc.getNestedNameSpecifier(),
2312 FoundDecl, Member);
2313 if (BaseResult.isInvalid())
2314 return ExprError();
2315 Base = BaseResult.get();
2316
2317 CXXScopeSpec EmptySS;
2318 return getSema().BuildFieldReferenceExpr(
2319 Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2320 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2321 }
2322
2323 CXXScopeSpec SS;
2324 SS.Adopt(QualifierLoc);
2325
2326 Base = BaseResult.get();
2327 QualType BaseType = Base->getType();
2328
2329 if (isArrow && !BaseType->isPointerType())
2330 return ExprError();
2331
2332 // FIXME: this involves duplicating earlier analysis in a lot of
2333 // cases; we should avoid this when possible.
2334 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2335 R.addDecl(FoundDecl);
2336 R.resolveKind();
2337
2338 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2339 SS, TemplateKWLoc,
2340 FirstQualifierInScope,
2341 R, ExplicitTemplateArgs,
2342 /*S*/nullptr);
2343 }
2344
2345 /// Build a new binary operator expression.
2346 ///
2347 /// By default, performs semantic analysis to build the new expression.
2348 /// Subclasses may override this routine to provide different behavior.
2349 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2350 BinaryOperatorKind Opc,
2351 Expr *LHS, Expr *RHS) {
2352 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2353 }
2354
2355 /// Build a new conditional operator expression.
2356 ///
2357 /// By default, performs semantic analysis to build the new expression.
2358 /// Subclasses may override this routine to provide different behavior.
2359 ExprResult RebuildConditionalOperator(Expr *Cond,
2360 SourceLocation QuestionLoc,
2361 Expr *LHS,
2362 SourceLocation ColonLoc,
2363 Expr *RHS) {
2364 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2365 LHS, RHS);
2366 }
2367
2368 /// Build a new C-style cast expression.
2369 ///
2370 /// By default, performs semantic analysis to build the new expression.
2371 /// Subclasses may override this routine to provide different behavior.
2372 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2373 TypeSourceInfo *TInfo,
2374 SourceLocation RParenLoc,
2375 Expr *SubExpr) {
2376 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2377 SubExpr);
2378 }
2379
2380 /// Build a new compound literal expression.
2381 ///
2382 /// By default, performs semantic analysis to build the new expression.
2383 /// Subclasses may override this routine to provide different behavior.
2384 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2385 TypeSourceInfo *TInfo,
2386 SourceLocation RParenLoc,
2387 Expr *Init) {
2388 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2389 Init);
2390 }
2391
2392 /// Build a new extended vector element access expression.
2393 ///
2394 /// By default, performs semantic analysis to build the new expression.
2395 /// Subclasses may override this routine to provide different behavior.
2396 ExprResult RebuildExtVectorElementExpr(Expr *Base,
2397 SourceLocation OpLoc,
2398 SourceLocation AccessorLoc,
2399 IdentifierInfo &Accessor) {
2400
2401 CXXScopeSpec SS;
2402 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2403 return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2404 OpLoc, /*IsArrow*/ false,
2405 SS, SourceLocation(),
2406 /*FirstQualifierInScope*/ nullptr,
2407 NameInfo,
2408 /* TemplateArgs */ nullptr,
2409 /*S*/ nullptr);
2410 }
2411
2412 /// Build a new initializer list expression.
2413 ///
2414 /// By default, performs semantic analysis to build the new expression.
2415 /// Subclasses may override this routine to provide different behavior.
2416 ExprResult RebuildInitList(SourceLocation LBraceLoc,
2417 MultiExprArg Inits,
2418 SourceLocation RBraceLoc) {
2419 return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2420 }
2421
2422 /// Build a new designated initializer expression.
2423 ///
2424 /// By default, performs semantic analysis to build the new expression.
2425 /// Subclasses may override this routine to provide different behavior.
2426 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2427 MultiExprArg ArrayExprs,
2428 SourceLocation EqualOrColonLoc,
2429 bool GNUSyntax,
2430 Expr *Init) {
2431 ExprResult Result
2432 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2433 Init);
2434 if (Result.isInvalid())
2435 return ExprError();
2436
2437 return Result;
2438 }
2439
2440 /// Build a new value-initialized expression.
2441 ///
2442 /// By default, builds the implicit value initialization without performing
2443 /// any semantic analysis. Subclasses may override this routine to provide
2444 /// different behavior.
2445 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2446 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2447 }
2448
2449 /// Build a new \c va_arg expression.
2450 ///
2451 /// By default, performs semantic analysis to build the new expression.
2452 /// Subclasses may override this routine to provide different behavior.
2453 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2454 Expr *SubExpr, TypeSourceInfo *TInfo,
2455 SourceLocation RParenLoc) {
2456 return getSema().BuildVAArgExpr(BuiltinLoc,
2457 SubExpr, TInfo,
2458 RParenLoc);
2459 }
2460
2461 /// Build a new expression list in parentheses.
2462 ///
2463 /// By default, performs semantic analysis to build the new expression.
2464 /// Subclasses may override this routine to provide different behavior.
2465 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2466 MultiExprArg SubExprs,
2467 SourceLocation RParenLoc) {
2468 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2469 }
2470
2471 /// Build a new address-of-label expression.
2472 ///
2473 /// By default, performs semantic analysis, using the name of the label
2474 /// rather than attempting to map the label statement itself.
2475 /// Subclasses may override this routine to provide different behavior.
2476 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2477 SourceLocation LabelLoc, LabelDecl *Label) {
2478 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2479 }
2480
2481 /// Build a new GNU statement expression.
2482 ///
2483 /// By default, performs semantic analysis to build the new expression.
2484 /// Subclasses may override this routine to provide different behavior.
2485 ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2486 Stmt *SubStmt,
2487 SourceLocation RParenLoc) {
2488 return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2489 }
2490
2491 /// Build a new __builtin_choose_expr expression.
2492 ///
2493 /// By default, performs semantic analysis to build the new expression.
2494 /// Subclasses may override this routine to provide different behavior.
2495 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2496 Expr *Cond, Expr *LHS, Expr *RHS,
2497 SourceLocation RParenLoc) {
2498 return SemaRef.ActOnChooseExpr(BuiltinLoc,
2499 Cond, LHS, RHS,
2500 RParenLoc);
2501 }
2502
2503 /// Build a new generic selection expression.
2504 ///
2505 /// By default, performs semantic analysis to build the new expression.
2506 /// Subclasses may override this routine to provide different behavior.
2507 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2508 SourceLocation DefaultLoc,
2509 SourceLocation RParenLoc,
2510 Expr *ControllingExpr,
2511 ArrayRef<TypeSourceInfo *> Types,
2512 ArrayRef<Expr *> Exprs) {
2513 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2514 ControllingExpr, Types, Exprs);
2515 }
2516
2517 /// Build a new overloaded operator call expression.
2518 ///
2519 /// By default, performs semantic analysis to build the new expression.
2520 /// The semantic analysis provides the behavior of template instantiation,
2521 /// copying with transformations that turn what looks like an overloaded
2522 /// operator call into a use of a builtin operator, performing
2523 /// argument-dependent lookup, etc. Subclasses may override this routine to
2524 /// provide different behavior.
2525 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2526 SourceLocation OpLoc,
2527 Expr *Callee,
2528 Expr *First,
2529 Expr *Second);
2530
2531 /// Build a new C++ "named" cast expression, such as static_cast or
2532 /// reinterpret_cast.
2533 ///
2534 /// By default, this routine dispatches to one of the more-specific routines
2535 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2536 /// Subclasses may override this routine to provide different behavior.
2537 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2538 Stmt::StmtClass Class,
2539 SourceLocation LAngleLoc,
2540 TypeSourceInfo *TInfo,
2541 SourceLocation RAngleLoc,
2542 SourceLocation LParenLoc,
2543 Expr *SubExpr,
2544 SourceLocation RParenLoc) {
2545 switch (Class) {
2546 case Stmt::CXXStaticCastExprClass:
2547 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2548 RAngleLoc, LParenLoc,
2549 SubExpr, RParenLoc);
2550
2551 case Stmt::CXXDynamicCastExprClass:
2552 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2553 RAngleLoc, LParenLoc,
2554 SubExpr, RParenLoc);
2555
2556 case Stmt::CXXReinterpretCastExprClass:
2557 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2558 RAngleLoc, LParenLoc,
2559 SubExpr,
2560 RParenLoc);
2561
2562 case Stmt::CXXConstCastExprClass:
2563 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2564 RAngleLoc, LParenLoc,
2565 SubExpr, RParenLoc);
2566
2567 default:
2568 llvm_unreachable("Invalid C++ named cast")::llvm::llvm_unreachable_internal("Invalid C++ named cast", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 2568)
;
2569 }
2570 }
2571
2572 /// Build a new C++ static_cast expression.
2573 ///
2574 /// By default, performs semantic analysis to build the new expression.
2575 /// Subclasses may override this routine to provide different behavior.
2576 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2577 SourceLocation LAngleLoc,
2578 TypeSourceInfo *TInfo,
2579 SourceLocation RAngleLoc,
2580 SourceLocation LParenLoc,
2581 Expr *SubExpr,
2582 SourceLocation RParenLoc) {
2583 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2584 TInfo, SubExpr,
2585 SourceRange(LAngleLoc, RAngleLoc),
2586 SourceRange(LParenLoc, RParenLoc));
2587 }
2588
2589 /// Build a new C++ dynamic_cast expression.
2590 ///
2591 /// By default, performs semantic analysis to build the new expression.
2592 /// Subclasses may override this routine to provide different behavior.
2593 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2594 SourceLocation LAngleLoc,
2595 TypeSourceInfo *TInfo,
2596 SourceLocation RAngleLoc,
2597 SourceLocation LParenLoc,
2598 Expr *SubExpr,
2599 SourceLocation RParenLoc) {
2600 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2601 TInfo, SubExpr,
2602 SourceRange(LAngleLoc, RAngleLoc),
2603 SourceRange(LParenLoc, RParenLoc));
2604 }
2605
2606 /// Build a new C++ reinterpret_cast expression.
2607 ///
2608 /// By default, performs semantic analysis to build the new expression.
2609 /// Subclasses may override this routine to provide different behavior.
2610 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2611 SourceLocation LAngleLoc,
2612 TypeSourceInfo *TInfo,
2613 SourceLocation RAngleLoc,
2614 SourceLocation LParenLoc,
2615 Expr *SubExpr,
2616 SourceLocation RParenLoc) {
2617 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2618 TInfo, SubExpr,
2619 SourceRange(LAngleLoc, RAngleLoc),
2620 SourceRange(LParenLoc, RParenLoc));
2621 }
2622
2623 /// Build a new C++ const_cast expression.
2624 ///
2625 /// By default, performs semantic analysis to build the new expression.
2626 /// Subclasses may override this routine to provide different behavior.
2627 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2628 SourceLocation LAngleLoc,
2629 TypeSourceInfo *TInfo,
2630 SourceLocation RAngleLoc,
2631 SourceLocation LParenLoc,
2632 Expr *SubExpr,
2633 SourceLocation RParenLoc) {
2634 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2635 TInfo, SubExpr,
2636 SourceRange(LAngleLoc, RAngleLoc),
2637 SourceRange(LParenLoc, RParenLoc));
2638 }
2639
2640 /// Build a new C++ functional-style cast expression.
2641 ///
2642 /// By default, performs semantic analysis to build the new expression.
2643 /// Subclasses may override this routine to provide different behavior.
2644 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2645 SourceLocation LParenLoc,
2646 Expr *Sub,
2647 SourceLocation RParenLoc,
2648 bool ListInitialization) {
2649 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2650 MultiExprArg(&Sub, 1), RParenLoc,
2651 ListInitialization);
2652 }
2653
2654 /// Build a new C++ __builtin_bit_cast expression.
2655 ///
2656 /// By default, performs semantic analysis to build the new expression.
2657 /// Subclasses may override this routine to provide different behavior.
2658 ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
2659 TypeSourceInfo *TSI, Expr *Sub,
2660 SourceLocation RParenLoc) {
2661 return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
2662 }
2663
2664 /// Build a new C++ typeid(type) expression.
2665 ///
2666 /// By default, performs semantic analysis to build the new expression.
2667 /// Subclasses may override this routine to provide different behavior.
2668 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2669 SourceLocation TypeidLoc,
2670 TypeSourceInfo *Operand,
2671 SourceLocation RParenLoc) {
2672 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2673 RParenLoc);
2674 }
2675
2676
2677 /// Build a new C++ typeid(expr) expression.
2678 ///
2679 /// By default, performs semantic analysis to build the new expression.
2680 /// Subclasses may override this routine to provide different behavior.
2681 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2682 SourceLocation TypeidLoc,
2683 Expr *Operand,
2684 SourceLocation RParenLoc) {
2685 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2686 RParenLoc);
2687 }
2688
2689 /// Build a new C++ __uuidof(type) expression.
2690 ///
2691 /// By default, performs semantic analysis to build the new expression.
2692 /// Subclasses may override this routine to provide different behavior.
2693 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2694 SourceLocation TypeidLoc,
2695 TypeSourceInfo *Operand,
2696 SourceLocation RParenLoc) {
2697 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2698 RParenLoc);
2699 }
2700
2701 /// Build a new C++ __uuidof(expr) expression.
2702 ///
2703 /// By default, performs semantic analysis to build the new expression.
2704 /// Subclasses may override this routine to provide different behavior.
2705 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2706 SourceLocation TypeidLoc,
2707 Expr *Operand,
2708 SourceLocation RParenLoc) {
2709 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2710 RParenLoc);
2711 }
2712
2713 /// Build a new C++ "this" expression.
2714 ///
2715 /// By default, builds a new "this" expression without performing any
2716 /// semantic analysis. Subclasses may override this routine to provide
2717 /// different behavior.
2718 ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2719 QualType ThisType,
2720 bool isImplicit) {
2721 return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
2722 }
2723
2724 /// Build a new C++ throw expression.
2725 ///
2726 /// By default, performs semantic analysis to build the new expression.
2727 /// Subclasses may override this routine to provide different behavior.
2728 ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2729 bool IsThrownVariableInScope) {
2730 return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2731 }
2732
2733 /// Build a new C++ default-argument expression.
2734 ///
2735 /// By default, builds a new default-argument expression, which does not
2736 /// require any semantic analysis. Subclasses may override this routine to
2737 /// provide different behavior.
2738 ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param) {
2739 return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
2740 getSema().CurContext);
2741 }
2742
2743 /// Build a new C++11 default-initialization expression.
2744 ///
2745 /// By default, builds a new default field initialization expression, which
2746 /// does not require any semantic analysis. Subclasses may override this
2747 /// routine to provide different behavior.
2748 ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2749 FieldDecl *Field) {
2750 return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field,
2751 getSema().CurContext);
2752 }
2753
2754 /// Build a new C++ zero-initialization expression.
2755 ///
2756 /// By default, performs semantic analysis to build the new expression.
2757 /// Subclasses may override this routine to provide different behavior.
2758 ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2759 SourceLocation LParenLoc,
2760 SourceLocation RParenLoc) {
2761 return getSema().BuildCXXTypeConstructExpr(
2762 TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
2763 }
2764
2765 /// Build a new C++ "new" expression.
2766 ///
2767 /// By default, performs semantic analysis to build the new expression.
2768 /// Subclasses may override this routine to provide different behavior.
2769 ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2770 bool UseGlobal,
2771 SourceLocation PlacementLParen,
2772 MultiExprArg PlacementArgs,
2773 SourceLocation PlacementRParen,
2774 SourceRange TypeIdParens,
2775 QualType AllocatedType,
2776 TypeSourceInfo *AllocatedTypeInfo,
2777 Optional<Expr *> ArraySize,
2778 SourceRange DirectInitRange,
2779 Expr *Initializer) {
2780 return getSema().BuildCXXNew(StartLoc, UseGlobal,
2781 PlacementLParen,
2782 PlacementArgs,
2783 PlacementRParen,
2784 TypeIdParens,
2785 AllocatedType,
2786 AllocatedTypeInfo,
2787 ArraySize,
2788 DirectInitRange,
2789 Initializer);
2790 }
2791
2792 /// Build a new C++ "delete" expression.
2793 ///
2794 /// By default, performs semantic analysis to build the new expression.
2795 /// Subclasses may override this routine to provide different behavior.
2796 ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2797 bool IsGlobalDelete,
2798 bool IsArrayForm,
2799 Expr *Operand) {
2800 return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2801 Operand);
2802 }
2803
2804 /// Build a new type trait expression.
2805 ///
2806 /// By default, performs semantic analysis to build the new expression.
2807 /// Subclasses may override this routine to provide different behavior.
2808 ExprResult RebuildTypeTrait(TypeTrait Trait,
2809 SourceLocation StartLoc,
2810 ArrayRef<TypeSourceInfo *> Args,
2811 SourceLocation RParenLoc) {
2812 return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2813 }
2814
2815 /// Build a new array type trait expression.
2816 ///
2817 /// By default, performs semantic analysis to build the new expression.
2818 /// Subclasses may override this routine to provide different behavior.
2819 ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2820 SourceLocation StartLoc,
2821 TypeSourceInfo *TSInfo,
2822 Expr *DimExpr,
2823 SourceLocation RParenLoc) {
2824 return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2825 }
2826
2827 /// Build a new expression trait expression.
2828 ///
2829 /// By default, performs semantic analysis to build the new expression.
2830 /// Subclasses may override this routine to provide different behavior.
2831 ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2832 SourceLocation StartLoc,
2833 Expr *Queried,
2834 SourceLocation RParenLoc) {
2835 return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2836 }
2837
2838 /// Build a new (previously unresolved) declaration reference
2839 /// expression.
2840 ///
2841 /// By default, performs semantic analysis to build the new expression.
2842 /// Subclasses may override this routine to provide different behavior.
2843 ExprResult RebuildDependentScopeDeclRefExpr(
2844 NestedNameSpecifierLoc QualifierLoc,
2845 SourceLocation TemplateKWLoc,
2846 const DeclarationNameInfo &NameInfo,
2847 const TemplateArgumentListInfo *TemplateArgs,
2848 bool IsAddressOfOperand,
2849 TypeSourceInfo **RecoveryTSI) {
2850 CXXScopeSpec SS;
2851 SS.Adopt(QualifierLoc);
2852
2853 if (TemplateArgs || TemplateKWLoc.isValid())
2854 return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2855 TemplateArgs);
2856
2857 return getSema().BuildQualifiedDeclarationNameExpr(
2858 SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
2859 }
2860
2861 /// Build a new template-id expression.
2862 ///
2863 /// By default, performs semantic analysis to build the new expression.
2864 /// Subclasses may override this routine to provide different behavior.
2865 ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2866 SourceLocation TemplateKWLoc,
2867 LookupResult &R,
2868 bool RequiresADL,
2869 const TemplateArgumentListInfo *TemplateArgs) {
2870 return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2871 TemplateArgs);
2872 }
2873
2874 /// Build a new object-construction expression.
2875 ///
2876 /// By default, performs semantic analysis to build the new expression.
2877 /// Subclasses may override this routine to provide different behavior.
2878 ExprResult RebuildCXXConstructExpr(QualType T,
2879 SourceLocation Loc,
2880 CXXConstructorDecl *Constructor,
2881 bool IsElidable,
2882 MultiExprArg Args,
2883 bool HadMultipleCandidates,
2884 bool ListInitialization,
2885 bool StdInitListInitialization,
2886 bool RequiresZeroInit,
2887 CXXConstructExpr::ConstructionKind ConstructKind,
2888 SourceRange ParenRange) {
2889 SmallVector<Expr*, 8> ConvertedArgs;
2890 if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2891 ConvertedArgs))
2892 return ExprError();
2893
2894 return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
2895 IsElidable,
2896 ConvertedArgs,
2897 HadMultipleCandidates,
2898 ListInitialization,
2899 StdInitListInitialization,
2900 RequiresZeroInit, ConstructKind,
2901 ParenRange);
2902 }
2903
2904 /// Build a new implicit construction via inherited constructor
2905 /// expression.
2906 ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
2907 CXXConstructorDecl *Constructor,
2908 bool ConstructsVBase,
2909 bool InheritedFromVBase) {
2910 return new (getSema().Context) CXXInheritedCtorInitExpr(
2911 Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
2912 }
2913
2914 /// Build a new object-construction expression.
2915 ///
2916 /// By default, performs semantic analysis to build the new expression.
2917 /// Subclasses may override this routine to provide different behavior.
2918 ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2919 SourceLocation LParenOrBraceLoc,
2920 MultiExprArg Args,
2921 SourceLocation RParenOrBraceLoc,
2922 bool ListInitialization) {
2923 return getSema().BuildCXXTypeConstructExpr(
2924 TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
2925 }
2926
2927 /// Build a new object-construction expression.
2928 ///
2929 /// By default, performs semantic analysis to build the new expression.
2930 /// Subclasses may override this routine to provide different behavior.
2931 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2932 SourceLocation LParenLoc,
2933 MultiExprArg Args,
2934 SourceLocation RParenLoc,
2935 bool ListInitialization) {
2936 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
2937 RParenLoc, ListInitialization);
2938 }
2939
2940 /// Build a new member reference expression.
2941 ///
2942 /// By default, performs semantic analysis to build the new expression.
2943 /// Subclasses may override this routine to provide different behavior.
2944 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2945 QualType BaseType,
2946 bool IsArrow,
2947 SourceLocation OperatorLoc,
2948 NestedNameSpecifierLoc QualifierLoc,
2949 SourceLocation TemplateKWLoc,
2950 NamedDecl *FirstQualifierInScope,
2951 const DeclarationNameInfo &MemberNameInfo,
2952 const TemplateArgumentListInfo *TemplateArgs) {
2953 CXXScopeSpec SS;
2954 SS.Adopt(QualifierLoc);
2955
2956 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2957 OperatorLoc, IsArrow,
2958 SS, TemplateKWLoc,
2959 FirstQualifierInScope,
2960 MemberNameInfo,
2961 TemplateArgs, /*S*/nullptr);
2962 }
2963
2964 /// Build a new member reference expression.
2965 ///
2966 /// By default, performs semantic analysis to build the new expression.
2967 /// Subclasses may override this routine to provide different behavior.
2968 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2969 SourceLocation OperatorLoc,
2970 bool IsArrow,
2971 NestedNameSpecifierLoc QualifierLoc,
2972 SourceLocation TemplateKWLoc,
2973 NamedDecl *FirstQualifierInScope,
2974 LookupResult &R,
2975 const TemplateArgumentListInfo *TemplateArgs) {
2976 CXXScopeSpec SS;
2977 SS.Adopt(QualifierLoc);
2978
2979 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2980 OperatorLoc, IsArrow,
2981 SS, TemplateKWLoc,
2982 FirstQualifierInScope,
2983 R, TemplateArgs, /*S*/nullptr);
2984 }
2985
2986 /// Build a new noexcept expression.
2987 ///
2988 /// By default, performs semantic analysis to build the new expression.
2989 /// Subclasses may override this routine to provide different behavior.
2990 ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
2991 return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
2992 }
2993
2994 /// Build a new expression to compute the length of a parameter pack.
2995 ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
2996 NamedDecl *Pack,
2997 SourceLocation PackLoc,
2998 SourceLocation RParenLoc,
2999 Optional<unsigned> Length,
3000 ArrayRef<TemplateArgument> PartialArgs) {
3001 return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3002 RParenLoc, Length, PartialArgs);
3003 }
3004
3005 /// Build a new expression representing a call to a source location
3006 /// builtin.
3007 ///
3008 /// By default, performs semantic analysis to build the new expression.
3009 /// Subclasses may override this routine to provide different behavior.
3010 ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3011 SourceLocation BuiltinLoc,
3012 SourceLocation RPLoc,
3013 DeclContext *ParentContext) {
3014 return getSema().BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, ParentContext);
3015 }
3016
3017 /// Build a new Objective-C boxed expression.
3018 ///
3019 /// By default, performs semantic analysis to build the new expression.
3020 /// Subclasses may override this routine to provide different behavior.
3021 ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3022 return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3023 }
3024
3025 /// Build a new Objective-C array literal.
3026 ///
3027 /// By default, performs semantic analysis to build the new expression.
3028 /// Subclasses may override this routine to provide different behavior.
3029 ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3030 Expr **Elements, unsigned NumElements) {
3031 return getSema().BuildObjCArrayLiteral(Range,
3032 MultiExprArg(Elements, NumElements));
3033 }
3034
3035 ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3036 Expr *Base, Expr *Key,
3037 ObjCMethodDecl *getterMethod,
3038 ObjCMethodDecl *setterMethod) {
3039 return getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3040 getterMethod, setterMethod);
3041 }
3042
3043 /// Build a new Objective-C dictionary literal.
3044 ///
3045 /// By default, performs semantic analysis to build the new expression.
3046 /// Subclasses may override this routine to provide different behavior.
3047 ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3048 MutableArrayRef<ObjCDictionaryElement> Elements) {
3049 return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3050 }
3051
3052 /// Build a new Objective-C \@encode expression.
3053 ///
3054 /// By default, performs semantic analysis to build the new expression.
3055 /// Subclasses may override this routine to provide different behavior.
3056 ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3057 TypeSourceInfo *EncodeTypeInfo,
3058 SourceLocation RParenLoc) {
3059 return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3060 }
3061
3062 /// Build a new Objective-C class message.
3063 ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3064 Selector Sel,
3065 ArrayRef<SourceLocation> SelectorLocs,
3066 ObjCMethodDecl *Method,
3067 SourceLocation LBracLoc,
3068 MultiExprArg Args,
3069 SourceLocation RBracLoc) {
3070 return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3071 ReceiverTypeInfo->getType(),
3072 /*SuperLoc=*/SourceLocation(),
3073 Sel, Method, LBracLoc, SelectorLocs,
3074 RBracLoc, Args);
3075 }
3076
3077 /// Build a new Objective-C instance message.
3078 ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3079 Selector Sel,
3080 ArrayRef<SourceLocation> SelectorLocs,
3081 ObjCMethodDecl *Method,
3082 SourceLocation LBracLoc,
3083 MultiExprArg Args,
3084 SourceLocation RBracLoc) {
3085 return SemaRef.BuildInstanceMessage(Receiver,
3086 Receiver->getType(),
3087 /*SuperLoc=*/SourceLocation(),
3088 Sel, Method, LBracLoc, SelectorLocs,
3089 RBracLoc, Args);
3090 }
3091
3092 /// Build a new Objective-C instance/class message to 'super'.
3093 ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3094 Selector Sel,
3095 ArrayRef<SourceLocation> SelectorLocs,
3096 QualType SuperType,
3097 ObjCMethodDecl *Method,
3098 SourceLocation LBracLoc,
3099 MultiExprArg Args,
3100 SourceLocation RBracLoc) {
3101 return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3102 SuperType,
3103 SuperLoc,
3104 Sel, Method, LBracLoc, SelectorLocs,
3105 RBracLoc, Args)
3106 : SemaRef.BuildClassMessage(nullptr,
3107 SuperType,
3108 SuperLoc,
3109 Sel, Method, LBracLoc, SelectorLocs,
3110 RBracLoc, Args);
3111
3112
3113 }
3114
3115 /// Build a new Objective-C ivar reference expression.
3116 ///
3117 /// By default, performs semantic analysis to build the new expression.
3118 /// Subclasses may override this routine to provide different behavior.
3119 ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3120 SourceLocation IvarLoc,
3121 bool IsArrow, bool IsFreeIvar) {
3122 CXXScopeSpec SS;
3123 DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3124 ExprResult Result = getSema().BuildMemberReferenceExpr(
3125 BaseArg, BaseArg->getType(),
3126 /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3127 /*FirstQualifierInScope=*/nullptr, NameInfo,
3128 /*TemplateArgs=*/nullptr,
3129 /*S=*/nullptr);
3130 if (IsFreeIvar && Result.isUsable())
3131 cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3132 return Result;
3133 }
3134
3135 /// Build a new Objective-C property reference expression.
3136 ///
3137 /// By default, performs semantic analysis to build the new expression.
3138 /// Subclasses may override this routine to provide different behavior.
3139 ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3140 ObjCPropertyDecl *Property,
3141 SourceLocation PropertyLoc) {
3142 CXXScopeSpec SS;
3143 DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3144 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3145 /*FIXME:*/PropertyLoc,
3146 /*IsArrow=*/false,
3147 SS, SourceLocation(),
3148 /*FirstQualifierInScope=*/nullptr,
3149 NameInfo,
3150 /*TemplateArgs=*/nullptr,
3151 /*S=*/nullptr);
3152 }
3153
3154 /// Build a new Objective-C property reference expression.
3155 ///
3156 /// By default, performs semantic analysis to build the new expression.
3157 /// Subclasses may override this routine to provide different behavior.
3158 ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3159 ObjCMethodDecl *Getter,
3160 ObjCMethodDecl *Setter,
3161 SourceLocation PropertyLoc) {
3162 // Since these expressions can only be value-dependent, we do not
3163 // need to perform semantic analysis again.
3164 return Owned(
3165 new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3166 VK_LValue, OK_ObjCProperty,
3167 PropertyLoc, Base));
3168 }
3169
3170 /// Build a new Objective-C "isa" expression.
3171 ///
3172 /// By default, performs semantic analysis to build the new expression.
3173 /// Subclasses may override this routine to provide different behavior.
3174 ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3175 SourceLocation OpLoc, bool IsArrow) {
3176 CXXScopeSpec SS;
3177 DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3178 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3179 OpLoc, IsArrow,
3180 SS, SourceLocation(),
3181 /*FirstQualifierInScope=*/nullptr,
3182 NameInfo,
3183 /*TemplateArgs=*/nullptr,
3184 /*S=*/nullptr);
3185 }
3186
3187 /// Build a new shuffle vector expression.
3188 ///
3189 /// By default, performs semantic analysis to build the new expression.
3190 /// Subclasses may override this routine to provide different behavior.
3191 ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3192 MultiExprArg SubExprs,
3193 SourceLocation RParenLoc) {
3194 // Find the declaration for __builtin_shufflevector
3195 const IdentifierInfo &Name
3196 = SemaRef.Context.Idents.get("__builtin_shufflevector");
3197 TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3198 DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3199 assert(!Lookup.empty() && "No __builtin_shufflevector?")((!Lookup.empty() && "No __builtin_shufflevector?") ?
static_cast<void> (0) : __assert_fail ("!Lookup.empty() && \"No __builtin_shufflevector?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 3199, __PRETTY_FUNCTION__))
;
3200
3201 // Build a reference to the __builtin_shufflevector builtin
3202 FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3203 Expr *Callee = new (SemaRef.Context)
3204 DeclRefExpr(SemaRef.Context, Builtin, false,
3205 SemaRef.Context.BuiltinFnTy, VK_RValue, BuiltinLoc);
3206 QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3207 Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3208 CK_BuiltinFnToFnPtr).get();
3209
3210 // Build the CallExpr
3211 ExprResult TheCall = CallExpr::Create(
3212 SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3213 Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
3214
3215 // Type-check the __builtin_shufflevector expression.
3216 return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3217 }
3218
3219 /// Build a new convert vector expression.
3220 ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3221 Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3222 SourceLocation RParenLoc) {
3223 return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3224 BuiltinLoc, RParenLoc);
3225 }
3226
3227 /// Build a new template argument pack expansion.
3228 ///
3229 /// By default, performs semantic analysis to build a new pack expansion
3230 /// for a template argument. Subclasses may override this routine to provide
3231 /// different behavior.
3232 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3233 SourceLocation EllipsisLoc,
3234 Optional<unsigned> NumExpansions) {
3235 switch (Pattern.getArgument().getKind()) {
3236 case TemplateArgument::Expression: {
3237 ExprResult Result
3238 = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3239 EllipsisLoc, NumExpansions);
3240 if (Result.isInvalid())
3241 return TemplateArgumentLoc();
3242
3243 return TemplateArgumentLoc(Result.get(), Result.get());
3244 }
3245
3246 case TemplateArgument::Template:
3247 return TemplateArgumentLoc(TemplateArgument(
3248 Pattern.getArgument().getAsTemplate(),
3249 NumExpansions),
3250 Pattern.getTemplateQualifierLoc(),
3251 Pattern.getTemplateNameLoc(),
3252 EllipsisLoc);
3253
3254 case TemplateArgument::Null:
3255 case TemplateArgument::Integral:
3256 case TemplateArgument::Declaration:
3257 case TemplateArgument::Pack:
3258 case TemplateArgument::TemplateExpansion:
3259 case TemplateArgument::NullPtr:
3260 llvm_unreachable("Pack expansion pattern has no parameter packs")::llvm::llvm_unreachable_internal("Pack expansion pattern has no parameter packs"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 3260)
;
3261
3262 case TemplateArgument::Type:
3263 if (TypeSourceInfo *Expansion
3264 = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3265 EllipsisLoc,
3266 NumExpansions))
3267 return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3268 Expansion);
3269 break;
3270 }
3271
3272 return TemplateArgumentLoc();
3273 }
3274
3275 /// Build a new expression pack expansion.
3276 ///
3277 /// By default, performs semantic analysis to build a new pack expansion
3278 /// for an expression. Subclasses may override this routine to provide
3279 /// different behavior.
3280 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3281 Optional<unsigned> NumExpansions) {
3282 return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3283 }
3284
3285 /// Build a new C++1z fold-expression.
3286 ///
3287 /// By default, performs semantic analysis in order to build a new fold
3288 /// expression.
3289 ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
3290 BinaryOperatorKind Operator,
3291 SourceLocation EllipsisLoc, Expr *RHS,
3292 SourceLocation RParenLoc,
3293 Optional<unsigned> NumExpansions) {
3294 return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
3295 RHS, RParenLoc, NumExpansions);
3296 }
3297
3298 /// Build an empty C++1z fold-expression with the given operator.
3299 ///
3300 /// By default, produces the fallback value for the fold-expression, or
3301 /// produce an error if there is no fallback value.
3302 ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3303 BinaryOperatorKind Operator) {
3304 return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3305 }
3306
3307 /// Build a new atomic operation expression.
3308 ///
3309 /// By default, performs semantic analysis to build the new expression.
3310 /// Subclasses may override this routine to provide different behavior.
3311 ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3312 AtomicExpr::AtomicOp Op,
3313 SourceLocation RParenLoc) {
3314 // Use this for all of the locations, since we don't know the difference
3315 // between the call and the expr at this point.
3316 SourceRange Range{BuiltinLoc, RParenLoc};
3317 return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3318 Sema::AtomicArgumentOrder::AST);
3319 }
3320
3321private:
3322 TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3323 QualType ObjectType,
3324 NamedDecl *FirstQualifierInScope,
3325 CXXScopeSpec &SS);
3326
3327 TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3328 QualType ObjectType,
3329 NamedDecl *FirstQualifierInScope,
3330 CXXScopeSpec &SS);
3331
3332 TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3333 NamedDecl *FirstQualifierInScope,
3334 CXXScopeSpec &SS);
3335
3336 QualType TransformDependentNameType(TypeLocBuilder &TLB,
3337 DependentNameTypeLoc TL,
3338 bool DeducibleTSTContext);
3339};
3340
3341template <typename Derived>
3342StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3343 if (!S)
3344 return S;
3345
3346 switch (S->getStmtClass()) {
3347 case Stmt::NoStmtClass: break;
3348
3349 // Transform individual statement nodes
3350 // Pass SDK into statements that can produce a value
3351#define STMT(Node, Parent) \
3352 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3353#define VALUESTMT(Node, Parent) \
3354 case Stmt::Node##Class: \
3355 return getDerived().Transform##Node(cast<Node>(S), SDK);
3356#define ABSTRACT_STMT(Node)
3357#define EXPR(Node, Parent)
3358#include "clang/AST/StmtNodes.inc"
3359
3360 // Transform expressions by calling TransformExpr.
3361#define STMT(Node, Parent)
3362#define ABSTRACT_STMT(Stmt)
3363#define EXPR(Node, Parent) case Stmt::Node##Class:
3364#include "clang/AST/StmtNodes.inc"
3365 {
3366 ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3367
3368 if (SDK == SDK_StmtExprResult)
3369 E = getSema().ActOnStmtExprResult(E);
3370 return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3371 }
3372 }
3373
3374 return S;
3375}
3376
3377template<typename Derived>
3378OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3379 if (!S)
3380 return S;
3381
3382 switch (S->getClauseKind()) {
3383 default: break;
3384 // Transform individual clause nodes
3385#define OPENMP_CLAUSE(Name, Class) \
3386 case OMPC_ ## Name : \
3387 return getDerived().Transform ## Class(cast<Class>(S));
3388#include "clang/Basic/OpenMPKinds.def"
3389 }
3390
3391 return S;
3392}
3393
3394
3395template<typename Derived>
3396ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3397 if (!E)
3398 return E;
3399
3400 switch (E->getStmtClass()) {
3401 case Stmt::NoStmtClass: break;
3402#define STMT(Node, Parent) case Stmt::Node##Class: break;
3403#define ABSTRACT_STMT(Stmt)
3404#define EXPR(Node, Parent) \
3405 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3406#include "clang/AST/StmtNodes.inc"
3407 }
3408
3409 return E;
3410}
3411
3412template<typename Derived>
3413ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3414 bool NotCopyInit) {
3415 // Initializers are instantiated like expressions, except that various outer
3416 // layers are stripped.
3417 if (!Init)
3418 return Init;
3419
3420 if (auto *FE = dyn_cast<FullExpr>(Init))
3421 Init = FE->getSubExpr();
3422
3423 if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init))
3424 Init = AIL->getCommonExpr();
3425
3426 if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3427 Init = MTE->GetTemporaryExpr();
3428
3429 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3430 Init = Binder->getSubExpr();
3431
3432 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3433 Init = ICE->getSubExprAsWritten();
3434
3435 if (CXXStdInitializerListExpr *ILE =
3436 dyn_cast<CXXStdInitializerListExpr>(Init))
3437 return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3438
3439 // If this is copy-initialization, we only need to reconstruct
3440 // InitListExprs. Other forms of copy-initialization will be a no-op if
3441 // the initializer is already the right type.
3442 CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3443 if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3444 return getDerived().TransformExpr(Init);
3445
3446 // Revert value-initialization back to empty parens.
3447 if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3448 SourceRange Parens = VIE->getSourceRange();
3449 return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3450 Parens.getEnd());
3451 }
3452
3453 // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3454 if (isa<ImplicitValueInitExpr>(Init))
3455 return getDerived().RebuildParenListExpr(SourceLocation(), None,
3456 SourceLocation());
3457
3458 // Revert initialization by constructor back to a parenthesized or braced list
3459 // of expressions. Any other form of initializer can just be reused directly.
3460 if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3461 return getDerived().TransformExpr(Init);
3462
3463 // If the initialization implicitly converted an initializer list to a
3464 // std::initializer_list object, unwrap the std::initializer_list too.
3465 if (Construct && Construct->isStdInitListInitialization())
3466 return TransformInitializer(Construct->getArg(0), NotCopyInit);
3467
3468 // Enter a list-init context if this was list initialization.
3469 EnterExpressionEvaluationContext Context(
3470 getSema(), EnterExpressionEvaluationContext::InitList,
3471 Construct->isListInitialization());
3472
3473 SmallVector<Expr*, 8> NewArgs;
3474 bool ArgChanged = false;
3475 if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3476 /*IsCall*/true, NewArgs, &ArgChanged))
3477 return ExprError();
3478
3479 // If this was list initialization, revert to syntactic list form.
3480 if (Construct->isListInitialization())
3481 return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
3482 Construct->getEndLoc());
3483
3484 // Build a ParenListExpr to represent anything else.
3485 SourceRange Parens = Construct->getParenOrBraceRange();
3486 if (Parens.isInvalid()) {
3487 // This was a variable declaration's initialization for which no initializer
3488 // was specified.
3489 assert(NewArgs.empty() &&((NewArgs.empty() && "no parens or braces but have direct init with arguments?"
) ? static_cast<void> (0) : __assert_fail ("NewArgs.empty() && \"no parens or braces but have direct init with arguments?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 3490, __PRETTY_FUNCTION__))
3490 "no parens or braces but have direct init with arguments?")((NewArgs.empty() && "no parens or braces but have direct init with arguments?"
) ? static_cast<void> (0) : __assert_fail ("NewArgs.empty() && \"no parens or braces but have direct init with arguments?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 3490, __PRETTY_FUNCTION__))
;
3491 return ExprEmpty();
3492 }
3493 return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3494 Parens.getEnd());
3495}
3496
3497template<typename Derived>
3498bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3499 unsigned NumInputs,
3500 bool IsCall,
3501 SmallVectorImpl<Expr *> &Outputs,
3502 bool *ArgChanged) {
3503 for (unsigned I = 0; I != NumInputs; ++I) {
3504 // If requested, drop call arguments that need to be dropped.
3505 if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3506 if (ArgChanged)
3507 *ArgChanged = true;
3508
3509 break;
3510 }
3511
3512 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3513 Expr *Pattern = Expansion->getPattern();
3514
3515 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3516 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3517 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")((!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? static_cast<void> (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 3517, __PRETTY_FUNCTION__))
;
3518
3519 // Determine whether the set of unexpanded parameter packs can and should
3520 // be expanded.
3521 bool Expand = true;
3522 bool RetainExpansion = false;
3523 Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3524 Optional<unsigned> NumExpansions = OrigNumExpansions;
3525 if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3526 Pattern->getSourceRange(),
3527 Unexpanded,
3528 Expand, RetainExpansion,
3529 NumExpansions))
3530 return true;
3531
3532 if (!Expand) {
3533 // The transform has determined that we should perform a simple
3534 // transformation on the pack expansion, producing another pack
3535 // expansion.
3536 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3537 ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3538 if (OutPattern.isInvalid())
3539 return true;
3540
3541 ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3542 Expansion->getEllipsisLoc(),
3543 NumExpansions);
3544 if (Out.isInvalid())
3545 return true;
3546
3547 if (ArgChanged)
3548 *ArgChanged = true;
3549 Outputs.push_back(Out.get());
3550 continue;
3551 }
3552
3553 // Record right away that the argument was changed. This needs
3554 // to happen even if the array expands to nothing.
3555 if (ArgChanged) *ArgChanged = true;
3556
3557 // The transform has determined that we should perform an elementwise
3558 // expansion of the pattern. Do so.
3559 for (unsigned I = 0; I != *NumExpansions; ++I) {
3560 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3561 ExprResult Out = getDerived().TransformExpr(Pattern);
3562 if (Out.isInvalid())
3563 return true;
3564
3565 if (Out.get()->containsUnexpandedParameterPack()) {
3566 Out = getDerived().RebuildPackExpansion(
3567 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3568 if (Out.isInvalid())
3569 return true;
3570 }
3571
3572 Outputs.push_back(Out.get());
3573 }
3574
3575 // If we're supposed to retain a pack expansion, do so by temporarily
3576 // forgetting the partially-substituted parameter pack.
3577 if (RetainExpansion) {
3578 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3579
3580 ExprResult Out = getDerived().TransformExpr(Pattern);
3581 if (Out.isInvalid())
3582 return true;
3583
3584 Out = getDerived().RebuildPackExpansion(
3585 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3586 if (Out.isInvalid())
3587 return true;
3588
3589 Outputs.push_back(Out.get());
3590 }
3591
3592 continue;
3593 }
3594
3595 ExprResult Result =
3596 IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3597 : getDerived().TransformExpr(Inputs[I]);
3598 if (Result.isInvalid())
3599 return true;
3600
3601 if (Result.get() != Inputs[I] && ArgChanged)
3602 *ArgChanged = true;
3603
3604 Outputs.push_back(Result.get());
3605 }
3606
3607 return false;
3608}
3609
3610template <typename Derived>
3611Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
3612 SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
3613 if (Var) {
3614 VarDecl *ConditionVar = cast_or_null<VarDecl>(
3615 getDerived().TransformDefinition(Var->getLocation(), Var));
3616
3617 if (!ConditionVar)
3618 return Sema::ConditionError();
3619
3620 return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
3621 }
3622
3623 if (Expr) {
3624 ExprResult CondExpr = getDerived().TransformExpr(Expr);
3625
3626 if (CondExpr.isInvalid())
3627 return Sema::ConditionError();
3628
3629 return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind);
3630 }
3631
3632 return Sema::ConditionResult();
3633}
3634
3635template<typename Derived>
3636NestedNameSpecifierLoc
3637TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3638 NestedNameSpecifierLoc NNS,
3639 QualType ObjectType,
3640 NamedDecl *FirstQualifierInScope) {
3641 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3642 for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3643 Qualifier = Qualifier.getPrefix())
3644 Qualifiers.push_back(Qualifier);
3645
3646 CXXScopeSpec SS;
3647 while (!Qualifiers.empty()) {
3648 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3649 NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3650
3651 switch (QNNS->getKind()) {
3652 case NestedNameSpecifier::Identifier: {
3653 Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
3654 Q.getLocalBeginLoc(), Q.getLocalEndLoc(), ObjectType);
3655 if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
3656 SS, FirstQualifierInScope, false))
3657 return NestedNameSpecifierLoc();
3658 }
3659 break;
3660
3661 case NestedNameSpecifier::Namespace: {
3662 NamespaceDecl *NS
3663 = cast_or_null<NamespaceDecl>(
3664 getDerived().TransformDecl(
3665 Q.getLocalBeginLoc(),
3666 QNNS->getAsNamespace()));
3667 SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3668 break;
3669 }
3670
3671 case NestedNameSpecifier::NamespaceAlias: {
3672 NamespaceAliasDecl *Alias
3673 = cast_or_null<NamespaceAliasDecl>(
3674 getDerived().TransformDecl(Q.getLocalBeginLoc(),
3675 QNNS->getAsNamespaceAlias()));
3676 SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3677 Q.getLocalEndLoc());
3678 break;
3679 }
3680
3681 case NestedNameSpecifier::Global:
3682 // There is no meaningful transformation that one could perform on the
3683 // global scope.
3684 SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3685 break;
3686
3687 case NestedNameSpecifier::Super: {
3688 CXXRecordDecl *RD =
3689 cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3690 SourceLocation(), QNNS->getAsRecordDecl()));
3691 SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3692 break;
3693 }
3694
3695 case NestedNameSpecifier::TypeSpecWithTemplate:
3696 case NestedNameSpecifier::TypeSpec: {
3697 TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3698 FirstQualifierInScope, SS);
3699
3700 if (!TL)
3701 return NestedNameSpecifierLoc();
3702
3703 if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3704 (SemaRef.getLangOpts().CPlusPlus11 &&
3705 TL.getType()->isEnumeralType())) {
3706 assert(!TL.getType().hasLocalQualifiers() &&((!TL.getType().hasLocalQualifiers() && "Can't get cv-qualifiers here"
) ? static_cast<void> (0) : __assert_fail ("!TL.getType().hasLocalQualifiers() && \"Can't get cv-qualifiers here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 3707, __PRETTY_FUNCTION__))
3707 "Can't get cv-qualifiers here")((!TL.getType().hasLocalQualifiers() && "Can't get cv-qualifiers here"
) ? static_cast<void> (0) : __assert_fail ("!TL.getType().hasLocalQualifiers() && \"Can't get cv-qualifiers here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 3707, __PRETTY_FUNCTION__))
;
3708 if (TL.getType()->isEnumeralType())
3709 SemaRef.Diag(TL.getBeginLoc(),
3710 diag::warn_cxx98_compat_enum_nested_name_spec);
3711 SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3712 Q.getLocalEndLoc());
3713 break;
3714 }
3715 // If the nested-name-specifier is an invalid type def, don't emit an
3716 // error because a previous error should have already been emitted.
3717 TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3718 if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3719 SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3720 << TL.getType() << SS.getRange();
3721 }
3722 return NestedNameSpecifierLoc();
3723 }
3724 }
3725
3726 // The qualifier-in-scope and object type only apply to the leftmost entity.
3727 FirstQualifierInScope = nullptr;
3728 ObjectType = QualType();
3729 }
3730
3731 // Don't rebuild the nested-name-specifier if we don't have to.
3732 if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3733 !getDerived().AlwaysRebuild())
3734 return NNS;
3735
3736 // If we can re-use the source-location data from the original
3737 // nested-name-specifier, do so.
3738 if (SS.location_size() == NNS.getDataLength() &&
3739 memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3740 return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3741
3742 // Allocate new nested-name-specifier location information.
3743 return SS.getWithLocInContext(SemaRef.Context);
3744}
3745
3746template<typename Derived>
3747DeclarationNameInfo
3748TreeTransform<Derived>
3749::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3750 DeclarationName Name = NameInfo.getName();
3751 if (!Name)
3752 return DeclarationNameInfo();
3753
3754 switch (Name.getNameKind()) {
3755 case DeclarationName::Identifier:
3756 case DeclarationName::ObjCZeroArgSelector:
3757 case DeclarationName::ObjCOneArgSelector:
3758 case DeclarationName::ObjCMultiArgSelector:
3759 case DeclarationName::CXXOperatorName:
3760 case DeclarationName::CXXLiteralOperatorName:
3761 case DeclarationName::CXXUsingDirective:
3762 return NameInfo;
3763
3764 case DeclarationName::CXXDeductionGuideName: {
3765 TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
3766 TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
3767 getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
3768 if (!NewTemplate)
3769 return DeclarationNameInfo();
3770
3771 DeclarationNameInfo NewNameInfo(NameInfo);
3772 NewNameInfo.setName(
3773 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
3774 return NewNameInfo;
3775 }
3776
3777 case DeclarationName::CXXConstructorName:
3778 case DeclarationName::CXXDestructorName:
3779 case DeclarationName::CXXConversionFunctionName: {
3780 TypeSourceInfo *NewTInfo;
3781 CanQualType NewCanTy;
3782 if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3783 NewTInfo = getDerived().TransformType(OldTInfo);
3784 if (!NewTInfo)
3785 return DeclarationNameInfo();
3786 NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3787 }
3788 else {
3789 NewTInfo = nullptr;
3790 TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3791 QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3792 if (NewT.isNull())
3793 return DeclarationNameInfo();
3794 NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3795 }
3796
3797 DeclarationName NewName
3798 = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3799 NewCanTy);
3800 DeclarationNameInfo NewNameInfo(NameInfo);
3801 NewNameInfo.setName(NewName);
3802 NewNameInfo.setNamedTypeInfo(NewTInfo);
3803 return NewNameInfo;
3804 }
3805 }
3806
3807 llvm_unreachable("Unknown name kind.")::llvm::llvm_unreachable_internal("Unknown name kind.", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 3807)
;
3808}
3809
3810template<typename Derived>
3811TemplateName
3812TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3813 TemplateName Name,
3814 SourceLocation NameLoc,
3815 QualType ObjectType,
3816 NamedDecl *FirstQualifierInScope,
3817 bool AllowInjectedClassName) {
3818 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3819 TemplateDecl *Template = QTN->getTemplateDecl();
3820 assert(Template && "qualified template name must refer to a template")((Template && "qualified template name must refer to a template"
) ? static_cast<void> (0) : __assert_fail ("Template && \"qualified template name must refer to a template\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 3820, __PRETTY_FUNCTION__))
;
3821
3822 TemplateDecl *TransTemplate
3823 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3824 Template));
3825 if (!TransTemplate)
3826 return TemplateName();
3827
3828 if (!getDerived().AlwaysRebuild() &&
3829 SS.getScopeRep() == QTN->getQualifier() &&
3830 TransTemplate == Template)
3831 return Name;
3832
3833 return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3834 TransTemplate);
3835 }
3836
3837 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3838 if (SS.getScopeRep()) {
3839 // These apply to the scope specifier, not the template.
3840 ObjectType = QualType();
3841 FirstQualifierInScope = nullptr;
3842 }
3843
3844 if (!getDerived().AlwaysRebuild() &&
3845 SS.getScopeRep() == DTN->getQualifier() &&
3846 ObjectType.isNull())
3847 return Name;
3848
3849 // FIXME: Preserve the location of the "template" keyword.
3850 SourceLocation TemplateKWLoc = NameLoc;
3851
3852 if (DTN->isIdentifier()) {
3853 return getDerived().RebuildTemplateName(SS,
3854 TemplateKWLoc,
3855 *DTN->getIdentifier(),
3856 NameLoc,
3857 ObjectType,
3858 FirstQualifierInScope,
3859 AllowInjectedClassName);
3860 }
3861
3862 return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
3863 DTN->getOperator(), NameLoc,
3864 ObjectType, AllowInjectedClassName);
3865 }
3866
3867 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3868 TemplateDecl *TransTemplate
3869 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3870 Template));
3871 if (!TransTemplate)
3872 return TemplateName();
3873
3874 if (!getDerived().AlwaysRebuild() &&
3875 TransTemplate == Template)
3876 return Name;
3877
3878 return TemplateName(TransTemplate);
3879 }
3880
3881 if (SubstTemplateTemplateParmPackStorage *SubstPack
3882 = Name.getAsSubstTemplateTemplateParmPack()) {
3883 TemplateTemplateParmDecl *TransParam
3884 = cast_or_null<TemplateTemplateParmDecl>(
3885 getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3886 if (!TransParam)
3887 return TemplateName();
3888
3889 if (!getDerived().AlwaysRebuild() &&
3890 TransParam == SubstPack->getParameterPack())
3891 return Name;
3892
3893 return getDerived().RebuildTemplateName(TransParam,
3894 SubstPack->getArgumentPack());
3895 }
3896
3897 // These should be getting filtered out before they reach the AST.
3898 llvm_unreachable("overloaded function decl survived to here")::llvm::llvm_unreachable_internal("overloaded function decl survived to here"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 3898)
;
3899}
3900
3901template<typename Derived>
3902void TreeTransform<Derived>::InventTemplateArgumentLoc(
3903 const TemplateArgument &Arg,
3904 TemplateArgumentLoc &Output) {
3905 SourceLocation Loc = getDerived().getBaseLocation();
3906 switch (Arg.getKind()) {
3907 case TemplateArgument::Null:
3908 llvm_unreachable("null template argument in TreeTransform")::llvm::llvm_unreachable_internal("null template argument in TreeTransform"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 3908)
;
3909 break;
3910
3911 case TemplateArgument::Type:
3912 Output = TemplateArgumentLoc(Arg,
3913 SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3914
3915 break;
3916
3917 case TemplateArgument::Template:
3918 case TemplateArgument::TemplateExpansion: {
3919 NestedNameSpecifierLocBuilder Builder;
3920 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
3921 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3922 Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3923 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3924 Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3925
3926 if (Arg.getKind() == TemplateArgument::Template)
3927 Output = TemplateArgumentLoc(Arg,
3928 Builder.getWithLocInContext(SemaRef.Context),
3929 Loc);
3930 else
3931 Output = TemplateArgumentLoc(Arg,
3932 Builder.getWithLocInContext(SemaRef.Context),
3933 Loc, Loc);
3934
3935 break;
3936 }
3937
3938 case TemplateArgument::Expression:
3939 Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
3940 break;
3941
3942 case TemplateArgument::Declaration:
3943 case TemplateArgument::Integral:
3944 case TemplateArgument::Pack:
3945 case TemplateArgument::NullPtr:
3946 Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
3947 break;
3948 }
3949}
3950
3951template<typename Derived>
3952bool TreeTransform<Derived>::TransformTemplateArgument(
3953 const TemplateArgumentLoc &Input,
3954 TemplateArgumentLoc &Output, bool Uneval) {
3955 const TemplateArgument &Arg = Input.getArgument();
3956 switch (Arg.getKind()) {
3957 case TemplateArgument::Null:
3958 case TemplateArgument::Integral:
3959 case TemplateArgument::Pack:
3960 case TemplateArgument::Declaration:
3961 case TemplateArgument::NullPtr:
3962 llvm_unreachable("Unexpected TemplateArgument")::llvm::llvm_unreachable_internal("Unexpected TemplateArgument"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 3962)
;
3963
3964 case TemplateArgument::Type: {
3965 TypeSourceInfo *DI = Input.getTypeSourceInfo();
3966 if (!DI)
3967 DI = InventTypeSourceInfo(Input.getArgument().getAsType());
3968
3969 DI = getDerived().TransformType(DI);
3970 if (!DI) return true;
3971
3972 Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3973 return false;
3974 }
3975
3976 case TemplateArgument::Template: {
3977 NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
3978 if (QualifierLoc) {
3979 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
3980 if (!QualifierLoc)
3981 return true;
3982 }
3983
3984 CXXScopeSpec SS;
3985 SS.Adopt(QualifierLoc);
3986 TemplateName Template
3987 = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
3988 Input.getTemplateNameLoc());
3989 if (Template.isNull())
3990 return true;
3991
3992 Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
3993 Input.getTemplateNameLoc());
3994 return false;
3995 }
3996
3997 case TemplateArgument::TemplateExpansion:
3998 llvm_unreachable("Caller should expand pack expansions")::llvm::llvm_unreachable_internal("Caller should expand pack expansions"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 3998)
;
3999
4000 case TemplateArgument::Expression: {
4001 // Template argument expressions are constant expressions.
4002 EnterExpressionEvaluationContext Unevaluated(
4003 getSema(),
4004 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4005 : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4006 /*LambdaContextDecl=*/nullptr, /*ExprContext=*/
4007 Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4008
4009 Expr *InputExpr = Input.getSourceExpression();
4010 if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
4011
4012 ExprResult E = getDerived().TransformExpr(InputExpr);
4013 E = SemaRef.ActOnConstantExpression(E);
4014 if (E.isInvalid()) return true;
4015 Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4016 return false;
4017 }
4018 }
4019
4020 // Work around bogus GCC warning
4021 return true;
4022}
4023
4024/// Iterator adaptor that invents template argument location information
4025/// for each of the template arguments in its underlying iterator.
4026template<typename Derived, typename InputIterator>
4027class TemplateArgumentLocInventIterator {
4028 TreeTransform<Derived> &Self;
4029 InputIterator Iter;
4030
4031public:
4032 typedef TemplateArgumentLoc value_type;
4033 typedef TemplateArgumentLoc reference;
4034 typedef typename std::iterator_traits<InputIterator>::difference_type
4035 difference_type;
4036 typedef std::input_iterator_tag iterator_category;
4037
4038 class pointer {
4039 TemplateArgumentLoc Arg;
4040
4041 public:
4042 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4043
4044 const TemplateArgumentLoc *operator->() const { return &Arg; }
4045 };
4046
4047 TemplateArgumentLocInventIterator() { }
4048
4049 explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4050 InputIterator Iter)
4051 : Self(Self), Iter(Iter) { }
4052
4053 TemplateArgumentLocInventIterator &operator++() {
4054 ++Iter;
4055 return *this;
4056 }
4057
4058 TemplateArgumentLocInventIterator operator++(int) {
4059 TemplateArgumentLocInventIterator Old(*this);
4060 ++(*this);
4061 return Old;
4062 }
4063
4064 reference operator*() const {
4065 TemplateArgumentLoc Result;
4066 Self.InventTemplateArgumentLoc(*Iter, Result);
4067 return Result;
4068 }
4069
4070 pointer operator->() const { return pointer(**this); }
4071
4072 friend bool operator==(const TemplateArgumentLocInventIterator &X,
4073 const TemplateArgumentLocInventIterator &Y) {
4074 return X.Iter == Y.Iter;
4075 }
4076
4077 friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4078 const TemplateArgumentLocInventIterator &Y) {
4079 return X.Iter != Y.Iter;
4080 }
4081};
4082
4083template<typename Derived>
4084template<typename InputIterator>
4085bool TreeTransform<Derived>::TransformTemplateArguments(
4086 InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4087 bool Uneval) {
4088 for (; First != Last; ++First) {
4089 TemplateArgumentLoc Out;
4090 TemplateArgumentLoc In = *First;
4091
4092 if (In.getArgument().getKind() == TemplateArgument::Pack) {
4093 // Unpack argument packs, which we translate them into separate
4094 // arguments.
4095 // FIXME: We could do much better if we could guarantee that the
4096 // TemplateArgumentLocInfo for the pack expansion would be usable for
4097 // all of the template arguments in the argument pack.
4098 typedef TemplateArgumentLocInventIterator<Derived,
4099 TemplateArgument::pack_iterator>
4100 PackLocIterator;
4101 if (TransformTemplateArguments(PackLocIterator(*this,
4102 In.getArgument().pack_begin()),
4103 PackLocIterator(*this,
4104 In.getArgument().pack_end()),
4105 Outputs, Uneval))
4106 return true;
4107
4108 continue;
4109 }
4110
4111 if (In.getArgument().isPackExpansion()) {
4112 // We have a pack expansion, for which we will be substituting into
4113 // the pattern.
4114 SourceLocation Ellipsis;
4115 Optional<unsigned> OrigNumExpansions;
4116 TemplateArgumentLoc Pattern
4117 = getSema().getTemplateArgumentPackExpansionPattern(
4118 In, Ellipsis, OrigNumExpansions);
4119
4120 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4121 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4122 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")((!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? static_cast<void> (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 4122, __PRETTY_FUNCTION__))
;
4123
4124 // Determine whether the set of unexpanded parameter packs can and should
4125 // be expanded.
4126 bool Expand = true;
4127 bool RetainExpansion = false;
4128 Optional<unsigned> NumExpansions = OrigNumExpansions;
4129 if (getDerived().TryExpandParameterPacks(Ellipsis,
4130 Pattern.getSourceRange(),
4131 Unexpanded,
4132 Expand,
4133 RetainExpansion,
4134 NumExpansions))
4135 return true;
4136
4137 if (!Expand) {
4138 // The transform has determined that we should perform a simple
4139 // transformation on the pack expansion, producing another pack
4140 // expansion.
4141 TemplateArgumentLoc OutPattern;
4142 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4143 if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4144 return true;
4145
4146 Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4147 NumExpansions);
4148 if (Out.getArgument().isNull())
4149 return true;
4150
4151 Outputs.addArgument(Out);
4152 continue;
4153 }
4154
4155 // The transform has determined that we should perform an elementwise
4156 // expansion of the pattern. Do so.
4157 for (unsigned I = 0; I != *NumExpansions; ++I) {
4158 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4159
4160 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4161 return true;
4162
4163 if (Out.getArgument().containsUnexpandedParameterPack()) {
4164 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4165 OrigNumExpansions);
4166 if (Out.getArgument().isNull())
4167 return true;
4168 }
4169
4170 Outputs.addArgument(Out);
4171 }
4172
4173 // If we're supposed to retain a pack expansion, do so by temporarily
4174 // forgetting the partially-substituted parameter pack.
4175 if (RetainExpansion) {
4176 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4177
4178 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4179 return true;
4180
4181 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4182 OrigNumExpansions);
4183 if (Out.getArgument().isNull())
4184 return true;
4185
4186 Outputs.addArgument(Out);
4187 }
4188
4189 continue;
4190 }
4191
4192 // The simple case:
4193 if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4194 return true;
4195
4196 Outputs.addArgument(Out);
4197 }
4198
4199 return false;
4200
4201}
4202
4203//===----------------------------------------------------------------------===//
4204// Type transformation
4205//===----------------------------------------------------------------------===//
4206
4207template<typename Derived>
4208QualType TreeTransform<Derived>::TransformType(QualType T) {
4209 if (getDerived().AlreadyTransformed(T))
4210 return T;
4211
4212 // Temporary workaround. All of these transformations should
4213 // eventually turn into transformations on TypeLocs.
4214 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4215 getDerived().getBaseLocation());
4216
4217 TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4218
4219 if (!NewDI)
4220 return QualType();
4221
4222 return NewDI->getType();
4223}
4224
4225template<typename Derived>
4226TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4227 // Refine the base location to the type's location.
4228 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4229 getDerived().getBaseEntity());
4230 if (getDerived().AlreadyTransformed(DI->getType()))
4231 return DI;
4232
4233 TypeLocBuilder TLB;
4234
4235 TypeLoc TL = DI->getTypeLoc();
4236 TLB.reserve(TL.getFullDataSize());
4237
4238 QualType Result = getDerived().TransformType(TLB, TL);
4239 if (Result.isNull())
4240 return nullptr;
4241
4242 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4243}
4244
4245template<typename Derived>
4246QualType
4247TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4248 switch (T.getTypeLocClass()) {
2
Control jumps to 'case VariableArray:' at line 72
5
Control jumps to 'case RValueReference:' at line 59
4249#define ABSTRACT_TYPELOC(CLASS, PARENT)
4250#define TYPELOC(CLASS, PARENT) \
4251 case TypeLoc::CLASS: \
4252 return getDerived().Transform##CLASS##Type(TLB, \
4253 T.castAs<CLASS##TypeLoc>());
4254#include "clang/AST/TypeLocNodes.def"
4255 }
4256
4257 llvm_unreachable("unhandled type loc!")::llvm::llvm_unreachable_internal("unhandled type loc!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 4257)
;
4258}
4259
4260template<typename Derived>
4261QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4262 if (!isa<DependentNameType>(T))
4263 return TransformType(T);
4264
4265 if (getDerived().AlreadyTransformed(T))
4266 return T;
4267 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4268 getDerived().getBaseLocation());
4269 TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4270 return NewDI ? NewDI->getType() : QualType();
4271}
4272
4273template<typename Derived>
4274TypeSourceInfo *
4275TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4276 if (!isa<DependentNameType>(DI->getType()))
4277 return TransformType(DI);
4278
4279 // Refine the base location to the type's location.
4280 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4281 getDerived().getBaseEntity());
4282 if (getDerived().AlreadyTransformed(DI->getType()))
4283 return DI;
4284
4285 TypeLocBuilder TLB;
4286
4287 TypeLoc TL = DI->getTypeLoc();
4288 TLB.reserve(TL.getFullDataSize());
4289
4290 auto QTL = TL.getAs<QualifiedTypeLoc>();
4291 if (QTL)
4292 TL = QTL.getUnqualifiedLoc();
4293
4294 auto DNTL = TL.castAs<DependentNameTypeLoc>();
4295
4296 QualType Result = getDerived().TransformDependentNameType(
4297 TLB, DNTL, /*DeducedTSTContext*/true);
4298 if (Result.isNull())
4299 return nullptr;
4300
4301 if (QTL) {
4302 Result = getDerived().RebuildQualifiedType(Result, QTL);
4303 if (Result.isNull())
4304 return nullptr;
4305 TLB.TypeWasModifiedSafely(Result);
4306 }
4307
4308 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4309}
4310
4311template<typename Derived>
4312QualType
4313TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4314 QualifiedTypeLoc T) {
4315 QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4316 if (Result.isNull())
4317 return QualType();
4318
4319 Result = getDerived().RebuildQualifiedType(Result, T);
4320
4321 if (Result.isNull())
4322 return QualType();
4323
4324 // RebuildQualifiedType might have updated the type, but not in a way
4325 // that invalidates the TypeLoc. (There's no location information for
4326 // qualifiers.)
4327 TLB.TypeWasModifiedSafely(Result);
4328
4329 return Result;
4330}
4331
4332template <typename Derived>
4333QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4334 QualifiedTypeLoc TL) {
4335
4336 SourceLocation Loc = TL.getBeginLoc();
4337 Qualifiers Quals = TL.getType().getLocalQualifiers();
4338
4339 if (((T.getAddressSpace() != LangAS::Default &&
4340 Quals.getAddressSpace() != LangAS::Default)) &&
4341 T.getAddressSpace() != Quals.getAddressSpace()) {
4342 SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4343 << TL.getType() << T;
4344 return QualType();
4345 }
4346
4347 // C++ [dcl.fct]p7:
4348 // [When] adding cv-qualifications on top of the function type [...] the
4349 // cv-qualifiers are ignored.
4350 if (T->isFunctionType()) {
4351 T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4352 Quals.getAddressSpace());
4353 return T;
4354 }
4355
4356 // C++ [dcl.ref]p1:
4357 // when the cv-qualifiers are introduced through the use of a typedef-name
4358 // or decltype-specifier [...] the cv-qualifiers are ignored.
4359 // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4360 // applied to a reference type.
4361 if (T->isReferenceType()) {
4362 // The only qualifier that applies to a reference type is restrict.
4363 if (!Quals.hasRestrict())
4364 return T;
4365 Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4366 }
4367
4368 // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4369 // resulting type.
4370 if (Quals.hasObjCLifetime()) {
4371 if (!T->isObjCLifetimeType() && !T->isDependentType())
4372 Quals.removeObjCLifetime();
4373 else if (T.getObjCLifetime()) {
4374 // Objective-C ARC:
4375 // A lifetime qualifier applied to a substituted template parameter
4376 // overrides the lifetime qualifier from the template argument.
4377 const AutoType *AutoTy;
4378 if (const SubstTemplateTypeParmType *SubstTypeParam
4379 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4380 QualType Replacement = SubstTypeParam->getReplacementType();
4381 Qualifiers Qs = Replacement.getQualifiers();
4382 Qs.removeObjCLifetime();
4383 Replacement = SemaRef.Context.getQualifiedType(
4384 Replacement.getUnqualifiedType(), Qs);
4385 T = SemaRef.Context.getSubstTemplateTypeParmType(
4386 SubstTypeParam->getReplacedParameter(), Replacement);
4387 } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4388 // 'auto' types behave the same way as template parameters.
4389 QualType Deduced = AutoTy->getDeducedType();
4390 Qualifiers Qs = Deduced.getQualifiers();
4391 Qs.removeObjCLifetime();
4392 Deduced =
4393 SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4394 T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4395 AutoTy->isDependentType());
4396 } else {
4397 // Otherwise, complain about the addition of a qualifier to an
4398 // already-qualified type.
4399 // FIXME: Why is this check not in Sema::BuildQualifiedType?
4400 SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4401 Quals.removeObjCLifetime();
4402 }
4403 }
4404 }
4405
4406 return SemaRef.BuildQualifiedType(T, Loc, Quals);
4407}
4408
4409template<typename Derived>
4410TypeLoc
4411TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4412 QualType ObjectType,
4413 NamedDecl *UnqualLookup,
4414 CXXScopeSpec &SS) {
4415 if (getDerived().AlreadyTransformed(TL.getType()))
4416 return TL;
4417
4418 TypeSourceInfo *TSI =
4419 TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4420 if (TSI)
4421 return TSI->getTypeLoc();
4422 return TypeLoc();
4423}
4424
4425template<typename Derived>
4426TypeSourceInfo *
4427TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4428 QualType ObjectType,
4429 NamedDecl *UnqualLookup,
4430 CXXScopeSpec &SS) {
4431 if (getDerived().AlreadyTransformed(TSInfo->getType()))
4432 return TSInfo;
4433
4434 return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4435 UnqualLookup, SS);
4436}
4437
4438template <typename Derived>
4439TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4440 TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4441 CXXScopeSpec &SS) {
4442 QualType T = TL.getType();
4443 assert(!getDerived().AlreadyTransformed(T))((!getDerived().AlreadyTransformed(T)) ? static_cast<void>
(0) : __assert_fail ("!getDerived().AlreadyTransformed(T)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 4443, __PRETTY_FUNCTION__))
;
4444
4445 TypeLocBuilder TLB;
4446 QualType Result;
4447
4448 if (isa<TemplateSpecializationType>(T)) {
4449 TemplateSpecializationTypeLoc SpecTL =
4450 TL.castAs<TemplateSpecializationTypeLoc>();
4451
4452 TemplateName Template = getDerived().TransformTemplateName(
4453 SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4454 ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4455 if (Template.isNull())
4456 return nullptr;
4457
4458 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4459 Template);
4460 } else if (isa<DependentTemplateSpecializationType>(T)) {
4461 DependentTemplateSpecializationTypeLoc SpecTL =
4462 TL.castAs<DependentTemplateSpecializationTypeLoc>();
4463
4464 TemplateName Template
4465 = getDerived().RebuildTemplateName(SS,
4466 SpecTL.getTemplateKeywordLoc(),
4467 *SpecTL.getTypePtr()->getIdentifier(),
4468 SpecTL.getTemplateNameLoc(),
4469 ObjectType, UnqualLookup,
4470 /*AllowInjectedClassName*/true);
4471 if (Template.isNull())
4472 return nullptr;
4473
4474 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4475 SpecTL,
4476 Template,
4477 SS);
4478 } else {
4479 // Nothing special needs to be done for these.
4480 Result = getDerived().TransformType(TLB, TL);
4481 }
4482
4483 if (Result.isNull())
4484 return nullptr;
4485
4486 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4487}
4488
4489template <class TyLoc> static inline
4490QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4491 TyLoc NewT = TLB.push<TyLoc>(T.getType());
4492 NewT.setNameLoc(T.getNameLoc());
4493 return T.getType();
4494}
4495
4496template<typename Derived>
4497QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4498 BuiltinTypeLoc T) {
4499 BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4500 NewT.setBuiltinLoc(T.getBuiltinLoc());
4501 if (T.needsExtraLocalData())
4502 NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4503 return T.getType();
4504}
4505
4506template<typename Derived>
4507QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4508 ComplexTypeLoc T) {
4509 // FIXME: recurse?
4510 return TransformTypeSpecType(TLB, T);
4511}
4512
4513template <typename Derived>
4514QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4515 AdjustedTypeLoc TL) {
4516 // Adjustments applied during transformation are handled elsewhere.
4517 return getDerived().TransformType(TLB, TL.getOriginalLoc());
4518}
4519
4520template<typename Derived>
4521QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4522 DecayedTypeLoc TL) {
4523 QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4524 if (OriginalType.isNull())
4525 return QualType();
4526
4527 QualType Result = TL.getType();
4528 if (getDerived().AlwaysRebuild() ||
4529 OriginalType != TL.getOriginalLoc().getType())
4530 Result = SemaRef.Context.getDecayedType(OriginalType);
4531 TLB.push<DecayedTypeLoc>(Result);
4532 // Nothing to set for DecayedTypeLoc.
4533 return Result;
4534}
4535
4536/// Helper to deduce addr space of a pointee type in OpenCL mode.
4537/// If the type is updated it will be overwritten in PointeeType param.
4538static void deduceOpenCLPointeeAddrSpace(Sema &SemaRef, QualType &PointeeType) {
4539 if (PointeeType.getAddressSpace() == LangAS::Default)
4540 PointeeType = SemaRef.Context.getAddrSpaceQualType(PointeeType,
4541 LangAS::opencl_generic);
4542}
4543
4544template<typename Derived>
4545QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4546 PointerTypeLoc TL) {
4547 QualType PointeeType
4548 = getDerived().TransformType(TLB, TL.getPointeeLoc());
4549 if (PointeeType.isNull())
4550 return QualType();
4551
4552 if (SemaRef.getLangOpts().OpenCL)
4553 deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
4554
4555 QualType Result = TL.getType();
4556 if (PointeeType->getAs<ObjCObjectType>()) {
4557 // A dependent pointer type 'T *' has is being transformed such
4558 // that an Objective-C class type is being replaced for 'T'. The
4559 // resulting pointer type is an ObjCObjectPointerType, not a
4560 // PointerType.
4561 Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4562
4563 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4564 NewT.setStarLoc(TL.getStarLoc());
4565 return Result;
4566 }
4567
4568 if (getDerived().AlwaysRebuild() ||
4569 PointeeType != TL.getPointeeLoc().getType()) {
4570 Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
4571 if (Result.isNull())
4572 return QualType();
4573 }
4574
4575 // Objective-C ARC can add lifetime qualifiers to the type that we're
4576 // pointing to.
4577 TLB.TypeWasModifiedSafely(Result->getPointeeType());
4578
4579 PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
4580 NewT.setSigilLoc(TL.getSigilLoc());
4581 return Result;
4582}
4583
4584template<typename Derived>
4585QualType
4586TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4587 BlockPointerTypeLoc TL) {
4588 QualType PointeeType
4589 = getDerived().TransformType(TLB, TL.getPointeeLoc());
4590 if (PointeeType.isNull())
4591 return QualType();
4592
4593 if (SemaRef.getLangOpts().OpenCL)
4594 deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
4595
4596 QualType Result = TL.getType();
4597 if (getDerived().AlwaysRebuild() ||
4598 PointeeType != TL.getPointeeLoc().getType()) {
4599 Result = getDerived().RebuildBlockPointerType(PointeeType,
4600 TL.getSigilLoc());
4601 if (Result.isNull())
4602 return QualType();
4603 }
4604
4605 BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4606 NewT.setSigilLoc(TL.getSigilLoc());
4607 return Result;
4608}
4609
4610/// Transforms a reference type. Note that somewhat paradoxically we
4611/// don't care whether the type itself is an l-value type or an r-value
4612/// type; we only care if the type was *written* as an l-value type
4613/// or an r-value type.
4614template<typename Derived>
4615QualType
4616TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4617 ReferenceTypeLoc TL) {
4618 const ReferenceType *T = TL.getTypePtr();
4619
4620 // Note that this works with the pointee-as-written.
4621 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4622 if (PointeeType.isNull())
8
Calling 'QualType::isNull'
14
Returning from 'QualType::isNull'
15
Taking false branch
4623 return QualType();
4624
4625 if (SemaRef.getLangOpts().OpenCL)
16
Assuming field 'OpenCL' is 0
17
Taking false branch
4626 deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
4627
4628 QualType Result = TL.getType();
4629 if (getDerived().AlwaysRebuild() ||
18
Taking false branch
4630 PointeeType != T->getPointeeTypeAsWritten()) {
4631 Result = getDerived().RebuildReferenceType(PointeeType,
4632 T->isSpelledAsLValue(),
4633 TL.getSigilLoc());
4634 if (Result.isNull())
4635 return QualType();
4636 }
4637
4638 // Objective-C ARC can add lifetime qualifiers to the type that we're
4639 // referring to.
4640 TLB.TypeWasModifiedSafely(
4641 Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
19
Assuming the object is not a 'ReferenceType'
20
Called C++ object pointer is null
4642
4643 // r-value references can be rebuilt as l-value references.
4644 ReferenceTypeLoc NewTL;
4645 if (isa<LValueReferenceType>(Result))
4646 NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4647 else
4648 NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4649 NewTL.setSigilLoc(TL.getSigilLoc());
4650
4651 return Result;
4652}
4653
4654template<typename Derived>
4655QualType
4656TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4657 LValueReferenceTypeLoc TL) {
4658 return TransformReferenceType(TLB, TL);
4659}
4660
4661template<typename Derived>
4662QualType
4663TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4664 RValueReferenceTypeLoc TL) {
4665 return TransformReferenceType(TLB, TL);
7
Calling 'TreeTransform::TransformReferenceType'
4666}
4667
4668template<typename Derived>
4669QualType
4670TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4671 MemberPointerTypeLoc TL) {
4672 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4673 if (PointeeType.isNull())
4674 return QualType();
4675
4676 TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4677 TypeSourceInfo *NewClsTInfo = nullptr;
4678 if (OldClsTInfo) {
4679 NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4680 if (!NewClsTInfo)
4681 return QualType();
4682 }
4683
4684 const MemberPointerType *T = TL.getTypePtr();
4685 QualType OldClsType = QualType(T->getClass(), 0);
4686 QualType NewClsType;
4687 if (NewClsTInfo)
4688 NewClsType = NewClsTInfo->getType();
4689 else {
4690 NewClsType = getDerived().TransformType(OldClsType);
4691 if (NewClsType.isNull())
4692 return QualType();
4693 }
4694
4695 QualType Result = TL.getType();
4696 if (getDerived().AlwaysRebuild() ||
4697 PointeeType != T->getPointeeType() ||
4698 NewClsType != OldClsType) {
4699 Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4700 TL.getStarLoc());
4701 if (Result.isNull())
4702 return QualType();
4703 }
4704
4705 // If we had to adjust the pointee type when building a member pointer, make
4706 // sure to push TypeLoc info for it.
4707 const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4708 if (MPT && PointeeType != MPT->getPointeeType()) {
4709 assert(isa<AdjustedType>(MPT->getPointeeType()))((isa<AdjustedType>(MPT->getPointeeType())) ? static_cast
<void> (0) : __assert_fail ("isa<AdjustedType>(MPT->getPointeeType())"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 4709, __PRETTY_FUNCTION__))
;
4710 TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4711 }
4712
4713 MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4714 NewTL.setSigilLoc(TL.getSigilLoc());
4715 NewTL.setClassTInfo(NewClsTInfo);
4716
4717 return Result;
4718}
4719
4720template<typename Derived>
4721QualType
4722TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4723 ConstantArrayTypeLoc TL) {
4724 const ConstantArrayType *T = TL.getTypePtr();
4725 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4726 if (ElementType.isNull())
4727 return QualType();
4728
4729 QualType Result = TL.getType();
4730 if (getDerived().AlwaysRebuild() ||
4731 ElementType != T->getElementType()) {
4732 Result = getDerived().RebuildConstantArrayType(ElementType,
4733 T->getSizeModifier(),
4734 T->getSize(),
4735 T->getIndexTypeCVRQualifiers(),
4736 TL.getBracketsRange());
4737 if (Result.isNull())
4738 return QualType();
4739 }
4740
4741 // We might have either a ConstantArrayType or a VariableArrayType now:
4742 // a ConstantArrayType is allowed to have an element type which is a
4743 // VariableArrayType if the type is dependent. Fortunately, all array
4744 // types have the same location layout.
4745 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4746 NewTL.setLBracketLoc(TL.getLBracketLoc());
4747 NewTL.setRBracketLoc(TL.getRBracketLoc());
4748
4749 Expr *Size = TL.getSizeExpr();
4750 if (Size) {
4751 EnterExpressionEvaluationContext Unevaluated(
4752 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4753 Size = getDerived().TransformExpr(Size).template getAs<Expr>();
4754 Size = SemaRef.ActOnConstantExpression(Size).get();
4755 }
4756 NewTL.setSizeExpr(Size);
4757
4758 return Result;
4759}
4760
4761template<typename Derived>
4762QualType TreeTransform<Derived>::TransformIncompleteArrayType(
4763 TypeLocBuilder &TLB,
4764 IncompleteArrayTypeLoc TL) {
4765 const IncompleteArrayType *T = TL.getTypePtr();
4766 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4767 if (ElementType.isNull())
4768 return QualType();
4769
4770 QualType Result = TL.getType();
4771 if (getDerived().AlwaysRebuild() ||
4772 ElementType != T->getElementType()) {
4773 Result = getDerived().RebuildIncompleteArrayType(ElementType,
4774 T->getSizeModifier(),
4775 T->getIndexTypeCVRQualifiers(),
4776 TL.getBracketsRange());
4777 if (Result.isNull())
4778 return QualType();
4779 }
4780
4781 IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
4782 NewTL.setLBracketLoc(TL.getLBracketLoc());
4783 NewTL.setRBracketLoc(TL.getRBracketLoc());
4784 NewTL.setSizeExpr(nullptr);
4785
4786 return Result;
4787}
4788
4789template<typename Derived>
4790QualType
4791TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
4792 VariableArrayTypeLoc TL) {
4793 const VariableArrayType *T = TL.getTypePtr();
4794 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4
Calling 'TreeTransform::TransformType'
4795 if (ElementType.isNull())
4796 return QualType();
4797
4798 ExprResult SizeResult;
4799 {
4800 EnterExpressionEvaluationContext Context(
4801 SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4802 SizeResult = getDerived().TransformExpr(T->getSizeExpr());
4803 }
4804 if (SizeResult.isInvalid())
4805 return QualType();
4806 SizeResult =
4807 SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
4808 if (SizeResult.isInvalid())
4809 return QualType();
4810
4811 Expr *Size = SizeResult.get();
4812
4813 QualType Result = TL.getType();
4814 if (getDerived().AlwaysRebuild() ||
4815 ElementType != T->getElementType() ||
4816 Size != T->getSizeExpr()) {
4817 Result = getDerived().RebuildVariableArrayType(ElementType,
4818 T->getSizeModifier(),
4819 Size,
4820 T->getIndexTypeCVRQualifiers(),
4821 TL.getBracketsRange());
4822 if (Result.isNull())
4823 return QualType();
4824 }
4825
4826 // We might have constant size array now, but fortunately it has the same
4827 // location layout.
4828 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4829 NewTL.setLBracketLoc(TL.getLBracketLoc());
4830 NewTL.setRBracketLoc(TL.getRBracketLoc());
4831 NewTL.setSizeExpr(Size);
4832
4833 return Result;
4834}
4835
4836template<typename Derived>
4837QualType
4838TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
4839 DependentSizedArrayTypeLoc TL) {
4840 const DependentSizedArrayType *T = TL.getTypePtr();
4841 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4842 if (ElementType.isNull())
4843 return QualType();
4844
4845 // Array bounds are constant expressions.
4846 EnterExpressionEvaluationContext Unevaluated(
4847 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4848
4849 // Prefer the expression from the TypeLoc; the other may have been uniqued.
4850 Expr *origSize = TL.getSizeExpr();
4851 if (!origSize) origSize = T->getSizeExpr();
4852
4853 ExprResult sizeResult
4854 = getDerived().TransformExpr(origSize);
4855 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
4856 if (sizeResult.isInvalid())
4857 return QualType();
4858
4859 Expr *size = sizeResult.get();
4860
4861 QualType Result = TL.getType();
4862 if (getDerived().AlwaysRebuild() ||
4863 ElementType != T->getElementType() ||
4864 size != origSize) {
4865 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
4866 T->getSizeModifier(),
4867 size,
4868 T->getIndexTypeCVRQualifiers(),
4869 TL.getBracketsRange());
4870 if (Result.isNull())
4871 return QualType();
4872 }
4873
4874 // We might have any sort of array type now, but fortunately they
4875 // all have the same location layout.
4876 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4877 NewTL.setLBracketLoc(TL.getLBracketLoc());
4878 NewTL.setRBracketLoc(TL.getRBracketLoc());
4879 NewTL.setSizeExpr(size);
4880
4881 return Result;
4882}
4883
4884template <typename Derived>
4885QualType TreeTransform<Derived>::TransformDependentVectorType(
4886 TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
4887 const DependentVectorType *T = TL.getTypePtr();
4888 QualType ElementType = getDerived().TransformType(T->getElementType());
4889 if (ElementType.isNull())
4890 return QualType();
4891
4892 EnterExpressionEvaluationContext Unevaluated(
4893 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4894
4895 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4896 Size = SemaRef.ActOnConstantExpression(Size);
4897 if (Size.isInvalid())
4898 return QualType();
4899
4900 QualType Result = TL.getType();
4901 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
4902 Size.get() != T->getSizeExpr()) {
4903 Result = getDerived().RebuildDependentVectorType(
4904 ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
4905 if (Result.isNull())
4906 return QualType();
4907 }
4908
4909 // Result might be dependent or not.
4910 if (isa<DependentVectorType>(Result)) {
4911 DependentVectorTypeLoc NewTL =
4912 TLB.push<DependentVectorTypeLoc>(Result);
4913 NewTL.setNameLoc(TL.getNameLoc());
4914 } else {
4915 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
4916 NewTL.setNameLoc(TL.getNameLoc());
4917 }
4918
4919 return Result;
4920}
4921
4922template<typename Derived>
4923QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
4924 TypeLocBuilder &TLB,
4925 DependentSizedExtVectorTypeLoc TL) {
4926 const DependentSizedExtVectorType *T = TL.getTypePtr();
4927
4928 // FIXME: ext vector locs should be nested
4929 QualType ElementType = getDerived().TransformType(T->getElementType());
4930 if (ElementType.isNull())
4931 return QualType();
4932
4933 // Vector sizes are constant expressions.
4934 EnterExpressionEvaluationContext Unevaluated(
4935 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4936
4937 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4938 Size = SemaRef.ActOnConstantExpression(Size);
4939 if (Size.isInvalid())
4940 return QualType();
4941
4942 QualType Result = TL.getType();
4943 if (getDerived().AlwaysRebuild() ||
4944 ElementType != T->getElementType() ||
4945 Size.get() != T->getSizeExpr()) {
4946 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
4947 Size.get(),
4948 T->getAttributeLoc());
4949 if (Result.isNull())
4950 return QualType();
4951 }
4952
4953 // Result might be dependent or not.
4954 if (isa<DependentSizedExtVectorType>(Result)) {
4955 DependentSizedExtVectorTypeLoc NewTL
4956 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
4957 NewTL.setNameLoc(TL.getNameLoc());
4958 } else {
4959 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4960 NewTL.setNameLoc(TL.getNameLoc());
4961 }
4962
4963 return Result;
4964}
4965
4966template <typename Derived>
4967QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
4968 TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
4969 const DependentAddressSpaceType *T = TL.getTypePtr();
4970
4971 QualType pointeeType = getDerived().TransformType(T->getPointeeType());
4972
4973 if (pointeeType.isNull())
4974 return QualType();
4975
4976 // Address spaces are constant expressions.
4977 EnterExpressionEvaluationContext Unevaluated(
4978 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4979
4980 ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
4981 AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
4982 if (AddrSpace.isInvalid())
4983 return QualType();
4984
4985 QualType Result = TL.getType();
4986 if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
4987 AddrSpace.get() != T->getAddrSpaceExpr()) {
4988 Result = getDerived().RebuildDependentAddressSpaceType(
4989 pointeeType, AddrSpace.get(), T->getAttributeLoc());
4990 if (Result.isNull())
4991 return QualType();
4992 }
4993
4994 // Result might be dependent or not.
4995 if (isa<DependentAddressSpaceType>(Result)) {
4996 DependentAddressSpaceTypeLoc NewTL =
4997 TLB.push<DependentAddressSpaceTypeLoc>(Result);
4998
4999 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5000 NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5001 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5002
5003 } else {
5004 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5005 Result, getDerived().getBaseLocation());
5006 TransformType(TLB, DI->getTypeLoc());
5007 }
5008
5009 return Result;
5010}
5011
5012template <typename Derived>
5013QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5014 VectorTypeLoc TL) {
5015 const VectorType *T = TL.getTypePtr();
5016 QualType ElementType = getDerived().TransformType(T->getElementType());
5017 if (ElementType.isNull())
5018 return QualType();
5019
5020 QualType Result = TL.getType();
5021 if (getDerived().AlwaysRebuild() ||
5022 ElementType != T->getElementType()) {
5023 Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5024 T->getVectorKind());
5025 if (Result.isNull())
5026 return QualType();
5027 }
5028
5029 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5030 NewTL.setNameLoc(TL.getNameLoc());
5031
5032 return Result;
5033}
5034
5035template<typename Derived>
5036QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5037 ExtVectorTypeLoc TL) {
5038 const VectorType *T = TL.getTypePtr();
5039 QualType ElementType = getDerived().TransformType(T->getElementType());
5040 if (ElementType.isNull())
5041 return QualType();
5042
5043 QualType Result = TL.getType();
5044 if (getDerived().AlwaysRebuild() ||
5045 ElementType != T->getElementType()) {
5046 Result = getDerived().RebuildExtVectorType(ElementType,
5047 T->getNumElements(),
5048 /*FIXME*/ SourceLocation());
5049 if (Result.isNull())
5050 return QualType();
5051 }
5052
5053 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5054 NewTL.setNameLoc(TL.getNameLoc());
5055
5056 return Result;
5057}
5058
5059template <typename Derived>
5060ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5061 ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
5062 bool ExpectParameterPack) {
5063 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5064 TypeSourceInfo *NewDI = nullptr;
5065
5066 if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5067 // If we're substituting into a pack expansion type and we know the
5068 // length we want to expand to, just substitute for the pattern.
5069 TypeLoc OldTL = OldDI->getTypeLoc();
5070 PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5071
5072 TypeLocBuilder TLB;
5073 TypeLoc NewTL = OldDI->getTypeLoc();
5074 TLB.reserve(NewTL.getFullDataSize());
5075
5076 QualType Result = getDerived().TransformType(TLB,
5077 OldExpansionTL.getPatternLoc());
5078 if (Result.isNull())
5079 return nullptr;
5080
5081 Result = RebuildPackExpansionType(Result,
5082 OldExpansionTL.getPatternLoc().getSourceRange(),
5083 OldExpansionTL.getEllipsisLoc(),
5084 NumExpansions);
5085 if (Result.isNull())
5086 return nullptr;
5087
5088 PackExpansionTypeLoc NewExpansionTL
5089 = TLB.push<PackExpansionTypeLoc>(Result);
5090 NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5091 NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5092 } else
5093 NewDI = getDerived().TransformType(OldDI);
5094 if (!NewDI)
5095 return nullptr;
5096
5097 if (NewDI == OldDI && indexAdjustment == 0)
5098 return OldParm;
5099
5100 ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5101 OldParm->getDeclContext(),
5102 OldParm->getInnerLocStart(),
5103 OldParm->getLocation(),
5104 OldParm->getIdentifier(),
5105 NewDI->getType(),
5106 NewDI,
5107 OldParm->getStorageClass(),
5108 /* DefArg */ nullptr);
5109 newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5110 OldParm->getFunctionScopeIndex() + indexAdjustment);
5111 return newParm;
5112}
5113
5114template <typename Derived>
5115bool TreeTransform<Derived>::TransformFunctionTypeParams(
5116 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5117 const QualType *ParamTypes,
5118 const FunctionProtoType::ExtParameterInfo *ParamInfos,
5119 SmallVectorImpl<QualType> &OutParamTypes,
5120 SmallVectorImpl<ParmVarDecl *> *PVars,
5121 Sema::ExtParameterInfoBuilder &PInfos) {
5122 int indexAdjustment = 0;
5123
5124 unsigned NumParams = Params.size();
5125 for (unsigned i = 0; i != NumParams; ++i) {
5126 if (ParmVarDecl *OldParm = Params[i]) {
5127 assert(OldParm->getFunctionScopeIndex() == i)((OldParm->getFunctionScopeIndex() == i) ? static_cast<
void> (0) : __assert_fail ("OldParm->getFunctionScopeIndex() == i"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 5127, __PRETTY_FUNCTION__))
;
5128
5129 Optional<unsigned> NumExpansions;
5130 ParmVarDecl *NewParm = nullptr;
5131 if (OldParm->isParameterPack()) {
5132 // We have a function parameter pack that may need to be expanded.
5133 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5134
5135 // Find the parameter packs that could be expanded.
5136 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5137 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5138 TypeLoc Pattern = ExpansionTL.getPatternLoc();
5139 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5140 assert(Unexpanded.size() > 0 && "Could not find parameter packs!")((Unexpanded.size() > 0 && "Could not find parameter packs!"
) ? static_cast<void> (0) : __assert_fail ("Unexpanded.size() > 0 && \"Could not find parameter packs!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 5140, __PRETTY_FUNCTION__))
;
5141
5142 // Determine whether we should expand the parameter packs.
5143 bool ShouldExpand = false;
5144 bool RetainExpansion = false;
5145 Optional<unsigned> OrigNumExpansions =
5146 ExpansionTL.getTypePtr()->getNumExpansions();
5147 NumExpansions = OrigNumExpansions;
5148 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5149 Pattern.getSourceRange(),
5150 Unexpanded,
5151 ShouldExpand,
5152 RetainExpansion,
5153 NumExpansions)) {
5154 return true;
5155 }
5156
5157 if (ShouldExpand) {
5158 // Expand the function parameter pack into multiple, separate
5159 // parameters.
5160 getDerived().ExpandingFunctionParameterPack(OldParm);
5161 for (unsigned I = 0; I != *NumExpansions; ++I) {
5162 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5163 ParmVarDecl *NewParm
5164 = getDerived().TransformFunctionTypeParam(OldParm,
5165 indexAdjustment++,
5166 OrigNumExpansions,
5167 /*ExpectParameterPack=*/false);
5168 if (!NewParm)
5169 return true;
5170
5171 if (ParamInfos)
5172 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5173 OutParamTypes.push_back(NewParm->getType());
5174 if (PVars)
5175 PVars->push_back(NewParm);
5176 }
5177
5178 // If we're supposed to retain a pack expansion, do so by temporarily
5179 // forgetting the partially-substituted parameter pack.
5180 if (RetainExpansion) {
5181 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5182 ParmVarDecl *NewParm
5183 = getDerived().TransformFunctionTypeParam(OldParm,
5184 indexAdjustment++,
5185 OrigNumExpansions,
5186 /*ExpectParameterPack=*/false);
5187 if (!NewParm)
5188 return true;
5189
5190 if (ParamInfos)
5191 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5192 OutParamTypes.push_back(NewParm->getType());
5193 if (PVars)
5194 PVars->push_back(NewParm);
5195 }
5196
5197 // The next parameter should have the same adjustment as the
5198 // last thing we pushed, but we post-incremented indexAdjustment
5199 // on every push. Also, if we push nothing, the adjustment should
5200 // go down by one.
5201 indexAdjustment--;
5202
5203 // We're done with the pack expansion.
5204 continue;
5205 }
5206
5207 // We'll substitute the parameter now without expanding the pack
5208 // expansion.
5209 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5210 NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5211 indexAdjustment,
5212 NumExpansions,
5213 /*ExpectParameterPack=*/true);
5214 } else {
5215 NewParm = getDerived().TransformFunctionTypeParam(
5216 OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
5217 }
5218
5219 if (!NewParm)
5220 return true;
5221
5222 if (ParamInfos)
5223 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5224 OutParamTypes.push_back(NewParm->getType());
5225 if (PVars)
5226 PVars->push_back(NewParm);
5227 continue;
5228 }
5229
5230 // Deal with the possibility that we don't have a parameter
5231 // declaration for this parameter.
5232 QualType OldType = ParamTypes[i];
5233 bool IsPackExpansion = false;
5234 Optional<unsigned> NumExpansions;
5235 QualType NewType;
5236 if (const PackExpansionType *Expansion
5237 = dyn_cast<PackExpansionType>(OldType)) {
5238 // We have a function parameter pack that may need to be expanded.
5239 QualType Pattern = Expansion->getPattern();
5240 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5241 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5242
5243 // Determine whether we should expand the parameter packs.
5244 bool ShouldExpand = false;
5245 bool RetainExpansion = false;
5246 if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5247 Unexpanded,
5248 ShouldExpand,
5249 RetainExpansion,
5250 NumExpansions)) {
5251 return true;
5252 }
5253
5254 if (ShouldExpand) {
5255 // Expand the function parameter pack into multiple, separate
5256 // parameters.
5257 for (unsigned I = 0; I != *NumExpansions; ++I) {
5258 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5259 QualType NewType = getDerived().TransformType(Pattern);
5260 if (NewType.isNull())
5261 return true;
5262
5263 if (NewType->containsUnexpandedParameterPack()) {
5264 NewType =
5265 getSema().getASTContext().getPackExpansionType(NewType, None);
5266
5267 if (NewType.isNull())
5268 return true;
5269 }
5270
5271 if (ParamInfos)
5272 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5273 OutParamTypes.push_back(NewType);
5274 if (PVars)
5275 PVars->push_back(nullptr);
5276 }
5277
5278 // We're done with the pack expansion.
5279 continue;
5280 }
5281
5282 // If we're supposed to retain a pack expansion, do so by temporarily
5283 // forgetting the partially-substituted parameter pack.
5284 if (RetainExpansion) {
5285 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5286 QualType NewType = getDerived().TransformType(Pattern);
5287 if (NewType.isNull())
5288 return true;
5289
5290 if (ParamInfos)
5291 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5292 OutParamTypes.push_back(NewType);
5293 if (PVars)
5294 PVars->push_back(nullptr);
5295 }
5296
5297 // We'll substitute the parameter now without expanding the pack
5298 // expansion.
5299 OldType = Expansion->getPattern();
5300 IsPackExpansion = true;
5301 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5302 NewType = getDerived().TransformType(OldType);
5303 } else {
5304 NewType = getDerived().TransformType(OldType);
5305 }
5306
5307 if (NewType.isNull())
5308 return true;
5309
5310 if (IsPackExpansion)
5311 NewType = getSema().Context.getPackExpansionType(NewType,
5312 NumExpansions);
5313
5314 if (ParamInfos)
5315 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5316 OutParamTypes.push_back(NewType);
5317 if (PVars)
5318 PVars->push_back(nullptr);
5319 }
5320
5321#ifndef NDEBUG
5322 if (PVars) {
5323 for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5324 if (ParmVarDecl *parm = (*PVars)[i])
5325 assert(parm->getFunctionScopeIndex() == i)((parm->getFunctionScopeIndex() == i) ? static_cast<void
> (0) : __assert_fail ("parm->getFunctionScopeIndex() == i"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 5325, __PRETTY_FUNCTION__))
;
5326 }
5327#endif
5328
5329 return false;
5330}
5331
5332template<typename Derived>
5333QualType
5334TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5335 FunctionProtoTypeLoc TL) {
5336 SmallVector<QualType, 4> ExceptionStorage;
5337 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5338 return getDerived().TransformFunctionProtoType(
5339 TLB, TL, nullptr, Qualifiers(),
5340 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5341 return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
5342 ExceptionStorage, Changed);
5343 });
5344}
5345
5346template<typename Derived> template<typename Fn>
5347QualType TreeTransform<Derived>::TransformFunctionProtoType(
5348 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5349 Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
5350
5351 // Transform the parameters and return type.
5352 //
5353 // We are required to instantiate the params and return type in source order.
5354 // When the function has a trailing return type, we instantiate the
5355 // parameters before the return type, since the return type can then refer
5356 // to the parameters themselves (via decltype, sizeof, etc.).
5357 //
5358 SmallVector<QualType, 4> ParamTypes;
5359 SmallVector<ParmVarDecl*, 4> ParamDecls;
5360 Sema::ExtParameterInfoBuilder ExtParamInfos;
5361 const FunctionProtoType *T = TL.getTypePtr();
5362
5363 QualType ResultType;
5364
5365 if (T->hasTrailingReturn()) {
5366 if (getDerived().TransformFunctionTypeParams(
5367 TL.getBeginLoc(), TL.getParams(),
5368 TL.getTypePtr()->param_type_begin(),
5369 T->getExtParameterInfosOrNull(),
5370 ParamTypes, &ParamDecls, ExtParamInfos))
5371 return QualType();
5372
5373 {
5374 // C++11 [expr.prim.general]p3:
5375 // If a declaration declares a member function or member function
5376 // template of a class X, the expression this is a prvalue of type
5377 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5378 // and the end of the function-definition, member-declarator, or
5379 // declarator.
5380 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5381
5382 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5383 if (ResultType.isNull())
5384 return QualType();
5385 }
5386 }
5387 else {
5388 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5389 if (ResultType.isNull())
5390 return QualType();
5391
5392 if (getDerived().TransformFunctionTypeParams(
5393 TL.getBeginLoc(), TL.getParams(),
5394 TL.getTypePtr()->param_type_begin(),
5395 T->getExtParameterInfosOrNull(),
5396 ParamTypes, &ParamDecls, ExtParamInfos))
5397 return QualType();
5398 }
5399
5400 FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5401
5402 bool EPIChanged = false;
5403 if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5404 return QualType();
5405
5406 // Handle extended parameter information.
5407 if (auto NewExtParamInfos =
5408 ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5409 if (!EPI.ExtParameterInfos ||
5410 llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5411 != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5412 EPIChanged = true;
5413 }
5414 EPI.ExtParameterInfos = NewExtParamInfos;
5415 } else if (EPI.ExtParameterInfos) {
5416 EPIChanged = true;
5417 EPI.ExtParameterInfos = nullptr;
5418 }
5419
5420 QualType Result = TL.getType();
5421 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5422 T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5423 Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5424 if (Result.isNull())
5425 return QualType();
5426 }
5427
5428 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5429 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5430 NewTL.setLParenLoc(TL.getLParenLoc());
5431 NewTL.setRParenLoc(TL.getRParenLoc());
5432 NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5433 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5434 for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5435 NewTL.setParam(i, ParamDecls[i]);
5436
5437 return Result;
5438}
5439
5440template<typename Derived>
5441bool TreeTransform<Derived>::TransformExceptionSpec(
5442 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
5443 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
5444 assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated)((ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated
) ? static_cast<void> (0) : __assert_fail ("ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 5444, __PRETTY_FUNCTION__))
;
5445
5446 // Instantiate a dynamic noexcept expression, if any.
5447 if (isComputedNoexcept(ESI.Type)) {
5448 EnterExpressionEvaluationContext Unevaluated(
5449 getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
5450 ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
5451 if (NoexceptExpr.isInvalid())
5452 return true;
5453
5454 ExceptionSpecificationType EST = ESI.Type;
5455 NoexceptExpr =
5456 getSema().ActOnNoexceptSpec(Loc, NoexceptExpr.get(), EST);
5457 if (NoexceptExpr.isInvalid())
5458 return true;
5459
5460 if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
5461 Changed = true;
5462 ESI.NoexceptExpr = NoexceptExpr.get();
5463 ESI.Type = EST;
5464 }
5465
5466 if (ESI.Type != EST_Dynamic)
5467 return false;
5468
5469 // Instantiate a dynamic exception specification's type.
5470 for (QualType T : ESI.Exceptions) {
5471 if (const PackExpansionType *PackExpansion =
5472 T->getAs<PackExpansionType>()) {
5473 Changed = true;
5474
5475 // We have a pack expansion. Instantiate it.
5476 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5477 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
5478 Unexpanded);
5479 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")((!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? static_cast<void> (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 5479, __PRETTY_FUNCTION__))
;
5480
5481 // Determine whether the set of unexpanded parameter packs can and
5482 // should
5483 // be expanded.
5484 bool Expand = false;
5485 bool RetainExpansion = false;
5486 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
5487 // FIXME: Track the location of the ellipsis (and track source location
5488 // information for the types in the exception specification in general).
5489 if (getDerived().TryExpandParameterPacks(
5490 Loc, SourceRange(), Unexpanded, Expand,
5491 RetainExpansion, NumExpansions))
5492 return true;
5493
5494 if (!Expand) {
5495 // We can't expand this pack expansion into separate arguments yet;
5496 // just substitute into the pattern and create a new pack expansion
5497 // type.
5498 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5499 QualType U = getDerived().TransformType(PackExpansion->getPattern());
5500 if (U.isNull())
5501 return true;
5502
5503 U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
5504 Exceptions.push_back(U);
5505 continue;
5506 }
5507
5508 // Substitute into the pack expansion pattern for each slice of the
5509 // pack.
5510 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
5511 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
5512
5513 QualType U = getDerived().TransformType(PackExpansion->getPattern());
5514 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5515 return true;
5516
5517 Exceptions.push_back(U);
5518 }
5519 } else {
5520 QualType U = getDerived().TransformType(T);
5521 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5522 return true;
5523 if (T != U)
5524 Changed = true;
5525
5526 Exceptions.push_back(U);
5527 }
5528 }
5529
5530 ESI.Exceptions = Exceptions;
5531 if (ESI.Exceptions.empty())
5532 ESI.Type = EST_DynamicNone;
5533 return false;
5534}
5535
5536template<typename Derived>
5537QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
5538 TypeLocBuilder &TLB,
5539 FunctionNoProtoTypeLoc TL) {
5540 const FunctionNoProtoType *T = TL.getTypePtr();
5541 QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5542 if (ResultType.isNull())
5543 return QualType();
5544
5545 QualType Result = TL.getType();
5546 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
5547 Result = getDerived().RebuildFunctionNoProtoType(ResultType);
5548
5549 FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
5550 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5551 NewTL.setLParenLoc(TL.getLParenLoc());
5552 NewTL.setRParenLoc(TL.getRParenLoc());
5553 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5554
5555 return Result;
5556}
5557
5558template<typename Derived> QualType
5559TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
5560 UnresolvedUsingTypeLoc TL) {
5561 const UnresolvedUsingType *T = TL.getTypePtr();
5562 Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
5563 if (!D)
5564 return QualType();
5565
5566 QualType Result = TL.getType();
5567 if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
5568 Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
5569 if (Result.isNull())
5570 return QualType();
5571 }
5572
5573 // We might get an arbitrary type spec type back. We should at
5574 // least always get a type spec type, though.
5575 TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
5576 NewTL.setNameLoc(TL.getNameLoc());
5577
5578 return Result;
5579}
5580
5581template<typename Derived>
5582QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
5583 TypedefTypeLoc TL) {
5584 const TypedefType *T = TL.getTypePtr();
5585 TypedefNameDecl *Typedef
5586 = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5587 T->getDecl()));
5588 if (!Typedef)
5589 return QualType();
5590
5591 QualType Result = TL.getType();
5592 if (getDerived().AlwaysRebuild() ||
5593 Typedef != T->getDecl()) {
5594 Result = getDerived().RebuildTypedefType(Typedef);
5595 if (Result.isNull())
5596 return QualType();
5597 }
5598
5599 TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
5600 NewTL.setNameLoc(TL.getNameLoc());
5601
5602 return Result;
5603}
5604
5605template<typename Derived>
5606QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
5607 TypeOfExprTypeLoc TL) {
5608 // typeof expressions are not potentially evaluated contexts
5609 EnterExpressionEvaluationContext Unevaluated(
5610 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
5611 Sema::ReuseLambdaContextDecl);
5612
5613 ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
5614 if (E.isInvalid())
5615 return QualType();
5616
5617 E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
5618 if (E.isInvalid())
5619 return QualType();
5620
5621 QualType Result = TL.getType();
5622 if (getDerived().AlwaysRebuild() ||
5623 E.get() != TL.getUnderlyingExpr()) {
5624 Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
5625 if (Result.isNull())
5626 return QualType();
5627 }
5628 else E.get();
5629
5630 TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
5631 NewTL.setTypeofLoc(TL.getTypeofLoc());
5632 NewTL.setLParenLoc(TL.getLParenLoc());
5633 NewTL.setRParenLoc(TL.getRParenLoc());
5634
5635 return Result;
5636}
5637
5638template<typename Derived>
5639QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
5640 TypeOfTypeLoc TL) {
5641 TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
5642 TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
5643 if (!New_Under_TI)
5644 return QualType();
5645
5646 QualType Result = TL.getType();
5647 if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
5648 Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
5649 if (Result.isNull())
5650 return QualType();
5651 }
5652
5653 TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
5654 NewTL.setTypeofLoc(TL.getTypeofLoc());
5655 NewTL.setLParenLoc(TL.getLParenLoc());
5656 NewTL.setRParenLoc(TL.getRParenLoc());
5657 NewTL.setUnderlyingTInfo(New_Under_TI);
5658
5659 return Result;
5660}
5661
5662template<typename Derived>
5663QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
5664 DecltypeTypeLoc TL) {
5665 const DecltypeType *T = TL.getTypePtr();
5666
5667 // decltype expressions are not potentially evaluated contexts
5668 EnterExpressionEvaluationContext Unevaluated(
5669 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
5670 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
5671
5672 ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
5673 if (E.isInvalid())
5674 return QualType();
5675
5676 E = getSema().ActOnDecltypeExpression(E.get());
5677 if (E.isInvalid())
5678 return QualType();
5679
5680 QualType Result = TL.getType();
5681 if (getDerived().AlwaysRebuild() ||
5682 E.get() != T->getUnderlyingExpr()) {
5683 Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
5684 if (Result.isNull())
5685 return QualType();
5686 }
5687 else E.get();
5688
5689 DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
5690 NewTL.setNameLoc(TL.getNameLoc());
5691
5692 return Result;
5693}
5694
5695template<typename Derived>
5696QualType TreeTransform<Derived>::TransformUnaryTransformType(
5697 TypeLocBuilder &TLB,
5698 UnaryTransformTypeLoc TL) {
5699 QualType Result = TL.getType();
5700 if (Result->isDependentType()) {
5701 const UnaryTransformType *T = TL.getTypePtr();
5702 QualType NewBase =
5703 getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
5704 Result = getDerived().RebuildUnaryTransformType(NewBase,
5705 T->getUTTKind(),
5706 TL.getKWLoc());
5707 if (Result.isNull())
5708 return QualType();
5709 }
5710
5711 UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
5712 NewTL.setKWLoc(TL.getKWLoc());
5713 NewTL.setParensRange(TL.getParensRange());
5714 NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
5715 return Result;
5716}
5717
5718template<typename Derived>
5719QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
5720 AutoTypeLoc TL) {
5721 const AutoType *T = TL.getTypePtr();
5722 QualType OldDeduced = T->getDeducedType();
5723 QualType NewDeduced;
5724 if (!OldDeduced.isNull()) {
5725 NewDeduced = getDerived().TransformType(OldDeduced);
5726 if (NewDeduced.isNull())
5727 return QualType();
5728 }
5729
5730 QualType Result = TL.getType();
5731 if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
5732 T->isDependentType()) {
5733 Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword());
5734 if (Result.isNull())
5735 return QualType();
5736 }
5737
5738 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
5739 NewTL.setNameLoc(TL.getNameLoc());
5740
5741 return Result;
5742}
5743
5744template<typename Derived>
5745QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
5746 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5747 const DeducedTemplateSpecializationType *T = TL.getTypePtr();
5748
5749 CXXScopeSpec SS;
5750 TemplateName TemplateName = getDerived().TransformTemplateName(
5751 SS, T->getTemplateName(), TL.getTemplateNameLoc());
5752 if (TemplateName.isNull())
5753 return QualType();
5754
5755 QualType OldDeduced = T->getDeducedType();
5756 QualType NewDeduced;
5757 if (!OldDeduced.isNull()) {
5758 NewDeduced = getDerived().TransformType(OldDeduced);
5759 if (NewDeduced.isNull())
5760 return QualType();
5761 }
5762
5763 QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
5764 TemplateName, NewDeduced);
5765 if (Result.isNull())
5766 return QualType();
5767
5768 DeducedTemplateSpecializationTypeLoc NewTL =
5769 TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5770 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5771
5772 return Result;
5773}
5774
5775template<typename Derived>
5776QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
5777 RecordTypeLoc TL) {
5778 const RecordType *T = TL.getTypePtr();
5779 RecordDecl *Record
5780 = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5781 T->getDecl()));
5782 if (!Record)
5783 return QualType();
5784
5785 QualType Result = TL.getType();
5786 if (getDerived().AlwaysRebuild() ||
5787 Record != T->getDecl()) {
5788 Result = getDerived().RebuildRecordType(Record);
5789 if (Result.isNull())
5790 return QualType();
5791 }
5792
5793 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5794 NewTL.setNameLoc(TL.getNameLoc());
5795
5796 return Result;
5797}
5798
5799template<typename Derived>
5800QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
5801 EnumTypeLoc TL) {
5802 const EnumType *T = TL.getTypePtr();
5803 EnumDecl *Enum
5804 = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5805 T->getDecl()));
5806 if (!Enum)
5807 return QualType();
5808
5809 QualType Result = TL.getType();
5810 if (getDerived().AlwaysRebuild() ||
5811 Enum != T->getDecl()) {
5812 Result = getDerived().RebuildEnumType(Enum);
5813 if (Result.isNull())
5814 return QualType();
5815 }
5816
5817 EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
5818 NewTL.setNameLoc(TL.getNameLoc());
5819
5820 return Result;
5821}
5822
5823template<typename Derived>
5824QualType TreeTransform<Derived>::TransformInjectedClassNameType(
5825 TypeLocBuilder &TLB,
5826 InjectedClassNameTypeLoc TL) {
5827 Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
5828 TL.getTypePtr()->getDecl());
5829 if (!D) return QualType();
5830
5831 QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
5832 TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
5833 return T;
5834}
5835
5836template<typename Derived>
5837QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
5838 TypeLocBuilder &TLB,
5839 TemplateTypeParmTypeLoc TL) {
5840 return TransformTypeSpecType(TLB, TL);
5841}
5842
5843template<typename Derived>
5844QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
5845 TypeLocBuilder &TLB,
5846 SubstTemplateTypeParmTypeLoc TL) {
5847 const SubstTemplateTypeParmType *T = TL.getTypePtr();
5848
5849 // Substitute into the replacement type, which itself might involve something
5850 // that needs to be transformed. This only tends to occur with default
5851 // template arguments of template template parameters.
5852 TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
5853 QualType Replacement = getDerived().TransformType(T->getReplacementType());
5854 if (Replacement.isNull())
5855 return QualType();
5856
5857 // Always canonicalize the replacement type.
5858 Replacement = SemaRef.Context.getCanonicalType(Replacement);
5859 QualType Result
5860 = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
5861 Replacement);
5862
5863 // Propagate type-source information.
5864 SubstTemplateTypeParmTypeLoc NewTL
5865 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
5866 NewTL.setNameLoc(TL.getNameLoc());
5867 return Result;
5868
5869}
5870
5871template<typename Derived>
5872QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
5873 TypeLocBuilder &TLB,
5874 SubstTemplateTypeParmPackTypeLoc TL) {
5875 return TransformTypeSpecType(TLB, TL);
5876}
5877
5878template<typename Derived>
5879QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5880 TypeLocBuilder &TLB,
5881 TemplateSpecializationTypeLoc TL) {
5882 const TemplateSpecializationType *T = TL.getTypePtr();
5883
5884 // The nested-name-specifier never matters in a TemplateSpecializationType,
5885 // because we can't have a dependent nested-name-specifier anyway.
5886 CXXScopeSpec SS;
5887 TemplateName Template
5888 = getDerived().TransformTemplateName(SS, T->getTemplateName(),
5889 TL.getTemplateNameLoc());
5890 if (Template.isNull())
5891 return QualType();
5892
5893 return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
5894}
5895
5896template<typename Derived>
5897QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
5898 AtomicTypeLoc TL) {
5899 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5900 if (ValueType.isNull())
5901 return QualType();
5902
5903 QualType Result = TL.getType();
5904 if (getDerived().AlwaysRebuild() ||
5905 ValueType != TL.getValueLoc().getType()) {
5906 Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
5907 if (Result.isNull())
5908 return QualType();
5909 }
5910
5911 AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
5912 NewTL.setKWLoc(TL.getKWLoc());
5913 NewTL.setLParenLoc(TL.getLParenLoc());
5914 NewTL.setRParenLoc(TL.getRParenLoc());
5915
5916 return Result;
5917}
5918
5919template <typename Derived>
5920QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
5921 PipeTypeLoc TL) {
5922 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5923 if (ValueType.isNull())
5924 return QualType();
5925
5926 QualType Result = TL.getType();
5927 if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
5928 const PipeType *PT = Result->getAs<PipeType>();
5929 bool isReadPipe = PT->isReadOnly();
5930 Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
5931 if (Result.isNull())
5932 return QualType();
5933 }
5934
5935 PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
5936 NewTL.setKWLoc(TL.getKWLoc());
5937
5938 return Result;
5939}
5940
5941 /// Simple iterator that traverses the template arguments in a
5942 /// container that provides a \c getArgLoc() member function.
5943 ///
5944 /// This iterator is intended to be used with the iterator form of
5945 /// \c TreeTransform<Derived>::TransformTemplateArguments().
5946 template<typename ArgLocContainer>
5947 class TemplateArgumentLocContainerIterator {
5948 ArgLocContainer *Container;
5949 unsigned Index;
5950
5951 public:
5952 typedef TemplateArgumentLoc value_type;
5953 typedef TemplateArgumentLoc reference;
5954 typedef int difference_type;
5955 typedef std::input_iterator_tag iterator_category;
5956
5957 class pointer {
5958 TemplateArgumentLoc Arg;
5959
5960 public:
5961 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
5962
5963 const TemplateArgumentLoc *operator->() const {
5964 return &Arg;
5965 }
5966 };
5967
5968
5969 TemplateArgumentLocContainerIterator() {}
5970
5971 TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
5972 unsigned Index)
5973 : Container(&Container), Index(Index) { }
5974
5975 TemplateArgumentLocContainerIterator &operator++() {
5976 ++Index;
5977 return *this;
5978 }
5979
5980 TemplateArgumentLocContainerIterator operator++(int) {
5981 TemplateArgumentLocContainerIterator Old(*this);
5982 ++(*this);
5983 return Old;
5984 }
5985
5986 TemplateArgumentLoc operator*() const {
5987 return Container->getArgLoc(Index);
5988 }
5989
5990 pointer operator->() const {
5991 return pointer(Container->getArgLoc(Index));
5992 }
5993
5994 friend bool operator==(const TemplateArgumentLocContainerIterator &X,
5995 const TemplateArgumentLocContainerIterator &Y) {
5996 return X.Container == Y.Container && X.Index == Y.Index;
5997 }
5998
5999 friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6000 const TemplateArgumentLocContainerIterator &Y) {
6001 return !(X == Y);
6002 }
6003 };
6004
6005
6006template <typename Derived>
6007QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6008 TypeLocBuilder &TLB,
6009 TemplateSpecializationTypeLoc TL,
6010 TemplateName Template) {
6011 TemplateArgumentListInfo NewTemplateArgs;
6012 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6013 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6014 typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6015 ArgIterator;
6016 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6017 ArgIterator(TL, TL.getNumArgs()),
6018 NewTemplateArgs))
6019 return QualType();
6020
6021 // FIXME: maybe don't rebuild if all the template arguments are the same.
6022
6023 QualType Result =
6024 getDerived().RebuildTemplateSpecializationType(Template,
6025 TL.getTemplateNameLoc(),
6026 NewTemplateArgs);
6027
6028 if (!Result.isNull()) {
6029 // Specializations of template template parameters are represented as
6030 // TemplateSpecializationTypes, and substitution of type alias templates
6031 // within a dependent context can transform them into
6032 // DependentTemplateSpecializationTypes.
6033 if (isa<DependentTemplateSpecializationType>(Result)) {
6034 DependentTemplateSpecializationTypeLoc NewTL
6035 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6036 NewTL.setElaboratedKeywordLoc(SourceLocation());
6037 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6038 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6039 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6040 NewTL.setLAngleLoc(TL.getLAngleLoc());
6041 NewTL.setRAngleLoc(TL.getRAngleLoc());
6042 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6043 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6044 return Result;
6045 }
6046
6047 TemplateSpecializationTypeLoc NewTL
6048 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6049 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6050 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6051 NewTL.setLAngleLoc(TL.getLAngleLoc());
6052 NewTL.setRAngleLoc(TL.getRAngleLoc());
6053 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6054 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6055 }
6056
6057 return Result;
6058}
6059
6060template <typename Derived>
6061QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6062 TypeLocBuilder &TLB,
6063 DependentTemplateSpecializationTypeLoc TL,
6064 TemplateName Template,
6065 CXXScopeSpec &SS) {
6066 TemplateArgumentListInfo NewTemplateArgs;
6067 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6068 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6069 typedef TemplateArgumentLocContainerIterator<
6070 DependentTemplateSpecializationTypeLoc> ArgIterator;
6071 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6072 ArgIterator(TL, TL.getNumArgs()),
6073 NewTemplateArgs))
6074 return QualType();
6075
6076 // FIXME: maybe don't rebuild if all the template arguments are the same.
6077
6078 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6079 QualType Result
6080 = getSema().Context.getDependentTemplateSpecializationType(
6081 TL.getTypePtr()->getKeyword(),
6082 DTN->getQualifier(),
6083 DTN->getIdentifier(),
6084 NewTemplateArgs);
6085
6086 DependentTemplateSpecializationTypeLoc NewTL
6087 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6088 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6089 NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6090 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6091 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6092 NewTL.setLAngleLoc(TL.getLAngleLoc());
6093 NewTL.setRAngleLoc(TL.getRAngleLoc());
6094 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6095 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6096 return Result;
6097 }
6098
6099 QualType Result
6100 = getDerived().RebuildTemplateSpecializationType(Template,
6101 TL.getTemplateNameLoc(),
6102 NewTemplateArgs);
6103
6104 if (!Result.isNull()) {
6105 /// FIXME: Wrap this in an elaborated-type-specifier?
6106 TemplateSpecializationTypeLoc NewTL
6107 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6108 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6109 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6110 NewTL.setLAngleLoc(TL.getLAngleLoc());
6111 NewTL.setRAngleLoc(TL.getRAngleLoc());
6112 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6113 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6114 }
6115
6116 return Result;
6117}
6118
6119template<typename Derived>
6120QualType
6121TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6122 ElaboratedTypeLoc TL) {
6123 const ElaboratedType *T = TL.getTypePtr();
6124
6125 NestedNameSpecifierLoc QualifierLoc;
6126 // NOTE: the qualifier in an ElaboratedType is optional.
6127 if (TL.getQualifierLoc()) {
6128 QualifierLoc
6129 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6130 if (!QualifierLoc)
6131 return QualType();
6132 }
6133
6134 QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6135 if (NamedT.isNull())
6136 return QualType();
6137
6138 // C++0x [dcl.type.elab]p2:
6139 // If the identifier resolves to a typedef-name or the simple-template-id
6140 // resolves to an alias template specialization, the
6141 // elaborated-type-specifier is ill-formed.
6142 if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6143 if (const TemplateSpecializationType *TST =
6144 NamedT->getAs<TemplateSpecializationType>()) {
6145 TemplateName Template = TST->getTemplateName();
6146 if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6147 Template.getAsTemplateDecl())) {
6148 SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6149 diag::err_tag_reference_non_tag)
6150 << TAT << Sema::NTK_TypeAliasTemplate
6151 << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6152 SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6153 }
6154 }
6155 }
6156
6157 QualType Result = TL.getType();
6158 if (getDerived().AlwaysRebuild() ||
6159 QualifierLoc != TL.getQualifierLoc() ||
6160 NamedT != T->getNamedType()) {
6161 Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6162 T->getKeyword(),
6163 QualifierLoc, NamedT);
6164 if (Result.isNull())
6165 return QualType();
6166 }
6167
6168 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6169 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6170 NewTL.setQualifierLoc(QualifierLoc);
6171 return Result;
6172}
6173
6174template<typename Derived>
6175QualType TreeTransform<Derived>::TransformAttributedType(
6176 TypeLocBuilder &TLB,
6177 AttributedTypeLoc TL) {
6178 const AttributedType *oldType = TL.getTypePtr();
6179 QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
6180 if (modifiedType.isNull())
6181 return QualType();
6182
6183 // oldAttr can be null if we started with a QualType rather than a TypeLoc.
6184 const Attr *oldAttr = TL.getAttr();
6185 const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
6186 if (oldAttr && !newAttr)
6187 return QualType();
6188
6189 QualType result = TL.getType();
6190
6191 // FIXME: dependent operand expressions?
6192 if (getDerived().AlwaysRebuild() ||
6193 modifiedType != oldType->getModifiedType()) {
6194 // TODO: this is really lame; we should really be rebuilding the
6195 // equivalent type from first principles.
6196 QualType equivalentType
6197 = getDerived().TransformType(oldType->getEquivalentType());
6198 if (equivalentType.isNull())
6199 return QualType();
6200
6201 // Check whether we can add nullability; it is only represented as
6202 // type sugar, and therefore cannot be diagnosed in any other way.
6203 if (auto nullability = oldType->getImmediateNullability()) {
6204 if (!modifiedType->canHaveNullability()) {
6205 SemaRef.Diag(TL.getAttr()->getLocation(),
6206 diag::err_nullability_nonpointer)
6207 << DiagNullabilityKind(*nullability, false) << modifiedType;
6208 return QualType();
6209 }
6210 }
6211
6212 result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
6213 modifiedType,
6214 equivalentType);
6215 }
6216
6217 AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
6218 newTL.setAttr(newAttr);
6219 return result;
6220}
6221
6222template<typename Derived>
6223QualType
6224TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
6225 ParenTypeLoc TL) {
6226 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6227 if (Inner.isNull())
6228 return QualType();
6229
6230 QualType Result = TL.getType();
6231 if (getDerived().AlwaysRebuild() ||
6232 Inner != TL.getInnerLoc().getType()) {
6233 Result = getDerived().RebuildParenType(Inner);
6234 if (Result.isNull())
6235 return QualType();
6236 }
6237
6238 ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
6239 NewTL.setLParenLoc(TL.getLParenLoc());
6240 NewTL.setRParenLoc(TL.getRParenLoc());
6241 return Result;
6242}
6243
6244template <typename Derived>
6245QualType
6246TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
6247 MacroQualifiedTypeLoc TL) {
6248 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6249 if (Inner.isNull())
6250 return QualType();
6251
6252 QualType Result = TL.getType();
6253 if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
6254 Result =
6255 getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
6256 if (Result.isNull())
6257 return QualType();
6258 }
6259
6260 MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
6261 NewTL.setExpansionLoc(TL.getExpansionLoc());
6262 return Result;
6263}
6264
6265template<typename Derived>
6266QualType TreeTransform<Derived>::TransformDependentNameType(
6267 TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
6268 return TransformDependentNameType(TLB, TL, false);
6269}
6270
6271template<typename Derived>
6272QualType TreeTransform<Derived>::TransformDependentNameType(
6273 TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6274 const DependentNameType *T = TL.getTypePtr();
6275
6276 NestedNameSpecifierLoc QualifierLoc
6277 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6278 if (!QualifierLoc)
6279 return QualType();
6280
6281 QualType Result
6282 = getDerived().RebuildDependentNameType(T->getKeyword(),
6283 TL.getElaboratedKeywordLoc(),
6284 QualifierLoc,
6285 T->getIdentifier(),
6286 TL.getNameLoc(),
6287 DeducedTSTContext);
6288 if (Result.isNull())
6289 return QualType();
6290
6291 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6292 QualType NamedT = ElabT->getNamedType();
6293 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6294
6295 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6296 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6297 NewTL.setQualifierLoc(QualifierLoc);
6298 } else {
6299 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6300 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6301 NewTL.setQualifierLoc(QualifierLoc);
6302 NewTL.setNameLoc(TL.getNameLoc());
6303 }
6304 return Result;
6305}
6306
6307template<typename Derived>
6308QualType TreeTransform<Derived>::
6309 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6310 DependentTemplateSpecializationTypeLoc TL) {
6311 NestedNameSpecifierLoc QualifierLoc;
6312 if (TL.getQualifierLoc()) {
6313 QualifierLoc
6314 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6315 if (!QualifierLoc)
6316 return QualType();
6317 }
6318
6319 return getDerived()
6320 .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
6321}
6322
6323template<typename Derived>
6324QualType TreeTransform<Derived>::
6325TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6326 DependentTemplateSpecializationTypeLoc TL,
6327 NestedNameSpecifierLoc QualifierLoc) {
6328 const DependentTemplateSpecializationType *T = TL.getTypePtr();
6329
6330 TemplateArgumentListInfo NewTemplateArgs;
6331 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6332 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6333
6334 typedef TemplateArgumentLocContainerIterator<
6335 DependentTemplateSpecializationTypeLoc> ArgIterator;
6336 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6337 ArgIterator(TL, TL.getNumArgs()),
6338 NewTemplateArgs))
6339 return QualType();
6340
6341 QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
6342 T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
6343 T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
6344 /*AllowInjectedClassName*/ false);
6345 if (Result.isNull())
6346 return QualType();
6347
6348 if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
6349 QualType NamedT = ElabT->getNamedType();
6350
6351 // Copy information relevant to the template specialization.
6352 TemplateSpecializationTypeLoc NamedTL
6353 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
6354 NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6355 NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6356 NamedTL.setLAngleLoc(TL.getLAngleLoc());
6357 NamedTL.setRAngleLoc(TL.getRAngleLoc());
6358 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6359 NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6360
6361 // Copy information relevant to the elaborated type.
6362 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6363 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6364 NewTL.setQualifierLoc(QualifierLoc);
6365 } else if (isa<DependentTemplateSpecializationType>(Result)) {
6366 DependentTemplateSpecializationTypeLoc SpecTL
6367 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6368 SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6369 SpecTL.setQualifierLoc(QualifierLoc);
6370 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6371 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6372 SpecTL.setLAngleLoc(TL.getLAngleLoc());
6373 SpecTL.setRAngleLoc(TL.getRAngleLoc());
6374 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6375 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6376 } else {
6377 TemplateSpecializationTypeLoc SpecTL
6378 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6379 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6380 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6381 SpecTL.setLAngleLoc(TL.getLAngleLoc());
6382 SpecTL.setRAngleLoc(TL.getRAngleLoc());
6383 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6384 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6385 }
6386 return Result;
6387}
6388
6389template<typename Derived>
6390QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
6391 PackExpansionTypeLoc TL) {
6392 QualType Pattern
6393 = getDerived().TransformType(TLB, TL.getPatternLoc());
6394 if (Pattern.isNull())
6395 return QualType();
6396
6397 QualType Result = TL.getType();
6398 if (getDerived().AlwaysRebuild() ||
6399 Pattern != TL.getPatternLoc().getType()) {
6400 Result = getDerived().RebuildPackExpansionType(Pattern,
6401 TL.getPatternLoc().getSourceRange(),
6402 TL.getEllipsisLoc(),
6403 TL.getTypePtr()->getNumExpansions());
6404 if (Result.isNull())
6405 return QualType();
6406 }
6407
6408 PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
6409 NewT.setEllipsisLoc(TL.getEllipsisLoc());
6410 return Result;
6411}
6412
6413template<typename Derived>
6414QualType
6415TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
6416 ObjCInterfaceTypeLoc TL) {
6417 // ObjCInterfaceType is never dependent.
6418 TLB.pushFullCopy(TL);
6419 return TL.getType();
6420}
6421
6422template<typename Derived>
6423QualType
6424TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
6425 ObjCTypeParamTypeLoc TL) {
6426 const ObjCTypeParamType *T = TL.getTypePtr();
6427 ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
6428 getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
6429 if (!OTP)
6430 return QualType();
6431
6432 QualType Result = TL.getType();
6433 if (getDerived().AlwaysRebuild() ||
6434 OTP != T->getDecl()) {
6435 Result = getDerived().RebuildObjCTypeParamType(OTP,
6436 TL.getProtocolLAngleLoc(),
6437 llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
6438 TL.getNumProtocols()),
6439 TL.getProtocolLocs(),
6440 TL.getProtocolRAngleLoc());
6441 if (Result.isNull())
6442 return QualType();
6443 }
6444
6445 ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
6446 if (TL.getNumProtocols()) {
6447 NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6448 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6449 NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
6450 NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6451 }
6452 return Result;
6453}
6454
6455template<typename Derived>
6456QualType
6457TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
6458 ObjCObjectTypeLoc TL) {
6459 // Transform base type.
6460 QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
6461 if (BaseType.isNull())
6462 return QualType();
6463
6464 bool AnyChanged = BaseType != TL.getBaseLoc().getType();
6465
6466 // Transform type arguments.
6467 SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
6468 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
6469 TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
6470 TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
6471 QualType TypeArg = TypeArgInfo->getType();
6472 if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
6473 AnyChanged = true;
6474
6475 // We have a pack expansion. Instantiate it.
6476 const auto *PackExpansion = PackExpansionLoc.getType()
6477 ->castAs<PackExpansionType>();
6478 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6479 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6480 Unexpanded);
6481 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")((!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? static_cast<void> (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 6481, __PRETTY_FUNCTION__))
;
6482
6483 // Determine whether the set of unexpanded parameter packs can
6484 // and should be expanded.
6485 TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
6486 bool Expand = false;
6487 bool RetainExpansion = false;
6488 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6489 if (getDerived().TryExpandParameterPacks(
6490 PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
6491 Unexpanded, Expand, RetainExpansion, NumExpansions))
6492 return QualType();
6493
6494 if (!Expand) {
6495 // We can't expand this pack expansion into separate arguments yet;
6496 // just substitute into the pattern and create a new pack expansion
6497 // type.
6498 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6499
6500 TypeLocBuilder TypeArgBuilder;
6501 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6502 QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
6503 PatternLoc);
6504 if (NewPatternType.isNull())
6505 return QualType();
6506
6507 QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
6508 NewPatternType, NumExpansions);
6509 auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
6510 NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
6511 NewTypeArgInfos.push_back(
6512 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
6513 continue;
6514 }
6515
6516 // Substitute into the pack expansion pattern for each slice of the
6517 // pack.
6518 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6519 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6520
6521 TypeLocBuilder TypeArgBuilder;
6522 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6523
6524 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
6525 PatternLoc);
6526 if (NewTypeArg.isNull())
6527 return QualType();
6528
6529 NewTypeArgInfos.push_back(
6530 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6531 }
6532
6533 continue;
6534 }
6535
6536 TypeLocBuilder TypeArgBuilder;
6537 TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
6538 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
6539 if (NewTypeArg.isNull())
6540 return QualType();
6541
6542 // If nothing changed, just keep the old TypeSourceInfo.
6543 if (NewTypeArg == TypeArg) {
6544 NewTypeArgInfos.push_back(TypeArgInfo);
6545 continue;
6546 }
6547
6548 NewTypeArgInfos.push_back(
6549 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6550 AnyChanged = true;
6551 }
6552
6553 QualType Result = TL.getType();
6554 if (getDerived().AlwaysRebuild() || AnyChanged) {
6555 // Rebuild the type.
6556 Result = getDerived().RebuildObjCObjectType(
6557 BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
6558 TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
6559 llvm::makeArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
6560 TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
6561
6562 if (Result.isNull())
6563 return QualType();
6564 }
6565
6566 ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
6567 NewT.setHasBaseTypeAsWritten(true);
6568 NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
6569 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
6570 NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
6571 NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
6572 NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6573 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6574 NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
6575 NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6576 return Result;
6577}
6578
6579template<typename Derived>
6580QualType
6581TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
6582 ObjCObjectPointerTypeLoc TL) {
6583 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
6584 if (PointeeType.isNull())
6585 return QualType();
6586
6587 QualType Result = TL.getType();
6588 if (getDerived().AlwaysRebuild() ||
6589 PointeeType != TL.getPointeeLoc().getType()) {
6590 Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
6591 TL.getStarLoc());
6592 if (Result.isNull())
6593 return QualType();
6594 }
6595
6596 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
6597 NewT.setStarLoc(TL.getStarLoc());
6598 return Result;
6599}
6600
6601//===----------------------------------------------------------------------===//
6602// Statement transformation
6603//===----------------------------------------------------------------------===//
6604template<typename Derived>
6605StmtResult
6606TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
6607 return S;
6608}
6609
6610template<typename Derived>
6611StmtResult
6612TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
6613 return getDerived().TransformCompoundStmt(S, false);
6614}
6615
6616template<typename Derived>
6617StmtResult
6618TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
6619 bool IsStmtExpr) {
6620 Sema::CompoundScopeRAII CompoundScope(getSema());
6621
6622 const Stmt *ExprResult = S->getStmtExprResult();
6623 bool SubStmtInvalid = false;
6624 bool SubStmtChanged = false;
6625 SmallVector<Stmt*, 8> Statements;
6626 for (auto *B : S->body()) {
6627 StmtResult Result = getDerived().TransformStmt(
6628 B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
6629
6630 if (Result.isInvalid()) {
6631 // Immediately fail if this was a DeclStmt, since it's very
6632 // likely that this will cause problems for future statements.
6633 if (isa<DeclStmt>(B))
6634 return StmtError();
6635
6636 // Otherwise, just keep processing substatements and fail later.
6637 SubStmtInvalid = true;
6638 continue;
6639 }
6640
6641 SubStmtChanged = SubStmtChanged || Result.get() != B;
6642 Statements.push_back(Result.getAs<Stmt>());
6643 }
6644
6645 if (SubStmtInvalid)
6646 return StmtError();
6647
6648 if (!getDerived().AlwaysRebuild() &&
6649 !SubStmtChanged)
6650 return S;
6651
6652 return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
6653 Statements,
6654 S->getRBracLoc(),
6655 IsStmtExpr);
6656}
6657
6658template<typename Derived>
6659StmtResult
6660TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
6661 ExprResult LHS, RHS;
6662 {
6663 EnterExpressionEvaluationContext Unevaluated(
6664 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6665
6666 // Transform the left-hand case value.
6667 LHS = getDerived().TransformExpr(S->getLHS());
6668 LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
6669 if (LHS.isInvalid())
6670 return StmtError();
6671
6672 // Transform the right-hand case value (for the GNU case-range extension).
6673 RHS = getDerived().TransformExpr(S->getRHS());
6674 RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
6675 if (RHS.isInvalid())
6676 return StmtError();
6677 }
6678
6679 // Build the case statement.
6680 // Case statements are always rebuilt so that they will attached to their
6681 // transformed switch statement.
6682 StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
6683 LHS.get(),
6684 S->getEllipsisLoc(),
6685 RHS.get(),
6686 S->getColonLoc());
6687 if (Case.isInvalid())
6688 return StmtError();
6689
6690 // Transform the statement following the case
6691 StmtResult SubStmt =
6692 getDerived().TransformStmt(S->getSubStmt());
6693 if (SubStmt.isInvalid())
6694 return StmtError();
6695
6696 // Attach the body to the case statement
6697 return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
6698}
6699
6700template <typename Derived>
6701StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
6702 // Transform the statement following the default case
6703 StmtResult SubStmt =
6704 getDerived().TransformStmt(S->getSubStmt());
6705 if (SubStmt.isInvalid())
6706 return StmtError();
6707
6708 // Default statements are always rebuilt
6709 return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
6710 SubStmt.get());
6711}
6712
6713template<typename Derived>
6714StmtResult
6715TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
6716 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
6717 if (SubStmt.isInvalid())
6718 return StmtError();
6719
6720 Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
6721 S->getDecl());
6722 if (!LD)
6723 return StmtError();
6724
6725 // If we're transforming "in-place" (we're not creating new local
6726 // declarations), assume we're replacing the old label statement
6727 // and clear out the reference to it.
6728 if (LD == S->getDecl())
6729 S->getDecl()->setStmt(nullptr);
6730
6731 // FIXME: Pass the real colon location in.
6732 return getDerived().RebuildLabelStmt(S->getIdentLoc(),
6733 cast<LabelDecl>(LD), SourceLocation(),
6734 SubStmt.get());
6735}
6736
6737template <typename Derived>
6738const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
6739 if (!R)
6740 return R;
6741
6742 switch (R->getKind()) {
6743// Transform attributes with a pragma spelling by calling TransformXXXAttr.
6744#define ATTR(X)
6745#define PRAGMA_SPELLING_ATTR(X) \
6746 case attr::X: \
6747 return getDerived().Transform##X##Attr(cast<X##Attr>(R));
6748#include "clang/Basic/AttrList.inc"
6749 default:
6750 return R;
6751 }
6752}
6753
6754template <typename Derived>
6755StmtResult
6756TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
6757 StmtDiscardKind SDK) {
6758 bool AttrsChanged = false;
6759 SmallVector<const Attr *, 1> Attrs;
6760
6761 // Visit attributes and keep track if any are transformed.
6762 for (const auto *I : S->getAttrs()) {
6763 const Attr *R = getDerived().TransformAttr(I);
6764 AttrsChanged |= (I != R);
6765 Attrs.push_back(R);
6766 }
6767
6768 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
6769 if (SubStmt.isInvalid())
6770 return StmtError();
6771
6772 if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
6773 return S;
6774
6775 return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
6776 SubStmt.get());
6777}
6778
6779template<typename Derived>
6780StmtResult
6781TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
6782 // Transform the initialization statement
6783 StmtResult Init = getDerived().TransformStmt(S->getInit());
6784 if (Init.isInvalid())
6785 return StmtError();
6786
6787 // Transform the condition
6788 Sema::ConditionResult Cond = getDerived().TransformCondition(
6789 S->getIfLoc(), S->getConditionVariable(), S->getCond(),
6790 S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
6791 : Sema::ConditionKind::Boolean);
6792 if (Cond.isInvalid())
6793 return StmtError();
6794
6795 // If this is a constexpr if, determine which arm we should instantiate.
6796 llvm::Optional<bool> ConstexprConditionValue;
6797 if (S->isConstexpr())
6798 ConstexprConditionValue = Cond.getKnownValue();
6799
6800 // Transform the "then" branch.
6801 StmtResult Then;
6802 if (!ConstexprConditionValue || *ConstexprConditionValue) {
6803 Then = getDerived().TransformStmt(S->getThen());
6804 if (Then.isInvalid())
6805 return StmtError();
6806 } else {
6807 Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
6808 }
6809
6810 // Transform the "else" branch.
6811 StmtResult Else;
6812 if (!ConstexprConditionValue || !*ConstexprConditionValue) {
6813 Else = getDerived().TransformStmt(S->getElse());
6814 if (Else.isInvalid())
6815 return StmtError();
6816 }
6817
6818 if (!getDerived().AlwaysRebuild() &&
6819 Init.get() == S->getInit() &&
6820 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6821 Then.get() == S->getThen() &&
6822 Else.get() == S->getElse())
6823 return S;
6824
6825 return getDerived().RebuildIfStmt(S->getIfLoc(), S->isConstexpr(), Cond,
6826 Init.get(), Then.get(), S->getElseLoc(),
6827 Else.get());
6828}
6829
6830template<typename Derived>
6831StmtResult
6832TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
6833 // Transform the initialization statement
6834 StmtResult Init = getDerived().TransformStmt(S->getInit());
6835 if (Init.isInvalid())
6836 return StmtError();
6837
6838 // Transform the condition.
6839 Sema::ConditionResult Cond = getDerived().TransformCondition(
6840 S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
6841 Sema::ConditionKind::Switch);
6842 if (Cond.isInvalid())
6843 return StmtError();
6844
6845 // Rebuild the switch statement.
6846 StmtResult Switch
6847 = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Init.get(), Cond);
6848 if (Switch.isInvalid())
6849 return StmtError();
6850
6851 // Transform the body of the switch statement.
6852 StmtResult Body = getDerived().TransformStmt(S->getBody());
6853 if (Body.isInvalid())
6854 return StmtError();
6855
6856 // Complete the switch statement.
6857 return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
6858 Body.get());
6859}
6860
6861template<typename Derived>
6862StmtResult
6863TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
6864 // Transform the condition
6865 Sema::ConditionResult Cond = getDerived().TransformCondition(
6866 S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
6867 Sema::ConditionKind::Boolean);
6868 if (Cond.isInvalid())
6869 return StmtError();
6870
6871 // Transform the body
6872 StmtResult Body = getDerived().TransformStmt(S->getBody());
6873 if (Body.isInvalid())
6874 return StmtError();
6875
6876 if (!getDerived().AlwaysRebuild() &&
6877 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6878 Body.get() == S->getBody())
6879 return Owned(S);
6880
6881 return getDerived().RebuildWhileStmt(S->getWhileLoc(), Cond, Body.get());
6882}
6883
6884template<typename Derived>
6885StmtResult
6886TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
6887 // Transform the body
6888 StmtResult Body = getDerived().TransformStmt(S->getBody());
6889 if (Body.isInvalid())
6890 return StmtError();
6891
6892 // Transform the condition
6893 ExprResult Cond = getDerived().TransformExpr(S->getCond());
6894 if (Cond.isInvalid())
6895 return StmtError();
6896
6897 if (!getDerived().AlwaysRebuild() &&
6898 Cond.get() == S->getCond() &&
6899 Body.get() == S->getBody())
6900 return S;
6901
6902 return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
6903 /*FIXME:*/S->getWhileLoc(), Cond.get(),
6904 S->getRParenLoc());
6905}
6906
6907template<typename Derived>
6908StmtResult
6909TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
6910 if (getSema().getLangOpts().OpenMP)
6911 getSema().startOpenMPLoop();
6912
6913 // Transform the initialization statement
6914 StmtResult Init = getDerived().TransformStmt(S->getInit());
6915 if (Init.isInvalid())
6916 return StmtError();
6917
6918 // In OpenMP loop region loop control variable must be captured and be
6919 // private. Perform analysis of first part (if any).
6920 if (getSema().getLangOpts().OpenMP && Init.isUsable())
6921 getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
6922
6923 // Transform the condition
6924 Sema::ConditionResult Cond = getDerived().TransformCondition(
6925 S->getForLoc(), S->getConditionVariable(), S->getCond(),
6926 Sema::ConditionKind::Boolean);
6927 if (Cond.isInvalid())
6928 return StmtError();
6929
6930 // Transform the increment
6931 ExprResult Inc = getDerived().TransformExpr(S->getInc());
6932 if (Inc.isInvalid())
6933 return StmtError();
6934
6935 Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
6936 if (S->getInc() && !FullInc.get())
6937 return StmtError();
6938
6939 // Transform the body
6940 StmtResult Body = getDerived().TransformStmt(S->getBody());
6941 if (Body.isInvalid())
6942 return StmtError();
6943
6944 if (!getDerived().AlwaysRebuild() &&
6945 Init.get() == S->getInit() &&
6946 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6947 Inc.get() == S->getInc() &&
6948 Body.get() == S->getBody())
6949 return S;
6950
6951 return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
6952 Init.get(), Cond, FullInc,
6953 S->getRParenLoc(), Body.get());
6954}
6955
6956template<typename Derived>
6957StmtResult
6958TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
6959 Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
6960 S->getLabel());
6961 if (!LD)
6962 return StmtError();
6963
6964 // Goto statements must always be rebuilt, to resolve the label.
6965 return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
6966 cast<LabelDecl>(LD));
6967}
6968
6969template<typename Derived>
6970StmtResult
6971TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
6972 ExprResult Target = getDerived().TransformExpr(S->getTarget());
6973 if (Target.isInvalid())
6974 return StmtError();
6975 Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
6976
6977 if (!getDerived().AlwaysRebuild() &&
6978 Target.get() == S->getTarget())
6979 return S;
6980
6981 return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
6982 Target.get());
6983}
6984
6985template<typename Derived>
6986StmtResult
6987TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
6988 return S;
6989}
6990
6991template<typename Derived>
6992StmtResult
6993TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
6994 return S;
6995}
6996
6997template<typename Derived>
6998StmtResult
6999TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7000 ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7001 /*NotCopyInit*/false);
7002 if (Result.isInvalid())
7003 return StmtError();
7004
7005 // FIXME: We always rebuild the return statement because there is no way
7006 // to tell whether the return type of the function has changed.
7007 return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7008}
7009
7010template<typename Derived>
7011StmtResult
7012TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7013 bool DeclChanged = false;
7014 SmallVector<Decl *, 4> Decls;
7015 for (auto *D : S->decls()) {
7016 Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7017 if (!Transformed)
7018 return StmtError();
7019
7020 if (Transformed != D)
7021 DeclChanged = true;
7022
7023 Decls.push_back(Transformed);
7024 }
7025
7026 if (!getDerived().AlwaysRebuild() && !DeclChanged)
7027 return S;
7028
7029 return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7030}
7031
7032template<typename Derived>
7033StmtResult
7034TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7035
7036 SmallVector<Expr*, 8> Constraints;
7037 SmallVector<Expr*, 8> Exprs;
7038 SmallVector<IdentifierInfo *, 4> Names;
7039
7040 ExprResult AsmString;
7041 SmallVector<Expr*, 8> Clobbers;
7042
7043 bool ExprsChanged = false;
7044
7045 // Go through the outputs.
7046 for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7047 Names.push_back(S->getOutputIdentifier(I));
7048
7049 // No need to transform the constraint literal.
7050 Constraints.push_back(S->getOutputConstraintLiteral(I));
7051
7052 // Transform the output expr.
7053 Expr *OutputExpr = S->getOutputExpr(I);
7054 ExprResult Result = getDerived().TransformExpr(OutputExpr);
7055 if (Result.isInvalid())
7056 return StmtError();
7057
7058 ExprsChanged |= Result.get() != OutputExpr;
7059
7060 Exprs.push_back(Result.get());
7061 }
7062
7063 // Go through the inputs.
7064 for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7065 Names.push_back(S->getInputIdentifier(I));
7066
7067 // No need to transform the constraint literal.
7068 Constraints.push_back(S->getInputConstraintLiteral(I));
7069
7070 // Transform the input expr.
7071 Expr *InputExpr = S->getInputExpr(I);
7072 ExprResult Result = getDerived().TransformExpr(InputExpr);
7073 if (Result.isInvalid())
7074 return StmtError();
7075
7076 ExprsChanged |= Result.get() != InputExpr;
7077
7078 Exprs.push_back(Result.get());
7079 }
7080
7081 // Go through the Labels.
7082 for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7083 Names.push_back(S->getLabelIdentifier(I));
7084
7085 ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7086 if (Result.isInvalid())
7087 return StmtError();
7088 ExprsChanged |= Result.get() != S->getLabelExpr(I);
7089 Exprs.push_back(Result.get());
7090 }
7091 if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7092 return S;
7093
7094 // Go through the clobbers.
7095 for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7096 Clobbers.push_back(S->getClobberStringLiteral(I));
7097
7098 // No need to transform the asm string literal.
7099 AsmString = S->getAsmString();
7100 return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7101 S->isVolatile(), S->getNumOutputs(),
7102 S->getNumInputs(), Names.data(),
7103 Constraints, Exprs, AsmString.get(),
7104 Clobbers, S->getNumLabels(),
7105 S->getRParenLoc());
7106}
7107
7108template<typename Derived>
7109StmtResult
7110TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7111 ArrayRef<Token> AsmToks =
7112 llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
7113
7114 bool HadError = false, HadChange = false;
7115
7116 ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7117 SmallVector<Expr*, 8> TransformedExprs;
7118 TransformedExprs.reserve(SrcExprs.size());
7119 for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7120 ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7121 if (!Result.isUsable()) {
7122 HadError = true;
7123 } else {
7124 HadChange |= (Result.get() != SrcExprs[i]);
7125 TransformedExprs.push_back(Result.get());
7126 }
7127 }
7128
7129 if (HadError) return StmtError();
7130 if (!HadChange && !getDerived().AlwaysRebuild())
7131 return Owned(S);
7132
7133 return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7134 AsmToks, S->getAsmString(),
7135 S->getNumOutputs(), S->getNumInputs(),
7136 S->getAllConstraints(), S->getClobbers(),
7137 TransformedExprs, S->getEndLoc());
7138}
7139
7140// C++ Coroutines TS
7141
7142template<typename Derived>
7143StmtResult
7144TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
7145 auto *ScopeInfo = SemaRef.getCurFunction();
7146 auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
7147 assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&((FD && ScopeInfo && !ScopeInfo->CoroutinePromise
&& ScopeInfo->NeedsCoroutineSuspends && ScopeInfo
->CoroutineSuspends.first == nullptr && ScopeInfo->
CoroutineSuspends.second == nullptr && "expected clean scope info"
) ? static_cast<void> (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 7151, __PRETTY_FUNCTION__))
7148 ScopeInfo->NeedsCoroutineSuspends &&((FD && ScopeInfo && !ScopeInfo->CoroutinePromise
&& ScopeInfo->NeedsCoroutineSuspends && ScopeInfo
->CoroutineSuspends.first == nullptr && ScopeInfo->
CoroutineSuspends.second == nullptr && "expected clean scope info"
) ? static_cast<void> (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 7151, __PRETTY_FUNCTION__))
7149 ScopeInfo->CoroutineSuspends.first == nullptr &&((FD && ScopeInfo && !ScopeInfo->CoroutinePromise
&& ScopeInfo->NeedsCoroutineSuspends && ScopeInfo
->CoroutineSuspends.first == nullptr && ScopeInfo->
CoroutineSuspends.second == nullptr && "expected clean scope info"
) ? static_cast<void> (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 7151, __PRETTY_FUNCTION__))
7150 ScopeInfo->CoroutineSuspends.second == nullptr &&((FD && ScopeInfo && !ScopeInfo->CoroutinePromise
&& ScopeInfo->NeedsCoroutineSuspends && ScopeInfo
->CoroutineSuspends.first == nullptr && ScopeInfo->
CoroutineSuspends.second == nullptr && "expected clean scope info"
) ? static_cast<void> (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 7151, __PRETTY_FUNCTION__))
7151 "expected clean scope info")((FD && ScopeInfo && !ScopeInfo->CoroutinePromise
&& ScopeInfo->NeedsCoroutineSuspends && ScopeInfo
->CoroutineSuspends.first == nullptr && ScopeInfo->
CoroutineSuspends.second == nullptr && "expected clean scope info"
) ? static_cast<void> (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 7151, __PRETTY_FUNCTION__))
;
7152
7153 // Set that we have (possibly-invalid) suspend points before we do anything
7154 // that may fail.
7155 ScopeInfo->setNeedsCoroutineSuspends(false);
7156
7157 // The new CoroutinePromise object needs to be built and put into the current
7158 // FunctionScopeInfo before any transformations or rebuilding occurs.
7159 if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
7160 return StmtError();
7161 auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
7162 if (!Promise)
7163 return StmtError();
7164 getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
7165 ScopeInfo->CoroutinePromise = Promise;
7166
7167 // Transform the implicit coroutine statements we built during the initial
7168 // parse.
7169 StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
7170 if (InitSuspend.isInvalid())
7171 return StmtError();
7172 StmtResult FinalSuspend =
7173 getDerived().TransformStmt(S->getFinalSuspendStmt());
7174 if (FinalSuspend.isInvalid())
7175 return StmtError();
7176 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
7177 assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()))((isa<Expr>(InitSuspend.get()) && isa<Expr>
(FinalSuspend.get())) ? static_cast<void> (0) : __assert_fail
("isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get())"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 7177, __PRETTY_FUNCTION__))
;
7178
7179 StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
7180 if (BodyRes.isInvalid())
7181 return StmtError();
7182
7183 CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
7184 if (Builder.isInvalid())
7185 return StmtError();
7186
7187 Expr *ReturnObject = S->getReturnValueInit();
7188 assert(ReturnObject && "the return object is expected to be valid")((ReturnObject && "the return object is expected to be valid"
) ? static_cast<void> (0) : __assert_fail ("ReturnObject && \"the return object is expected to be valid\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 7188, __PRETTY_FUNCTION__))
;
7189 ExprResult Res = getDerived().TransformInitializer(ReturnObject,
7190 /*NoCopyInit*/ false);
7191 if (Res.isInvalid())
7192 return StmtError();
7193 Builder.ReturnValue = Res.get();
7194
7195 if (S->hasDependentPromiseType()) {
7196 // PR41909: We may find a generic coroutine lambda definition within a
7197 // template function that is being instantiated. In this case, the lambda
7198 // will have a dependent promise type, until it is used in an expression
7199 // that creates an instantiation with a non-dependent promise type. We
7200 // should not assert or build coroutine dependent statements for such a
7201 // generic lambda.
7202 auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD);
7203 if (!MD || !MD->getParent()->isGenericLambda()) {
7204 assert(!Promise->getType()->isDependentType() &&((!Promise->getType()->isDependentType() && "the promise type must no longer be dependent"
) ? static_cast<void> (0) : __assert_fail ("!Promise->getType()->isDependentType() && \"the promise type must no longer be dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 7205, __PRETTY_FUNCTION__))
7205 "the promise type must no longer be dependent")((!Promise->getType()->isDependentType() && "the promise type must no longer be dependent"
) ? static_cast<void> (0) : __assert_fail ("!Promise->getType()->isDependentType() && \"the promise type must no longer be dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 7205, __PRETTY_FUNCTION__))
;
7206 assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&((!S->getFallthroughHandler() && !S->getExceptionHandler
() && !S->getReturnStmtOnAllocFailure() &&
!S->getDeallocate() && "these nodes should not have been built yet"
) ? static_cast<void> (0) : __assert_fail ("!S->getFallthroughHandler() && !S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() && \"these nodes should not have been built yet\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 7208, __PRETTY_FUNCTION__))
7207 !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&((!S->getFallthroughHandler() && !S->getExceptionHandler
() && !S->getReturnStmtOnAllocFailure() &&
!S->getDeallocate() && "these nodes should not have been built yet"
) ? static_cast<void> (0) : __assert_fail ("!S->getFallthroughHandler() && !S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() && \"these nodes should not have been built yet\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 7208, __PRETTY_FUNCTION__))
7208 "these nodes should not have been built yet")((!S->getFallthroughHandler() && !S->getExceptionHandler
() && !S->getReturnStmtOnAllocFailure() &&
!S->getDeallocate() && "these nodes should not have been built yet"
) ? static_cast<void> (0) : __assert_fail ("!S->getFallthroughHandler() && !S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() && \"these nodes should not have been built yet\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 7208, __PRETTY_FUNCTION__))
;
7209 if (!Builder.buildDependentStatements())
7210 return StmtError();
7211 }
7212 } else {
7213 if (auto *OnFallthrough = S->getFallthroughHandler()) {
7214 StmtResult Res = getDerived().TransformStmt(OnFallthrough);
7215 if (Res.isInvalid())
7216 return StmtError();
7217 Builder.OnFallthrough = Res.get();
7218 }
7219
7220 if (auto *OnException = S->getExceptionHandler()) {
7221 StmtResult Res = getDerived().TransformStmt(OnException);
7222 if (Res.isInvalid())
7223 return StmtError();
7224 Builder.OnException = Res.get();
7225 }
7226
7227 if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
7228 StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
7229 if (Res.isInvalid())
7230 return StmtError();
7231 Builder.ReturnStmtOnAllocFailure = Res.get();
7232 }
7233
7234 // Transform any additional statements we may have already built
7235 assert(S->getAllocate() && S->getDeallocate() &&((S->getAllocate() && S->getDeallocate() &&
"allocation and deallocation calls must already be built") ?
static_cast<void> (0) : __assert_fail ("S->getAllocate() && S->getDeallocate() && \"allocation and deallocation calls must already be built\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 7236, __PRETTY_FUNCTION__))
7236 "allocation and deallocation calls must already be built")((S->getAllocate() && S->getDeallocate() &&
"allocation and deallocation calls must already be built") ?
static_cast<void> (0) : __assert_fail ("S->getAllocate() && S->getDeallocate() && \"allocation and deallocation calls must already be built\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 7236, __PRETTY_FUNCTION__))
;
7237 ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
7238 if (AllocRes.isInvalid())
7239 return StmtError();
7240 Builder.Allocate = AllocRes.get();
7241
7242 ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
7243 if (DeallocRes.isInvalid())
7244 return StmtError();
7245 Builder.Deallocate = DeallocRes.get();
7246
7247 assert(S->getResultDecl() && "ResultDecl must already be built")((S->getResultDecl() && "ResultDecl must already be built"
) ? static_cast<void> (0) : __assert_fail ("S->getResultDecl() && \"ResultDecl must already be built\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 7247, __PRETTY_FUNCTION__))
;
7248 StmtResult ResultDecl = getDerived().TransformStmt(S->getResultDecl());
7249 if (ResultDecl.isInvalid())
7250 return StmtError();
7251 Builder.ResultDecl = ResultDecl.get();
7252
7253 if (auto *ReturnStmt = S->getReturnStmt()) {
7254 StmtResult Res = getDerived().TransformStmt(ReturnStmt);
7255 if (Res.isInvalid())
7256 return StmtError();
7257 Builder.ReturnStmt = Res.get();
7258 }
7259 }
7260
7261 return getDerived().RebuildCoroutineBodyStmt(Builder);
7262}
7263
7264template<typename Derived>
7265StmtResult
7266TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
7267 ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
7268 /*NotCopyInit*/false);
7269 if (Result.isInvalid())
7270 return StmtError();
7271
7272 // Always rebuild; we don't know if this needs to be injected into a new
7273 // context or if the promise type has changed.
7274 return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
7275 S->isImplicit());
7276}
7277
7278template<typename Derived>
7279ExprResult
7280TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
7281 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7282 /*NotCopyInit*/false);
7283 if (Result.isInvalid())
7284 return ExprError();
7285
7286 // Always rebuild; we don't know if this needs to be injected into a new
7287 // context or if the promise type has changed.
7288 return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
7289 E->isImplicit());
7290}
7291
7292template <typename Derived>
7293ExprResult
7294TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
7295 ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
7296 /*NotCopyInit*/ false);
7297 if (OperandResult.isInvalid())
7298 return ExprError();
7299
7300 ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
7301 E->getOperatorCoawaitLookup());
7302
7303 if (LookupResult.isInvalid())
7304 return ExprError();
7305
7306 // Always rebuild; we don't know if this needs to be injected into a new
7307 // context or if the promise type has changed.
7308 return getDerived().RebuildDependentCoawaitExpr(
7309 E->getKeywordLoc(), OperandResult.get(),
7310 cast<UnresolvedLookupExpr>(LookupResult.get()));
7311}
7312
7313template<typename Derived>
7314ExprResult
7315TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7316 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7317 /*NotCopyInit*/false);
7318 if (Result.isInvalid())
7319 return ExprError();
7320
7321 // Always rebuild; we don't know if this needs to be injected into a new
7322 // context or if the promise type has changed.
7323 return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7324}
7325
7326// Objective-C Statements.
7327
7328template<typename Derived>
7329StmtResult
7330TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
7331 // Transform the body of the @try.
7332 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
7333 if (TryBody.isInvalid())
7334 return StmtError();
7335
7336 // Transform the @catch statements (if present).
7337 bool AnyCatchChanged = false;
7338 SmallVector<Stmt*, 8> CatchStmts;
7339 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
7340 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
7341 if (Catch.isInvalid())
7342 return StmtError();
7343 if (Catch.get() != S->getCatchStmt(I))
7344 AnyCatchChanged = true;
7345 CatchStmts.push_back(Catch.get());
7346 }
7347
7348 // Transform the @finally statement (if present).
7349 StmtResult Finally;
7350 if (S->getFinallyStmt()) {
7351 Finally = getDerived().TransformStmt(S->getFinallyStmt());
7352 if (Finally.isInvalid())
7353 return StmtError();
7354 }
7355
7356 // If nothing changed, just retain this statement.
7357 if (!getDerived().AlwaysRebuild() &&
7358 TryBody.get() == S->getTryBody() &&
7359 !AnyCatchChanged &&
7360 Finally.get() == S->getFinallyStmt())
7361 return S;
7362
7363 // Build a new statement.
7364 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
7365 CatchStmts, Finally.get());
7366}
7367
7368template<typename Derived>
7369StmtResult
7370TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7371 // Transform the @catch parameter, if there is one.
7372 VarDecl *Var = nullptr;
7373 if (VarDecl *FromVar = S->getCatchParamDecl()) {
7374 TypeSourceInfo *TSInfo = nullptr;
7375 if (FromVar->getTypeSourceInfo()) {
7376 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
7377 if (!TSInfo)
7378 return StmtError();
7379 }
7380
7381 QualType T;
7382 if (TSInfo)
7383 T = TSInfo->getType();
7384 else {
7385 T = getDerived().TransformType(FromVar->getType());
7386 if (T.isNull())
7387 return StmtError();
7388 }
7389
7390 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
7391 if (!Var)
7392 return StmtError();
7393 }
7394
7395 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
7396 if (Body.isInvalid())
7397 return StmtError();
7398
7399 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
7400 S->getRParenLoc(),
7401 Var, Body.get());
7402}
7403
7404template<typename Derived>
7405StmtResult
7406TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7407 // Transform the body.
7408 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
7409 if (Body.isInvalid())
7410 return StmtError();
7411
7412 // If nothing changed, just retain this statement.
7413 if (!getDerived().AlwaysRebuild() &&
7414 Body.get() == S->getFinallyBody())
7415 return S;
7416
7417 // Build a new statement.
7418 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
7419 Body.get());
7420}
7421
7422template<typename Derived>
7423StmtResult
7424TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7425 ExprResult Operand;
7426 if (S->getThrowExpr()) {
7427 Operand = getDerived().TransformExpr(S->getThrowExpr());
7428 if (Operand.isInvalid())
7429 return StmtError();
7430 }
7431
7432 if (!getDerived().AlwaysRebuild() &&
7433 Operand.get() == S->getThrowExpr())
7434 return S;
7435
7436 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
7437}
7438
7439template<typename Derived>
7440StmtResult
7441TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
7442 ObjCAtSynchronizedStmt *S) {
7443 // Transform the object we are locking.
7444 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
7445 if (Object.isInvalid())
7446 return StmtError();
7447 Object =
7448 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
7449 Object.get());
7450 if (Object.isInvalid())
7451 return StmtError();
7452
7453 // Transform the body.
7454 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
7455 if (Body.isInvalid())
7456 return StmtError();
7457
7458 // If nothing change, just retain the current statement.
7459 if (!getDerived().AlwaysRebuild() &&
7460 Object.get() == S->getSynchExpr() &&
7461 Body.get() == S->getSynchBody())
7462 return S;
7463
7464 // Build a new statement.
7465 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
7466 Object.get(), Body.get());
7467}
7468
7469template<typename Derived>
7470StmtResult
7471TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
7472 ObjCAutoreleasePoolStmt *S) {
7473 // Transform the body.
7474 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
7475 if (Body.isInvalid())
7476 return StmtError();
7477
7478 // If nothing changed, just retain this statement.
7479 if (!getDerived().AlwaysRebuild() &&
7480 Body.get() == S->getSubStmt())
7481 return S;
7482
7483 // Build a new statement.
7484 return getDerived().RebuildObjCAutoreleasePoolStmt(
7485 S->getAtLoc(), Body.get());
7486}
7487
7488template<typename Derived>
7489StmtResult
7490TreeTransform<Derived>::TransformObjCForCollectionStmt(
7491 ObjCForCollectionStmt *S) {
7492 // Transform the element statement.
7493 StmtResult Element =
7494 getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
7495 if (Element.isInvalid())
7496 return StmtError();
7497
7498 // Transform the collection expression.
7499 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
7500 if (Collection.isInvalid())
7501 return StmtError();
7502
7503 // Transform the body.
7504 StmtResult Body = getDerived().TransformStmt(S->getBody());
7505 if (Body.isInvalid())
7506 return StmtError();
7507
7508 // If nothing changed, just retain this statement.
7509 if (!getDerived().AlwaysRebuild() &&
7510 Element.get() == S->getElement() &&
7511 Collection.get() == S->getCollection() &&
7512 Body.get() == S->getBody())
7513 return S;
7514
7515 // Build a new statement.
7516 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
7517 Element.get(),
7518 Collection.get(),
7519 S->getRParenLoc(),
7520 Body.get());
7521}
7522
7523template <typename Derived>
7524StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
7525 // Transform the exception declaration, if any.
7526 VarDecl *Var = nullptr;
7527 if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
7528 TypeSourceInfo *T =
7529 getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
7530 if (!T)
7531 return StmtError();
7532
7533 Var = getDerived().RebuildExceptionDecl(
7534 ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
7535 ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
7536 if (!Var || Var->isInvalidDecl())
7537 return StmtError();
7538 }
7539
7540 // Transform the actual exception handler.
7541 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
7542 if (Handler.isInvalid())
7543 return StmtError();
7544
7545 if (!getDerived().AlwaysRebuild() && !Var &&
7546 Handler.get() == S->getHandlerBlock())
7547 return S;
7548
7549 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
7550}
7551
7552template <typename Derived>
7553StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
7554 // Transform the try block itself.
7555 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7556 if (TryBlock.isInvalid())
7557 return StmtError();
7558
7559 // Transform the handlers.
7560 bool HandlerChanged = false;
7561 SmallVector<Stmt *, 8> Handlers;
7562 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
7563 StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
7564 if (Handler.isInvalid())
7565 return StmtError();
7566
7567 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
7568 Handlers.push_back(Handler.getAs<Stmt>());
7569 }
7570
7571 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7572 !HandlerChanged)
7573 return S;
7574
7575 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
7576 Handlers);
7577}
7578
7579template<typename Derived>
7580StmtResult
7581TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
7582 StmtResult Init =
7583 S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
7584 if (Init.isInvalid())
7585 return StmtError();
7586
7587 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
7588 if (Range.isInvalid())
7589 return StmtError();
7590
7591 StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
7592 if (Begin.isInvalid())
7593 return StmtError();
7594 StmtResult End = getDerived().TransformStmt(S->getEndStmt());
7595 if (End.isInvalid())
7596 return StmtError();
7597
7598 ExprResult Cond = getDerived().TransformExpr(S->getCond());
7599 if (Cond.isInvalid())
7600 return StmtError();
7601 if (Cond.get())
7602 Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
7603 if (Cond.isInvalid())
7604 return StmtError();
7605 if (Cond.get())
7606 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
7607
7608 ExprResult Inc = getDerived().TransformExpr(S->getInc());
7609 if (Inc.isInvalid())
7610 return StmtError();
7611 if (Inc.get())
7612 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
7613
7614 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
7615 if (LoopVar.isInvalid())
7616 return StmtError();
7617
7618 StmtResult NewStmt = S;
7619 if (getDerived().AlwaysRebuild() ||
7620 Init.get() != S->getInit() ||
7621 Range.get() != S->getRangeStmt() ||
7622 Begin.get() != S->getBeginStmt() ||
7623 End.get() != S->getEndStmt() ||
7624 Cond.get() != S->getCond() ||
7625 Inc.get() != S->getInc() ||
7626 LoopVar.get() != S->getLoopVarStmt()) {
7627 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7628 S->getCoawaitLoc(), Init.get(),
7629 S->getColonLoc(), Range.get(),
7630 Begin.get(), End.get(),
7631 Cond.get(),
7632 Inc.get(), LoopVar.get(),
7633 S->getRParenLoc());
7634 if (NewStmt.isInvalid())
7635 return StmtError();
7636 }
7637
7638 StmtResult Body = getDerived().TransformStmt(S->getBody());
7639 if (Body.isInvalid())
7640 return StmtError();
7641
7642 // Body has changed but we didn't rebuild the for-range statement. Rebuild
7643 // it now so we have a new statement to attach the body to.
7644 if (Body.get() != S->getBody() && NewStmt.get() == S) {
7645 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7646 S->getCoawaitLoc(), Init.get(),
7647 S->getColonLoc(), Range.get(),
7648 Begin.get(), End.get(),
7649 Cond.get(),
7650 Inc.get(), LoopVar.get(),
7651 S->getRParenLoc());
7652 if (NewStmt.isInvalid())
7653 return StmtError();
7654 }
7655
7656 if (NewStmt.get() == S)
7657 return S;
7658
7659 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
7660}
7661
7662template<typename Derived>
7663StmtResult
7664TreeTransform<Derived>::TransformMSDependentExistsStmt(
7665 MSDependentExistsStmt *S) {
7666 // Transform the nested-name-specifier, if any.
7667 NestedNameSpecifierLoc QualifierLoc;
7668 if (S->getQualifierLoc()) {
7669 QualifierLoc
7670 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
7671 if (!QualifierLoc)
7672 return StmtError();
7673 }
7674
7675 // Transform the declaration name.
7676 DeclarationNameInfo NameInfo = S->getNameInfo();
7677 if (NameInfo.getName()) {
7678 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7679 if (!NameInfo.getName())
7680 return StmtError();
7681 }
7682
7683 // Check whether anything changed.
7684 if (!getDerived().AlwaysRebuild() &&
7685 QualifierLoc == S->getQualifierLoc() &&
7686 NameInfo.getName() == S->getNameInfo().getName())
7687 return S;
7688
7689 // Determine whether this name exists, if we can.
7690 CXXScopeSpec SS;
7691 SS.Adopt(QualifierLoc);
7692 bool Dependent = false;
7693 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
7694 case Sema::IER_Exists:
7695 if (S->isIfExists())
7696 break;
7697
7698 return new (getSema().Context) NullStmt(S->getKeywordLoc());
7699
7700 case Sema::IER_DoesNotExist:
7701 if (S->isIfNotExists())
7702 break;
7703
7704 return new (getSema().Context) NullStmt(S->getKeywordLoc());
7705
7706 case Sema::IER_Dependent:
7707 Dependent = true;
7708 break;
7709
7710 case Sema::IER_Error:
7711 return StmtError();
7712 }
7713
7714 // We need to continue with the instantiation, so do so now.
7715 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
7716 if (SubStmt.isInvalid())
7717 return StmtError();
7718
7719 // If we have resolved the name, just transform to the substatement.
7720 if (!Dependent)
7721 return SubStmt;
7722
7723 // The name is still dependent, so build a dependent expression again.
7724 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
7725 S->isIfExists(),
7726 QualifierLoc,
7727 NameInfo,
7728 SubStmt.get());
7729}
7730
7731template<typename Derived>
7732ExprResult
7733TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
7734 NestedNameSpecifierLoc QualifierLoc;
7735 if (E->getQualifierLoc()) {
7736 QualifierLoc
7737 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7738 if (!QualifierLoc)
7739 return ExprError();
7740 }
7741
7742 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
7743 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
7744 if (!PD)
7745 return ExprError();
7746
7747 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
7748 if (Base.isInvalid())
7749 return ExprError();
7750
7751 return new (SemaRef.getASTContext())
7752 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
7753 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
7754 QualifierLoc, E->getMemberLoc());
7755}
7756
7757template <typename Derived>
7758ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
7759 MSPropertySubscriptExpr *E) {
7760 auto BaseRes = getDerived().TransformExpr(E->getBase());
7761 if (BaseRes.isInvalid())
7762 return ExprError();
7763 auto IdxRes = getDerived().TransformExpr(E->getIdx());
7764 if (IdxRes.isInvalid())
7765 return ExprError();
7766
7767 if (!getDerived().AlwaysRebuild() &&
7768 BaseRes.get() == E->getBase() &&
7769 IdxRes.get() == E->getIdx())
7770 return E;
7771
7772 return getDerived().RebuildArraySubscriptExpr(
7773 BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
7774}
7775
7776template <typename Derived>
7777StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
7778 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7779 if (TryBlock.isInvalid())
7780 return StmtError();
7781
7782 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
7783 if (Handler.isInvalid())
7784 return StmtError();
7785
7786 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7787 Handler.get() == S->getHandler())
7788 return S;
7789
7790 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
7791 TryBlock.get(), Handler.get());
7792}
7793
7794template <typename Derived>
7795StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
7796 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7797 if (Block.isInvalid())
7798 return StmtError();
7799
7800 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
7801}
7802
7803template <typename Derived>
7804StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
7805 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
7806 if (FilterExpr.isInvalid())
7807 return StmtError();
7808
7809 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7810 if (Block.isInvalid())
7811 return StmtError();
7812
7813 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
7814 Block.get());
7815}
7816
7817template <typename Derived>
7818StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
7819 if (isa<SEHFinallyStmt>(Handler))
7820 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
7821 else
7822 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
7823}
7824
7825template<typename Derived>
7826StmtResult
7827TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
7828 return S;
7829}
7830
7831//===----------------------------------------------------------------------===//
7832// OpenMP directive transformation
7833//===----------------------------------------------------------------------===//
7834template <typename Derived>
7835StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
7836 OMPExecutableDirective *D) {
7837
7838 // Transform the clauses
7839 llvm::SmallVector<OMPClause *, 16> TClauses;
7840 ArrayRef<OMPClause *> Clauses = D->clauses();
7841 TClauses.reserve(Clauses.size());
7842 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
7843 I != E; ++I) {
7844 if (*I) {
7845 getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
7846 OMPClause *Clause = getDerived().TransformOMPClause(*I);
7847 getDerived().getSema().EndOpenMPClause();
7848 if (Clause)
7849 TClauses.push_back(Clause);
7850 } else {
7851 TClauses.push_back(nullptr);
7852 }
7853 }
7854 StmtResult AssociatedStmt;
7855 if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
7856 getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
7857 /*CurScope=*/nullptr);
7858 StmtResult Body;
7859 {
7860 Sema::CompoundScopeRAII CompoundScope(getSema());
7861 Stmt *CS = D->getInnermostCapturedStmt()->getCapturedStmt();
7862 Body = getDerived().TransformStmt(CS);
7863 }
7864 AssociatedStmt =
7865 getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
7866 if (AssociatedStmt.isInvalid()) {
7867 return StmtError();
7868 }
7869 }
7870 if (TClauses.size() != Clauses.size()) {
7871 return StmtError();
7872 }
7873
7874 // Transform directive name for 'omp critical' directive.
7875 DeclarationNameInfo DirName;
7876 if (D->getDirectiveKind() == OMPD_critical) {
7877 DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
7878 DirName = getDerived().TransformDeclarationNameInfo(DirName);
7879 }
7880 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
7881 if (D->getDirectiveKind() == OMPD_cancellation_point) {
7882 CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
7883 } else if (D->getDirectiveKind() == OMPD_cancel) {
7884 CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
7885 }
7886
7887 return getDerived().RebuildOMPExecutableDirective(
7888 D->getDirectiveKind(), DirName, CancelRegion, TClauses,
7889 AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
7890}
7891
7892template <typename Derived>
7893StmtResult
7894TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
7895 DeclarationNameInfo DirName;
7896 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
7897 D->getBeginLoc());
7898 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7899 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7900 return Res;
7901}
7902
7903template <typename Derived>
7904StmtResult
7905TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
7906 DeclarationNameInfo DirName;
7907 getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
7908 D->getBeginLoc());
7909 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7910 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7911 return Res;
7912}
7913
7914template <typename Derived>
7915StmtResult
7916TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
7917 DeclarationNameInfo DirName;
7918 getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
7919 D->getBeginLoc());
7920 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7921 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7922 return Res;
7923}
7924
7925template <typename Derived>
7926StmtResult
7927TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
7928 DeclarationNameInfo DirName;
7929 getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
7930 D->getBeginLoc());
7931 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7932 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7933 return Res;
7934}
7935
7936template <typename Derived>
7937StmtResult
7938TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
7939 DeclarationNameInfo DirName;
7940 getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
7941 D->getBeginLoc());
7942 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7943 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7944 return Res;
7945}
7946
7947template <typename Derived>
7948StmtResult
7949TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
7950 DeclarationNameInfo DirName;
7951 getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
7952 D->getBeginLoc());
7953 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7954 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7955 return Res;
7956}
7957
7958template <typename Derived>
7959StmtResult
7960TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
7961 DeclarationNameInfo DirName;
7962 getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
7963 D->getBeginLoc());
7964 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7965 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7966 return Res;
7967}
7968
7969template <typename Derived>
7970StmtResult
7971TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
7972 DeclarationNameInfo DirName;
7973 getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
7974 D->getBeginLoc());
7975 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7976 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7977 return Res;
7978}
7979
7980template <typename Derived>
7981StmtResult
7982TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
7983 getDerived().getSema().StartOpenMPDSABlock(
7984 OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
7985 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7986 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7987 return Res;
7988}
7989
7990template <typename Derived>
7991StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
7992 OMPParallelForDirective *D) {
7993 DeclarationNameInfo DirName;
7994 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
7995 nullptr, D->getBeginLoc());
7996 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7997 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7998 return Res;
7999}
8000
8001template <typename Derived>
8002StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8003 OMPParallelForSimdDirective *D) {
8004 DeclarationNameInfo DirName;
8005 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8006 nullptr, D->getBeginLoc());
8007 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8008 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8009 return Res;
8010}
8011
8012template <typename Derived>
8013StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8014 OMPParallelSectionsDirective *D) {
8015 DeclarationNameInfo DirName;
8016 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8017 nullptr, D->getBeginLoc());
8018 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8019 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8020 return Res;
8021}
8022
8023template <typename Derived>
8024StmtResult
8025TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8026 DeclarationNameInfo DirName;
8027 getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8028 D->getBeginLoc());
8029 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8030 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8031 return Res;
8032}
8033
8034template <typename Derived>
8035StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8036 OMPTaskyieldDirective *D) {
8037 DeclarationNameInfo DirName;
8038 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8039 D->getBeginLoc());
8040 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8041 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8042 return Res;
8043}
8044
8045template <typename Derived>
8046StmtResult
8047TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8048 DeclarationNameInfo DirName;
8049 getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8050 D->getBeginLoc());
8051 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8052 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8053 return Res;
8054}
8055
8056template <typename Derived>
8057StmtResult
8058TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
8059 DeclarationNameInfo DirName;
8060 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
8061 D->getBeginLoc());
8062 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8063 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8064 return Res;
8065}
8066
8067template <typename Derived>
8068StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
8069 OMPTaskgroupDirective *D) {
8070 DeclarationNameInfo DirName;
8071 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
8072 D->getBeginLoc());
8073 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8074 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8075 return Res;
8076}
8077
8078template <typename Derived>
8079StmtResult
8080TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
8081 DeclarationNameInfo DirName;
8082 getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
8083 D->getBeginLoc());
8084 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8085 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8086 return Res;
8087}
8088
8089template <typename Derived>
8090StmtResult
8091TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
8092 DeclarationNameInfo DirName;
8093 getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
8094 D->getBeginLoc());
8095 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8096 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8097 return Res;
8098}
8099
8100template <typename Derived>
8101StmtResult
8102TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
8103 DeclarationNameInfo DirName;
8104 getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
8105 D->getBeginLoc());
8106 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8107 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8108 return Res;
8109}
8110
8111template <typename Derived>
8112StmtResult
8113TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
8114 DeclarationNameInfo DirName;
8115 getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
8116 D->getBeginLoc());
8117 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8118 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8119 return Res;
8120}
8121
8122template <typename Derived>
8123StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
8124 OMPTargetDataDirective *D) {
8125 DeclarationNameInfo DirName;
8126 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
8127 D->getBeginLoc());
8128 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8129 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8130 return Res;
8131}
8132
8133template <typename Derived>
8134StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
8135 OMPTargetEnterDataDirective *D) {
8136 DeclarationNameInfo DirName;
8137 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
8138 nullptr, D->getBeginLoc());
8139 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8140 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8141 return Res;
8142}
8143
8144template <typename Derived>
8145StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
8146 OMPTargetExitDataDirective *D) {
8147 DeclarationNameInfo DirName;
8148 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
8149 nullptr, D->getBeginLoc());
8150 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8151 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8152 return Res;
8153}
8154
8155template <typename Derived>
8156StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
8157 OMPTargetParallelDirective *D) {
8158 DeclarationNameInfo DirName;
8159 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
8160 nullptr, D->getBeginLoc());
8161 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8162 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8163 return Res;
8164}
8165
8166template <typename Derived>
8167StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
8168 OMPTargetParallelForDirective *D) {
8169 DeclarationNameInfo DirName;
8170 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
8171 nullptr, D->getBeginLoc());
8172 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8173 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8174 return Res;
8175}
8176
8177template <typename Derived>
8178StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
8179 OMPTargetUpdateDirective *D) {
8180 DeclarationNameInfo DirName;
8181 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
8182 nullptr, D->getBeginLoc());
8183 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8184 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8185 return Res;
8186}
8187
8188template <typename Derived>
8189StmtResult
8190TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
8191 DeclarationNameInfo DirName;
8192 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
8193 D->getBeginLoc());
8194 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8195 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8196 return Res;
8197}
8198
8199template <typename Derived>
8200StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
8201 OMPCancellationPointDirective *D) {
8202 DeclarationNameInfo DirName;
8203 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
8204 nullptr, D->getBeginLoc());
8205 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8206 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8207 return Res;
8208}
8209
8210template <typename Derived>
8211StmtResult
8212TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
8213 DeclarationNameInfo DirName;
8214 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
8215 D->getBeginLoc());
8216 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8217 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8218 return Res;
8219}
8220
8221template <typename Derived>
8222StmtResult
8223TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
8224 DeclarationNameInfo DirName;
8225 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
8226 D->getBeginLoc());
8227 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8228 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8229 return Res;
8230}
8231
8232template <typename Derived>
8233StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
8234 OMPTaskLoopSimdDirective *D) {
8235 DeclarationNameInfo DirName;
8236 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
8237 nullptr, D->getBeginLoc());
8238 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8239 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8240 return Res;
8241}
8242
8243template <typename Derived>
8244StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
8245 OMPDistributeDirective *D) {
8246 DeclarationNameInfo DirName;
8247 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
8248 D->getBeginLoc());
8249 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8250 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8251 return Res;
8252}
8253
8254template <typename Derived>
8255StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
8256 OMPDistributeParallelForDirective *D) {
8257 DeclarationNameInfo DirName;
8258 getDerived().getSema().StartOpenMPDSABlock(
8259 OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8260 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8261 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8262 return Res;
8263}
8264
8265template <typename Derived>
8266StmtResult
8267TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
8268 OMPDistributeParallelForSimdDirective *D) {
8269 DeclarationNameInfo DirName;
8270 getDerived().getSema().StartOpenMPDSABlock(
8271 OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8272 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8273 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8274 return Res;
8275}
8276
8277template <typename Derived>
8278StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
8279 OMPDistributeSimdDirective *D) {
8280 DeclarationNameInfo DirName;
8281 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
8282 nullptr, D->getBeginLoc());
8283 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8284 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8285 return Res;
8286}
8287
8288template <typename Derived>
8289StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
8290 OMPTargetParallelForSimdDirective *D) {
8291 DeclarationNameInfo DirName;
8292 getDerived().getSema().StartOpenMPDSABlock(
8293 OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8294 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8295 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8296 return Res;
8297}
8298
8299template <typename Derived>
8300StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
8301 OMPTargetSimdDirective *D) {
8302 DeclarationNameInfo DirName;
8303 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
8304 D->getBeginLoc());
8305 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8306 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8307 return Res;
8308}
8309
8310template <typename Derived>
8311StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
8312 OMPTeamsDistributeDirective *D) {
8313 DeclarationNameInfo DirName;
8314 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
8315 nullptr, D->getBeginLoc());
8316 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8317 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8318 return Res;
8319}
8320
8321template <typename Derived>
8322StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
8323 OMPTeamsDistributeSimdDirective *D) {
8324 DeclarationNameInfo DirName;
8325 getDerived().getSema().StartOpenMPDSABlock(
8326 OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8327 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8328 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8329 return Res;
8330}
8331
8332template <typename Derived>
8333StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
8334 OMPTeamsDistributeParallelForSimdDirective *D) {
8335 DeclarationNameInfo DirName;
8336 getDerived().getSema().StartOpenMPDSABlock(
8337 OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
8338 D->getBeginLoc());
8339 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8340 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8341 return Res;
8342}
8343
8344template <typename Derived>
8345StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
8346 OMPTeamsDistributeParallelForDirective *D) {
8347 DeclarationNameInfo DirName;
8348 getDerived().getSema().StartOpenMPDSABlock(
8349 OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8350 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8351 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8352 return Res;
8353}
8354
8355template <typename Derived>
8356StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
8357 OMPTargetTeamsDirective *D) {
8358 DeclarationNameInfo DirName;
8359 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
8360 nullptr, D->getBeginLoc());
8361 auto Res = getDerived().TransformOMPExecutableDirective(D);
8362 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8363 return Res;
8364}
8365
8366template <typename Derived>
8367StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
8368 OMPTargetTeamsDistributeDirective *D) {
8369 DeclarationNameInfo DirName;
8370 getDerived().getSema().StartOpenMPDSABlock(
8371 OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
8372 auto Res = getDerived().TransformOMPExecutableDirective(D);
8373 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8374 return Res;
8375}
8376
8377template <typename Derived>
8378StmtResult
8379TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
8380 OMPTargetTeamsDistributeParallelForDirective *D) {
8381 DeclarationNameInfo DirName;
8382 getDerived().getSema().StartOpenMPDSABlock(
8383 OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
8384 D->getBeginLoc());
8385 auto Res = getDerived().TransformOMPExecutableDirective(D);
8386 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8387 return Res;
8388}
8389
8390template <typename Derived>
8391StmtResult TreeTransform<Derived>::
8392 TransformOMPTargetTeamsDistributeParallelForSimdDirective(
8393 OMPTargetTeamsDistributeParallelForSimdDirective *D) {
8394 DeclarationNameInfo DirName;
8395 getDerived().getSema().StartOpenMPDSABlock(
8396 OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
8397 D->getBeginLoc());
8398 auto Res = getDerived().TransformOMPExecutableDirective(D);
8399 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8400 return Res;
8401}
8402
8403template <typename Derived>
8404StmtResult
8405TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
8406 OMPTargetTeamsDistributeSimdDirective *D) {
8407 DeclarationNameInfo DirName;
8408 getDerived().getSema().StartOpenMPDSABlock(
8409 OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8410 auto Res = getDerived().TransformOMPExecutableDirective(D);
8411 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8412 return Res;
8413}
8414
8415
8416//===----------------------------------------------------------------------===//
8417// OpenMP clause transformation
8418//===----------------------------------------------------------------------===//
8419template <typename Derived>
8420OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
8421 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8422 if (Cond.isInvalid())
8423 return nullptr;
8424 return getDerived().RebuildOMPIfClause(
8425 C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
8426 C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
8427}
8428
8429template <typename Derived>
8430OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
8431 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8432 if (Cond.isInvalid())
8433 return nullptr;
8434 return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
8435 C->getLParenLoc(), C->getEndLoc());
8436}
8437
8438template <typename Derived>
8439OMPClause *
8440TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
8441 ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
8442 if (NumThreads.isInvalid())
8443 return nullptr;
8444 return getDerived().RebuildOMPNumThreadsClause(
8445 NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8446}
8447
8448template <typename Derived>
8449OMPClause *
8450TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
8451 ExprResult E = getDerived().TransformExpr(C->getSafelen());
8452 if (E.isInvalid())
8453 return nullptr;
8454 return getDerived().RebuildOMPSafelenClause(
8455 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8456}
8457
8458template <typename Derived>
8459OMPClause *
8460TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
8461 ExprResult E = getDerived().TransformExpr(C->getAllocator());
8462 if (E.isInvalid())
8463 return nullptr;
8464 return getDerived().RebuildOMPAllocatorClause(
8465 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8466}
8467
8468template <typename Derived>
8469OMPClause *
8470TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
8471 ExprResult E = getDerived().TransformExpr(C->getSimdlen());
8472 if (E.isInvalid())
8473 return nullptr;
8474 return getDerived().RebuildOMPSimdlenClause(
8475 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8476}
8477
8478template <typename Derived>
8479OMPClause *
8480TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
8481 ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
8482 if (E.isInvalid())
8483 return nullptr;
8484 return getDerived().RebuildOMPCollapseClause(
8485 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8486}
8487
8488template <typename Derived>
8489OMPClause *
8490TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
8491 return getDerived().RebuildOMPDefaultClause(
8492 C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
8493 C->getLParenLoc(), C->getEndLoc());
8494}
8495
8496template <typename Derived>
8497OMPClause *
8498TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
8499 return getDerived().RebuildOMPProcBindClause(
8500 C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
8501 C->getLParenLoc(), C->getEndLoc());
8502}
8503
8504template <typename Derived>
8505OMPClause *
8506TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
8507 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8508 if (E.isInvalid())
8509 return nullptr;
8510 return getDerived().RebuildOMPScheduleClause(
8511 C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
8512 C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
8513 C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
8514 C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
8515}
8516
8517template <typename Derived>
8518OMPClause *
8519TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
8520 ExprResult E;
8521 if (auto *Num = C->getNumForLoops()) {
8522 E = getDerived().TransformExpr(Num);
8523 if (E.isInvalid())
8524 return nullptr;
8525 }
8526 return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
8527 C->getLParenLoc(), E.get());
8528}
8529
8530template <typename Derived>
8531OMPClause *
8532TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
8533 // No need to rebuild this clause, no template-dependent parameters.
8534 return C;
8535}
8536
8537template <typename Derived>
8538OMPClause *
8539TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
8540 // No need to rebuild this clause, no template-dependent parameters.
8541 return C;
8542}
8543
8544template <typename Derived>
8545OMPClause *
8546TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
8547 // No need to rebuild this clause, no template-dependent parameters.
8548 return C;
8549}
8550
8551template <typename Derived>
8552OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
8553 // No need to rebuild this clause, no template-dependent parameters.
8554 return C;
8555}
8556
8557template <typename Derived>
8558OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
8559 // No need to rebuild this clause, no template-dependent parameters.
8560 return C;
8561}
8562
8563template <typename Derived>
8564OMPClause *
8565TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
8566 // No need to rebuild this clause, no template-dependent parameters.
8567 return C;
8568}
8569
8570template <typename Derived>
8571OMPClause *
8572TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
8573 // No need to rebuild this clause, no template-dependent parameters.
8574 return C;
8575}
8576
8577template <typename Derived>
8578OMPClause *
8579TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
8580 // No need to rebuild this clause, no template-dependent parameters.
8581 return C;
8582}
8583
8584template <typename Derived>
8585OMPClause *
8586TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
8587 // No need to rebuild this clause, no template-dependent parameters.
8588 return C;
8589}
8590
8591template <typename Derived>
8592OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
8593 // No need to rebuild this clause, no template-dependent parameters.
8594 return C;
8595}
8596
8597template <typename Derived>
8598OMPClause *
8599TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
8600 // No need to rebuild this clause, no template-dependent parameters.
8601 return C;
8602}
8603
8604template <typename Derived>
8605OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
8606 OMPUnifiedAddressClause *C) {
8607 llvm_unreachable("unified_address clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("unified_address clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 8607)
;
8608}
8609
8610template <typename Derived>
8611OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
8612 OMPUnifiedSharedMemoryClause *C) {
8613 llvm_unreachable(::llvm::llvm_unreachable_internal("unified_shared_memory clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 8614)
8614 "unified_shared_memory clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("unified_shared_memory clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 8614)
;
8615}
8616
8617template <typename Derived>
8618OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
8619 OMPReverseOffloadClause *C) {
8620 llvm_unreachable("reverse_offload clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("reverse_offload clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 8620)
;
8621}
8622
8623template <typename Derived>
8624OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
8625 OMPDynamicAllocatorsClause *C) {
8626 llvm_unreachable(::llvm::llvm_unreachable_internal("dynamic_allocators clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 8627)
8627 "dynamic_allocators clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("dynamic_allocators clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 8627)
;
8628}
8629
8630template <typename Derived>
8631OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
8632 OMPAtomicDefaultMemOrderClause *C) {
8633 llvm_unreachable(::llvm::llvm_unreachable_internal("atomic_default_mem_order clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 8634)
8634 "atomic_default_mem_order clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("atomic_default_mem_order clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 8634)
;
8635}
8636
8637template <typename Derived>
8638OMPClause *
8639TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
8640 llvm::SmallVector<Expr *, 16> Vars;
8641 Vars.reserve(C->varlist_size());
8642 for (auto *VE : C->varlists()) {
8643 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8644 if (EVar.isInvalid())
8645 return nullptr;
8646 Vars.push_back(EVar.get());
8647 }
8648 return getDerived().RebuildOMPPrivateClause(
8649 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8650}
8651
8652template <typename Derived>
8653OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
8654 OMPFirstprivateClause *C) {
8655 llvm::SmallVector<Expr *, 16> Vars;
8656 Vars.reserve(C->varlist_size());
8657 for (auto *VE : C->varlists()) {
8658 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8659 if (EVar.isInvalid())
8660 return nullptr;
8661 Vars.push_back(EVar.get());
8662 }
8663 return getDerived().RebuildOMPFirstprivateClause(
8664 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8665}
8666
8667template <typename Derived>
8668OMPClause *
8669TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
8670 llvm::SmallVector<Expr *, 16> Vars;
8671 Vars.reserve(C->varlist_size());
8672 for (auto *VE : C->varlists()) {
8673 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8674 if (EVar.isInvalid())
8675 return nullptr;
8676 Vars.push_back(EVar.get());
8677 }
8678 return getDerived().RebuildOMPLastprivateClause(
8679 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8680}
8681
8682template <typename Derived>
8683OMPClause *
8684TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
8685 llvm::SmallVector<Expr *, 16> Vars;
8686 Vars.reserve(C->varlist_size());
8687 for (auto *VE : C->varlists()) {
8688 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8689 if (EVar.isInvalid())
8690 return nullptr;
8691 Vars.push_back(EVar.get());
8692 }
8693 return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
8694 C->getLParenLoc(), C->getEndLoc());
8695}
8696
8697template <typename Derived>
8698OMPClause *
8699TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
8700 llvm::SmallVector<Expr *, 16> Vars;
8701 Vars.reserve(C->varlist_size());
8702 for (auto *VE : C->varlists()) {
8703 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8704 if (EVar.isInvalid())
8705 return nullptr;
8706 Vars.push_back(EVar.get());
8707 }
8708 CXXScopeSpec ReductionIdScopeSpec;
8709 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8710
8711 DeclarationNameInfo NameInfo = C->getNameInfo();
8712 if (NameInfo.getName()) {
8713 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8714 if (!NameInfo.getName())
8715 return nullptr;
8716 }
8717 // Build a list of all UDR decls with the same names ranged by the Scopes.
8718 // The Scope boundary is a duplication of the previous decl.
8719 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8720 for (auto *E : C->reduction_ops()) {
8721 // Transform all the decls.
8722 if (E) {
8723 auto *ULE = cast<UnresolvedLookupExpr>(E);
8724 UnresolvedSet<8> Decls;
8725 for (auto *D : ULE->decls()) {
8726 NamedDecl *InstD =
8727 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8728 Decls.addDecl(InstD, InstD->getAccess());
8729 }
8730 UnresolvedReductions.push_back(
8731 UnresolvedLookupExpr::Create(
8732 SemaRef.Context, /*NamingClass=*/nullptr,
8733 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
8734 NameInfo, /*ADL=*/true, ULE->isOverloaded(),
8735 Decls.begin(), Decls.end()));
8736 } else
8737 UnresolvedReductions.push_back(nullptr);
8738 }
8739 return getDerived().RebuildOMPReductionClause(
8740 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8741 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8742}
8743
8744template <typename Derived>
8745OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
8746 OMPTaskReductionClause *C) {
8747 llvm::SmallVector<Expr *, 16> Vars;
8748 Vars.reserve(C->varlist_size());
8749 for (auto *VE : C->varlists()) {
8750 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8751 if (EVar.isInvalid())
8752 return nullptr;
8753 Vars.push_back(EVar.get());
8754 }
8755 CXXScopeSpec ReductionIdScopeSpec;
8756 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8757
8758 DeclarationNameInfo NameInfo = C->getNameInfo();
8759 if (NameInfo.getName()) {
8760 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8761 if (!NameInfo.getName())
8762 return nullptr;
8763 }
8764 // Build a list of all UDR decls with the same names ranged by the Scopes.
8765 // The Scope boundary is a duplication of the previous decl.
8766 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8767 for (auto *E : C->reduction_ops()) {
8768 // Transform all the decls.
8769 if (E) {
8770 auto *ULE = cast<UnresolvedLookupExpr>(E);
8771 UnresolvedSet<8> Decls;
8772 for (auto *D : ULE->decls()) {
8773 NamedDecl *InstD =
8774 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8775 Decls.addDecl(InstD, InstD->getAccess());
8776 }
8777 UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8778 SemaRef.Context, /*NamingClass=*/nullptr,
8779 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8780 /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8781 } else
8782 UnresolvedReductions.push_back(nullptr);
8783 }
8784 return getDerived().RebuildOMPTaskReductionClause(
8785 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8786 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8787}
8788
8789template <typename Derived>
8790OMPClause *
8791TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
8792 llvm::SmallVector<Expr *, 16> Vars;
8793 Vars.reserve(C->varlist_size());
8794 for (auto *VE : C->varlists()) {
8795 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8796 if (EVar.isInvalid())
8797 return nullptr;
8798 Vars.push_back(EVar.get());
8799 }
8800 CXXScopeSpec ReductionIdScopeSpec;
8801 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8802
8803 DeclarationNameInfo NameInfo = C->getNameInfo();
8804 if (NameInfo.getName()) {
8805 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8806 if (!NameInfo.getName())
8807 return nullptr;
8808 }
8809 // Build a list of all UDR decls with the same names ranged by the Scopes.
8810 // The Scope boundary is a duplication of the previous decl.
8811 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8812 for (auto *E : C->reduction_ops()) {
8813 // Transform all the decls.
8814 if (E) {
8815 auto *ULE = cast<UnresolvedLookupExpr>(E);
8816 UnresolvedSet<8> Decls;
8817 for (auto *D : ULE->decls()) {
8818 NamedDecl *InstD =
8819 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8820 Decls.addDecl(InstD, InstD->getAccess());
8821 }
8822 UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8823 SemaRef.Context, /*NamingClass=*/nullptr,
8824 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8825 /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8826 } else
8827 UnresolvedReductions.push_back(nullptr);
8828 }
8829 return getDerived().RebuildOMPInReductionClause(
8830 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8831 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8832}
8833
8834template <typename Derived>
8835OMPClause *
8836TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
8837 llvm::SmallVector<Expr *, 16> Vars;
8838 Vars.reserve(C->varlist_size());
8839 for (auto *VE : C->varlists()) {
8840 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8841 if (EVar.isInvalid())
8842 return nullptr;
8843 Vars.push_back(EVar.get());
8844 }
8845 ExprResult Step = getDerived().TransformExpr(C->getStep());
8846 if (Step.isInvalid())
8847 return nullptr;
8848 return getDerived().RebuildOMPLinearClause(
8849 Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
8850 C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
8851}
8852
8853template <typename Derived>
8854OMPClause *
8855TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
8856 llvm::SmallVector<Expr *, 16> Vars;
8857 Vars.reserve(C->varlist_size());
8858 for (auto *VE : C->varlists()) {
8859 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8860 if (EVar.isInvalid())
8861 return nullptr;
8862 Vars.push_back(EVar.get());
8863 }
8864 ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
8865 if (Alignment.isInvalid())
8866 return nullptr;
8867 return getDerived().RebuildOMPAlignedClause(
8868 Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
8869 C->getColonLoc(), C->getEndLoc());
8870}
8871
8872template <typename Derived>
8873OMPClause *
8874TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
8875 llvm::SmallVector<Expr *, 16> Vars;
8876 Vars.reserve(C->varlist_size());
8877 for (auto *VE : C->varlists()) {
8878 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8879 if (EVar.isInvalid())
8880 return nullptr;
8881 Vars.push_back(EVar.get());
8882 }
8883 return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
8884 C->getLParenLoc(), C->getEndLoc());
8885}
8886
8887template <typename Derived>
8888OMPClause *
8889TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
8890 llvm::SmallVector<Expr *, 16> Vars;
8891 Vars.reserve(C->varlist_size());
8892 for (auto *VE : C->varlists()) {
8893 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8894 if (EVar.isInvalid())
8895 return nullptr;
8896 Vars.push_back(EVar.get());
8897 }
8898 return getDerived().RebuildOMPCopyprivateClause(
8899 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8900}
8901
8902template <typename Derived>
8903OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
8904 llvm::SmallVector<Expr *, 16> Vars;
8905 Vars.reserve(C->varlist_size());
8906 for (auto *VE : C->varlists()) {
8907 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8908 if (EVar.isInvalid())
8909 return nullptr;
8910 Vars.push_back(EVar.get());
8911 }
8912 return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
8913 C->getLParenLoc(), C->getEndLoc());
8914}
8915
8916template <typename Derived>
8917OMPClause *
8918TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
8919 llvm::SmallVector<Expr *, 16> Vars;
8920 Vars.reserve(C->varlist_size());
8921 for (auto *VE : C->varlists()) {
8922 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8923 if (EVar.isInvalid())
8924 return nullptr;
8925 Vars.push_back(EVar.get());
8926 }
8927 return getDerived().RebuildOMPDependClause(
8928 C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(), Vars,
8929 C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8930}
8931
8932template <typename Derived>
8933OMPClause *
8934TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
8935 ExprResult E = getDerived().TransformExpr(C->getDevice());
8936 if (E.isInvalid())
8937 return nullptr;
8938 return getDerived().RebuildOMPDeviceClause(E.get(), C->getBeginLoc(),
8939 C->getLParenLoc(), C->getEndLoc());
8940}
8941
8942template <typename Derived, class T>
8943bool transformOMPMappableExprListClause(
8944 TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
8945 llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
8946 DeclarationNameInfo &MapperIdInfo,
8947 llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
8948 // Transform expressions in the list.
8949 Vars.reserve(C->varlist_size());
8950 for (auto *VE : C->varlists()) {
8951 ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
8952 if (EVar.isInvalid())
8953 return true;
8954 Vars.push_back(EVar.get());
8955 }
8956 // Transform mapper scope specifier and identifier.
8957 NestedNameSpecifierLoc QualifierLoc;
8958 if (C->getMapperQualifierLoc()) {
8959 QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
8960 C->getMapperQualifierLoc());
8961 if (!QualifierLoc)
8962 return true;
8963 }
8964 MapperIdScopeSpec.Adopt(QualifierLoc);
8965 MapperIdInfo = C->getMapperIdInfo();
8966 if (MapperIdInfo.getName()) {
8967 MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
8968 if (!MapperIdInfo.getName())
8969 return true;
8970 }
8971 // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
8972 // the previous user-defined mapper lookup in dependent environment.
8973 for (auto *E : C->mapperlists()) {
8974 // Transform all the decls.
8975 if (E) {
8976 auto *ULE = cast<UnresolvedLookupExpr>(E);
8977 UnresolvedSet<8> Decls;
8978 for (auto *D : ULE->decls()) {
8979 NamedDecl *InstD =
8980 cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
8981 Decls.addDecl(InstD, InstD->getAccess());
8982 }
8983 UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
8984 TT.getSema().Context, /*NamingClass=*/nullptr,
8985 MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
8986 MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
8987 Decls.end()));
8988 } else {
8989 UnresolvedMappers.push_back(nullptr);
8990 }
8991 }
8992 return false;
8993}
8994
8995template <typename Derived>
8996OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
8997 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8998 llvm::SmallVector<Expr *, 16> Vars;
8999 CXXScopeSpec MapperIdScopeSpec;
9000 DeclarationNameInfo MapperIdInfo;
9001 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9002 if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
9003 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9004 return nullptr;
9005 return getDerived().RebuildOMPMapClause(
9006 C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), MapperIdScopeSpec,
9007 MapperIdInfo, C->getMapType(), C->isImplicitMapType(), C->getMapLoc(),
9008 C->getColonLoc(), Vars, Locs, UnresolvedMappers);
9009}
9010
9011template <typename Derived>
9012OMPClause *
9013TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
9014 Expr *Allocator = C->getAllocator();
9015 if (Allocator) {
9016 ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
9017 if (AllocatorRes.isInvalid())
9018 return nullptr;
9019 Allocator = AllocatorRes.get();
9020 }
9021 llvm::SmallVector<Expr *, 16> Vars;
9022 Vars.reserve(C->varlist_size());
9023 for (auto *VE : C->varlists()) {
9024 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9025 if (EVar.isInvalid())
9026 return nullptr;
9027 Vars.push_back(EVar.get());
9028 }
9029 return getDerived().RebuildOMPAllocateClause(
9030 Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9031 C->getEndLoc());
9032}
9033
9034template <typename Derived>
9035OMPClause *
9036TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
9037 ExprResult E = getDerived().TransformExpr(C->getNumTeams());
9038 if (E.isInvalid())
9039 return nullptr;
9040 return getDerived().RebuildOMPNumTeamsClause(
9041 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9042}
9043
9044template <typename Derived>
9045OMPClause *
9046TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
9047 ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
9048 if (E.isInvalid())
9049 return nullptr;
9050 return getDerived().RebuildOMPThreadLimitClause(
9051 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9052}
9053
9054template <typename Derived>
9055OMPClause *
9056TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
9057 ExprResult E = getDerived().TransformExpr(C->getPriority());
9058 if (E.isInvalid())
9059 return nullptr;
9060 return getDerived().RebuildOMPPriorityClause(
9061 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9062}
9063
9064template <typename Derived>
9065OMPClause *
9066TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
9067 ExprResult E = getDerived().TransformExpr(C->getGrainsize());
9068 if (E.isInvalid())
9069 return nullptr;
9070 return getDerived().RebuildOMPGrainsizeClause(
9071 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9072}
9073
9074template <typename Derived>
9075OMPClause *
9076TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
9077 ExprResult E = getDerived().TransformExpr(C->getNumTasks());
9078 if (E.isInvalid())
9079 return nullptr;
9080 return getDerived().RebuildOMPNumTasksClause(
9081 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9082}
9083
9084template <typename Derived>
9085OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
9086 ExprResult E = getDerived().TransformExpr(C->getHint());
9087 if (E.isInvalid())
9088 return nullptr;
9089 return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
9090 C->getLParenLoc(), C->getEndLoc());
9091}
9092
9093template <typename Derived>
9094OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
9095 OMPDistScheduleClause *C) {
9096 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9097 if (E.isInvalid())
9098 return nullptr;
9099 return getDerived().RebuildOMPDistScheduleClause(
9100 C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9101 C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9102}
9103
9104template <typename Derived>
9105OMPClause *
9106TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
9107 return C;
9108}
9109
9110template <typename Derived>
9111OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
9112 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9113 llvm::SmallVector<Expr *, 16> Vars;
9114 CXXScopeSpec MapperIdScopeSpec;
9115 DeclarationNameInfo MapperIdInfo;
9116 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9117 if (transformOMPMappableExprListClause<Derived, OMPToClause>(
9118 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9119 return nullptr;
9120 return getDerived().RebuildOMPToClause(Vars, MapperIdScopeSpec, MapperIdInfo,
9121 Locs, UnresolvedMappers);
9122}
9123
9124template <typename Derived>
9125OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
9126 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9127 llvm::SmallVector<Expr *, 16> Vars;
9128 CXXScopeSpec MapperIdScopeSpec;
9129 DeclarationNameInfo MapperIdInfo;
9130 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9131 if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
9132 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9133 return nullptr;
9134 return getDerived().RebuildOMPFromClause(
9135 Vars, MapperIdScopeSpec, MapperIdInfo, Locs, UnresolvedMappers);
9136}
9137
9138template <typename Derived>
9139OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
9140 OMPUseDevicePtrClause *C) {
9141 llvm::SmallVector<Expr *, 16> Vars;
9142 Vars.reserve(C->varlist_size());
9143 for (auto *VE : C->varlists()) {
9144 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9145 if (EVar.isInvalid())
9146 return nullptr;
9147 Vars.push_back(EVar.get());
9148 }
9149 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9150 return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
9151}
9152
9153template <typename Derived>
9154OMPClause *
9155TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
9156 llvm::SmallVector<Expr *, 16> Vars;
9157 Vars.reserve(C->varlist_size());
9158 for (auto *VE : C->varlists()) {
9159 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9160 if (EVar.isInvalid())
9161 return nullptr;
9162 Vars.push_back(EVar.get());
9163 }
9164 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9165 return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
9166}
9167
9168//===----------------------------------------------------------------------===//
9169// Expression transformation
9170//===----------------------------------------------------------------------===//
9171template<typename Derived>
9172ExprResult
9173TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
9174 return TransformExpr(E->getSubExpr());
9175}
9176
9177template<typename Derived>
9178ExprResult
9179TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
9180 if (!E->isTypeDependent())
9181 return E;
9182
9183 return getDerived().RebuildPredefinedExpr(E->getLocation(),
9184 E->getIdentKind());
9185}
9186
9187template<typename Derived>
9188ExprResult
9189TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
9190 NestedNameSpecifierLoc QualifierLoc;
9191 if (E->getQualifierLoc()) {
9192 QualifierLoc
9193 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9194 if (!QualifierLoc)
9195 return ExprError();
9196 }
9197
9198 ValueDecl *ND
9199 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
9200 E->getDecl()));
9201 if (!ND)
9202 return ExprError();
9203
9204 NamedDecl *Found = ND;
9205 if (E->getFoundDecl() != E->getDecl()) {
9206 Found = cast_or_null<NamedDecl>(
9207 getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
9208 if (!Found)
9209 return ExprError();
9210 }
9211
9212 DeclarationNameInfo NameInfo = E->getNameInfo();
9213 if (NameInfo.getName()) {
9214 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9215 if (!NameInfo.getName())
9216 return ExprError();
9217 }
9218
9219 if (!getDerived().AlwaysRebuild() &&
9220 QualifierLoc == E->getQualifierLoc() &&
9221 ND == E->getDecl() &&
9222 Found == E->getFoundDecl() &&
9223 NameInfo.getName() == E->getDecl()->getDeclName() &&
9224 !E->hasExplicitTemplateArgs()) {
9225
9226 // Mark it referenced in the new context regardless.
9227 // FIXME: this is a bit instantiation-specific.
9228 SemaRef.MarkDeclRefReferenced(E);
9229
9230 return E;
9231 }
9232
9233 TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
9234 if (E->hasExplicitTemplateArgs()) {
9235 TemplateArgs = &TransArgs;
9236 TransArgs.setLAngleLoc(E->getLAngleLoc());
9237 TransArgs.setRAngleLoc(E->getRAngleLoc());
9238 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9239 E->getNumTemplateArgs(),
9240 TransArgs))
9241 return ExprError();
9242 }
9243
9244 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
9245 Found, TemplateArgs);
9246}
9247
9248template<typename Derived>
9249ExprResult
9250TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
9251 return E;
9252}
9253
9254template <typename Derived>
9255ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
9256 FixedPointLiteral *E) {
9257 return E;
9258}
9259
9260template<typename Derived>
9261ExprResult
9262TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
9263 return E;
9264}
9265
9266template<typename Derived>
9267ExprResult
9268TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
9269 return E;
9270}
9271
9272template<typename Derived>
9273ExprResult
9274TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
9275 return E;
9276}
9277
9278template<typename Derived>
9279ExprResult
9280TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
9281 return E;
9282}
9283
9284template<typename Derived>
9285ExprResult
9286TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
9287 if (FunctionDecl *FD = E->getDirectCallee())
9288 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), FD);
9289 return SemaRef.MaybeBindToTemporary(E);
9290}
9291
9292template<typename Derived>
9293ExprResult
9294TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
9295 ExprResult ControllingExpr =
9296 getDerived().TransformExpr(E->getControllingExpr());
9297 if (ControllingExpr.isInvalid())
9298 return ExprError();
9299
9300 SmallVector<Expr *, 4> AssocExprs;
9301 SmallVector<TypeSourceInfo *, 4> AssocTypes;
9302 for (const GenericSelectionExpr::Association &Assoc : E->associations()) {
9303 TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
9304 if (TSI) {
9305 TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
9306 if (!AssocType)
9307 return ExprError();
9308 AssocTypes.push_back(AssocType);
9309 } else {
9310 AssocTypes.push_back(nullptr);
9311 }
9312
9313 ExprResult AssocExpr =
9314 getDerived().TransformExpr(Assoc.getAssociationExpr());
9315 if (AssocExpr.isInvalid())
9316 return ExprError();
9317 AssocExprs.push_back(AssocExpr.get());
9318 }
9319
9320 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
9321 E->getDefaultLoc(),
9322 E->getRParenLoc(),
9323 ControllingExpr.get(),
9324 AssocTypes,
9325 AssocExprs);
9326}
9327
9328template<typename Derived>
9329ExprResult
9330TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
9331 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9332 if (SubExpr.isInvalid())
9333 return ExprError();
9334
9335 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9336 return E;
9337
9338 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
9339 E->getRParen());
9340}
9341
9342/// The operand of a unary address-of operator has special rules: it's
9343/// allowed to refer to a non-static member of a class even if there's no 'this'
9344/// object available.
9345template<typename Derived>
9346ExprResult
9347TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
9348 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
9349 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
9350 else
9351 return getDerived().TransformExpr(E);
9352}
9353
9354template<typename Derived>
9355ExprResult
9356TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
9357 ExprResult SubExpr;
9358 if (E->getOpcode() == UO_AddrOf)
9359 SubExpr = TransformAddressOfOperand(E->getSubExpr());
9360 else
9361 SubExpr = TransformExpr(E->getSubExpr());
9362 if (SubExpr.isInvalid())
9363 return ExprError();
9364
9365 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9366 return E;
9367
9368 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
9369 E->getOpcode(),
9370 SubExpr.get());
9371}
9372
9373template<typename Derived>
9374ExprResult
9375TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
9376 // Transform the type.
9377 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
9378 if (!Type)
9379 return ExprError();
9380
9381 // Transform all of the components into components similar to what the
9382 // parser uses.
9383 // FIXME: It would be slightly more efficient in the non-dependent case to
9384 // just map FieldDecls, rather than requiring the rebuilder to look for
9385 // the fields again. However, __builtin_offsetof is rare enough in
9386 // template code that we don't care.
9387 bool ExprChanged = false;
9388 typedef Sema::OffsetOfComponent Component;
9389 SmallVector<Component, 4> Components;
9390 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
9391 const OffsetOfNode &ON = E->getComponent(I);
9392 Component Comp;
9393 Comp.isBrackets = true;
9394 Comp.LocStart = ON.getSourceRange().getBegin();
9395 Comp.LocEnd = ON.getSourceRange().getEnd();
9396 switch (ON.getKind()) {
9397 case OffsetOfNode::Array: {
9398 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
9399 ExprResult Index = getDerived().TransformExpr(FromIndex);
9400 if (Index.isInvalid())
9401 return ExprError();
9402
9403 ExprChanged = ExprChanged || Index.get() != FromIndex;
9404 Comp.isBrackets = true;
9405 Comp.U.E = Index.get();
9406 break;
9407 }
9408
9409 case OffsetOfNode::Field:
9410 case OffsetOfNode::Identifier:
9411 Comp.isBrackets = false;
9412 Comp.U.IdentInfo = ON.getFieldName();
9413 if (!Comp.U.IdentInfo)
9414 continue;
9415
9416 break;
9417
9418 case OffsetOfNode::Base:
9419 // Will be recomputed during the rebuild.
9420 continue;
9421 }
9422
9423 Components.push_back(Comp);
9424 }
9425
9426 // If nothing changed, retain the existing expression.
9427 if (!getDerived().AlwaysRebuild() &&
9428 Type == E->getTypeSourceInfo() &&
9429 !ExprChanged)
9430 return E;
9431
9432 // Build a new offsetof expression.
9433 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
9434 Components, E->getRParenLoc());
9435}
9436
9437template<typename Derived>
9438ExprResult
9439TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
9440 assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&(((!E->getSourceExpr() || getDerived().AlreadyTransformed(
E->getType())) && "opaque value expression requires transformation"
) ? static_cast<void> (0) : __assert_fail ("(!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) && \"opaque value expression requires transformation\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 9441, __PRETTY_FUNCTION__))
9441 "opaque value expression requires transformation")(((!E->getSourceExpr() || getDerived().AlreadyTransformed(
E->getType())) && "opaque value expression requires transformation"
) ? static_cast<void> (0) : __assert_fail ("(!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) && \"opaque value expression requires transformation\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 9441, __PRETTY_FUNCTION__))
;
9442 return E;
9443}
9444
9445template<typename Derived>
9446ExprResult
9447TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
9448 return E;
9449}
9450
9451template<typename Derived>
9452ExprResult
9453TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
9454 // Rebuild the syntactic form. The original syntactic form has
9455 // opaque-value expressions in it, so strip those away and rebuild
9456 // the result. This is a really awful way of doing this, but the
9457 // better solution (rebuilding the semantic expressions and
9458 // rebinding OVEs as necessary) doesn't work; we'd need
9459 // TreeTransform to not strip away implicit conversions.
9460 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
9461 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
9462 if (result.isInvalid()) return ExprError();
9463
9464 // If that gives us a pseudo-object result back, the pseudo-object
9465 // expression must have been an lvalue-to-rvalue conversion which we
9466 // should reapply.
9467 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
9468 result = SemaRef.checkPseudoObjectRValue(result.get());
9469
9470 return result;
9471}
9472
9473template<typename Derived>
9474ExprResult
9475TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
9476 UnaryExprOrTypeTraitExpr *E) {
9477 if (E->isArgumentType()) {
9478 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
9479
9480 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9481 if (!NewT)
9482 return ExprError();
9483
9484 if (!getDerived().AlwaysRebuild() && OldT == NewT)
9485 return E;
9486
9487 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
9488 E->getKind(),
9489 E->getSourceRange());
9490 }
9491
9492 // C++0x [expr.sizeof]p1:
9493 // The operand is either an expression, which is an unevaluated operand
9494 // [...]
9495 EnterExpressionEvaluationContext Unevaluated(
9496 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
9497 Sema::ReuseLambdaContextDecl);
9498
9499 // Try to recover if we have something like sizeof(T::X) where X is a type.
9500 // Notably, there must be *exactly* one set of parens if X is a type.
9501 TypeSourceInfo *RecoveryTSI = nullptr;
9502 ExprResult SubExpr;
9503 auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
9504 if (auto *DRE =
9505 PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
9506 SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
9507 PE, DRE, false, &RecoveryTSI);
9508 else
9509 SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
9510
9511 if (RecoveryTSI) {
9512 return getDerived().RebuildUnaryExprOrTypeTrait(
9513 RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
9514 } else if (SubExpr.isInvalid())
9515 return ExprError();
9516
9517 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
9518 return E;
9519
9520 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
9521 E->getOperatorLoc(),
9522 E->getKind(),
9523 E->getSourceRange());
9524}
9525
9526template<typename Derived>
9527ExprResult
9528TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
9529 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9530 if (LHS.isInvalid())
9531 return ExprError();
9532
9533 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9534 if (RHS.isInvalid())
9535 return ExprError();
9536
9537
9538 if (!getDerived().AlwaysRebuild() &&
9539 LHS.get() == E->getLHS() &&
9540 RHS.get() == E->getRHS())
9541 return E;
9542
9543 return getDerived().RebuildArraySubscriptExpr(
9544 LHS.get(),
9545 /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
9546}
9547
9548template <typename Derived>
9549ExprResult
9550TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
9551 ExprResult Base = getDerived().TransformExpr(E->getBase());
9552 if (Base.isInvalid())
9553 return ExprError();
9554
9555 ExprResult LowerBound;
9556 if (E->getLowerBound()) {
9557 LowerBound = getDerived().TransformExpr(E->getLowerBound());
9558 if (LowerBound.isInvalid())
9559 return ExprError();
9560 }
9561
9562 ExprResult Length;
9563 if (E->getLength()) {
9564 Length = getDerived().TransformExpr(E->getLength());
9565 if (Length.isInvalid())
9566 return ExprError();
9567 }
9568
9569 if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
9570 LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
9571 return E;
9572
9573 return getDerived().RebuildOMPArraySectionExpr(
9574 Base.get(), E->getBase()->getEndLoc(), LowerBound.get(), E->getColonLoc(),
9575 Length.get(), E->getRBracketLoc());
9576}
9577
9578template<typename Derived>
9579ExprResult
9580TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
9581 // Transform the callee.
9582 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9583 if (Callee.isInvalid())
9584 return ExprError();
9585
9586 // Transform arguments.
9587 bool ArgChanged = false;
9588 SmallVector<Expr*, 8> Args;
9589 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9590 &ArgChanged))
9591 return ExprError();
9592
9593 if (!getDerived().AlwaysRebuild() &&
9594 Callee.get() == E->getCallee() &&
9595 !ArgChanged)
9596 return SemaRef.MaybeBindToTemporary(E);
9597
9598 // FIXME: Wrong source location information for the '('.
9599 SourceLocation FakeLParenLoc
9600 = ((Expr *)Callee.get())->getSourceRange().getBegin();
9601 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
9602 Args,
9603 E->getRParenLoc());
9604}
9605
9606template<typename Derived>
9607ExprResult
9608TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
9609 ExprResult Base = getDerived().TransformExpr(E->getBase());
9610 if (Base.isInvalid())
9611 return ExprError();
9612
9613 NestedNameSpecifierLoc QualifierLoc;
9614 if (E->hasQualifier()) {
9615 QualifierLoc
9616 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9617
9618 if (!QualifierLoc)
9619 return ExprError();
9620 }
9621 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9622
9623 ValueDecl *Member
9624 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
9625 E->getMemberDecl()));
9626 if (!Member)
9627 return ExprError();
9628
9629 NamedDecl *FoundDecl = E->getFoundDecl();
9630 if (FoundDecl == E->getMemberDecl()) {
9631 FoundDecl = Member;
9632 } else {
9633 FoundDecl = cast_or_null<NamedDecl>(
9634 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
9635 if (!FoundDecl)
9636 return ExprError();
9637 }
9638
9639 if (!getDerived().AlwaysRebuild() &&
9640 Base.get() == E->getBase() &&
9641 QualifierLoc == E->getQualifierLoc() &&
9642 Member == E->getMemberDecl() &&
9643 FoundDecl == E->getFoundDecl() &&
9644 !E->hasExplicitTemplateArgs()) {
9645
9646 // Mark it referenced in the new context regardless.
9647 // FIXME: this is a bit instantiation-specific.
9648 SemaRef.MarkMemberReferenced(E);
9649
9650 return E;
9651 }
9652
9653 TemplateArgumentListInfo TransArgs;
9654 if (E->hasExplicitTemplateArgs()) {
9655 TransArgs.setLAngleLoc(E->getLAngleLoc());
9656 TransArgs.setRAngleLoc(E->getRAngleLoc());
9657 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9658 E->getNumTemplateArgs(),
9659 TransArgs))
9660 return ExprError();
9661 }
9662
9663 // FIXME: Bogus source location for the operator
9664 SourceLocation FakeOperatorLoc =
9665 SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
9666
9667 // FIXME: to do this check properly, we will need to preserve the
9668 // first-qualifier-in-scope here, just in case we had a dependent
9669 // base (and therefore couldn't do the check) and a
9670 // nested-name-qualifier (and therefore could do the lookup).
9671 NamedDecl *FirstQualifierInScope = nullptr;
9672 DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
9673 if (MemberNameInfo.getName()) {
9674 MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
9675 if (!MemberNameInfo.getName())
9676 return ExprError();
9677 }
9678
9679 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
9680 E->isArrow(),
9681 QualifierLoc,
9682 TemplateKWLoc,
9683 MemberNameInfo,
9684 Member,
9685 FoundDecl,
9686 (E->hasExplicitTemplateArgs()
9687 ? &TransArgs : nullptr),
9688 FirstQualifierInScope);
9689}
9690
9691template<typename Derived>
9692ExprResult
9693TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
9694 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9695 if (LHS.isInvalid())
9696 return ExprError();
9697
9698 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9699 if (RHS.isInvalid())
9700 return ExprError();
9701
9702 if (!getDerived().AlwaysRebuild() &&
9703 LHS.get() == E->getLHS() &&
9704 RHS.get() == E->getRHS())
9705 return E;
9706
9707 Sema::FPContractStateRAII FPContractState(getSema());
9708 getSema().FPFeatures = E->getFPFeatures();
9709
9710 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
9711 LHS.get(), RHS.get());
9712}
9713
9714template<typename Derived>
9715ExprResult
9716TreeTransform<Derived>::TransformCompoundAssignOperator(
9717 CompoundAssignOperator *E) {
9718 return getDerived().TransformBinaryOperator(E);
9719}
9720
9721template<typename Derived>
9722ExprResult TreeTransform<Derived>::
9723TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
9724 // Just rebuild the common and RHS expressions and see whether we
9725 // get any changes.
9726
9727 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
9728 if (commonExpr.isInvalid())
9729 return ExprError();
9730
9731 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
9732 if (rhs.isInvalid())
9733 return ExprError();
9734
9735 if (!getDerived().AlwaysRebuild() &&
9736 commonExpr.get() == e->getCommon() &&
9737 rhs.get() == e->getFalseExpr())
9738 return e;
9739
9740 return getDerived().RebuildConditionalOperator(commonExpr.get(),
9741 e->getQuestionLoc(),
9742 nullptr,
9743 e->getColonLoc(),
9744 rhs.get());
9745}
9746
9747template<typename Derived>
9748ExprResult
9749TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
9750 ExprResult Cond = getDerived().TransformExpr(E->getCond());
9751 if (Cond.isInvalid())
9752 return ExprError();
9753
9754 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9755 if (LHS.isInvalid())
9756 return ExprError();
9757
9758 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9759 if (RHS.isInvalid())
9760 return ExprError();
9761
9762 if (!getDerived().AlwaysRebuild() &&
9763 Cond.get() == E->getCond() &&
9764 LHS.get() == E->getLHS() &&
9765 RHS.get() == E->getRHS())
9766 return E;
9767
9768 return getDerived().RebuildConditionalOperator(Cond.get(),
9769 E->getQuestionLoc(),
9770 LHS.get(),
9771 E->getColonLoc(),
9772 RHS.get());
9773}
9774
9775template<typename Derived>
9776ExprResult
9777TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
9778 // Implicit casts are eliminated during transformation, since they
9779 // will be recomputed by semantic analysis after transformation.
9780 return getDerived().TransformExpr(E->getSubExprAsWritten());
9781}
9782
9783template<typename Derived>
9784ExprResult
9785TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
9786 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
9787 if (!Type)
9788 return ExprError();
9789
9790 ExprResult SubExpr
9791 = getDerived().TransformExpr(E->getSubExprAsWritten());
9792 if (SubExpr.isInvalid())
9793 return ExprError();
9794
9795 if (!getDerived().AlwaysRebuild() &&
9796 Type == E->getTypeInfoAsWritten() &&
9797 SubExpr.get() == E->getSubExpr())
9798 return E;
9799
9800 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
9801 Type,
9802 E->getRParenLoc(),
9803 SubExpr.get());
9804}
9805
9806template<typename Derived>
9807ExprResult
9808TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
9809 TypeSourceInfo *OldT = E->getTypeSourceInfo();
9810 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9811 if (!NewT)
9812 return ExprError();
9813
9814 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
9815 if (Init.isInvalid())
9816 return ExprError();
9817
9818 if (!getDerived().AlwaysRebuild() &&
9819 OldT == NewT &&
9820 Init.get() == E->getInitializer())
9821 return SemaRef.MaybeBindToTemporary(E);
9822
9823 // Note: the expression type doesn't necessarily match the
9824 // type-as-written, but that's okay, because it should always be
9825 // derivable from the initializer.
9826
9827 return getDerived().RebuildCompoundLiteralExpr(
9828 E->getLParenLoc(), NewT,
9829 /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
9830}
9831
9832template<typename Derived>
9833ExprResult
9834TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
9835 ExprResult Base = getDerived().TransformExpr(E->getBase());
9836 if (Base.isInvalid())
9837 return ExprError();
9838
9839 if (!getDerived().AlwaysRebuild() &&
9840 Base.get() == E->getBase())
9841 return E;
9842
9843 // FIXME: Bad source location
9844 SourceLocation FakeOperatorLoc =
9845 SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
9846 return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
9847 E->getAccessorLoc(),
9848 E->getAccessor());
9849}
9850
9851template<typename Derived>
9852ExprResult
9853TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
9854 if (InitListExpr *Syntactic = E->getSyntacticForm())
9855 E = Syntactic;
9856
9857 bool InitChanged = false;
9858
9859 EnterExpressionEvaluationContext Context(
9860 getSema(), EnterExpressionEvaluationContext::InitList);
9861
9862 SmallVector<Expr*, 4> Inits;
9863 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
9864 Inits, &InitChanged))
9865 return ExprError();
9866
9867 if (!getDerived().AlwaysRebuild() && !InitChanged) {
9868 // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
9869 // in some cases. We can't reuse it in general, because the syntactic and
9870 // semantic forms are linked, and we can't know that semantic form will
9871 // match even if the syntactic form does.
9872 }
9873
9874 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
9875 E->getRBraceLoc());
9876}
9877
9878template<typename Derived>
9879ExprResult
9880TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
9881 Designation Desig;
9882
9883 // transform the initializer value
9884 ExprResult Init = getDerived().TransformExpr(E->getInit());
9885 if (Init.isInvalid())
9886 return ExprError();
9887
9888 // transform the designators.
9889 SmallVector<Expr*, 4> ArrayExprs;
9890 bool ExprChanged = false;
9891 for (const DesignatedInitExpr::Designator &D : E->designators()) {
9892 if (D.isFieldDesignator()) {
9893 Desig.AddDesignator(Designator::getField(D.getFieldName(),
9894 D.getDotLoc(),
9895 D.getFieldLoc()));
9896 if (D.getField()) {
9897 FieldDecl *Field = cast_or_null<FieldDecl>(
9898 getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
9899 if (Field != D.getField())
9900 // Rebuild the expression when the transformed FieldDecl is
9901 // different to the already assigned FieldDecl.
9902 ExprChanged = true;
9903 } else {
9904 // Ensure that the designator expression is rebuilt when there isn't
9905 // a resolved FieldDecl in the designator as we don't want to assign
9906 // a FieldDecl to a pattern designator that will be instantiated again.
9907 ExprChanged = true;
9908 }
9909 continue;
9910 }
9911
9912 if (D.isArrayDesignator()) {
9913 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
9914 if (Index.isInvalid())
9915 return ExprError();
9916
9917 Desig.AddDesignator(
9918 Designator::getArray(Index.get(), D.getLBracketLoc()));
9919
9920 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
9921 ArrayExprs.push_back(Index.get());
9922 continue;
9923 }
9924
9925 assert(D.isArrayRangeDesignator() && "New kind of designator?")((D.isArrayRangeDesignator() && "New kind of designator?"
) ? static_cast<void> (0) : __assert_fail ("D.isArrayRangeDesignator() && \"New kind of designator?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 9925, __PRETTY_FUNCTION__))
;
9926 ExprResult Start
9927 = getDerived().TransformExpr(E->getArrayRangeStart(D));
9928 if (Start.isInvalid())
9929 return ExprError();
9930
9931 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
9932 if (End.isInvalid())
9933 return ExprError();
9934
9935 Desig.AddDesignator(Designator::getArrayRange(Start.get(),
9936 End.get(),
9937 D.getLBracketLoc(),
9938 D.getEllipsisLoc()));
9939
9940 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
9941 End.get() != E->getArrayRangeEnd(D);
9942
9943 ArrayExprs.push_back(Start.get());
9944 ArrayExprs.push_back(End.get());
9945 }
9946
9947 if (!getDerived().AlwaysRebuild() &&
9948 Init.get() == E->getInit() &&
9949 !ExprChanged)
9950 return E;
9951
9952 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
9953 E->getEqualOrColonLoc(),
9954 E->usesGNUSyntax(), Init.get());
9955}
9956
9957// Seems that if TransformInitListExpr() only works on the syntactic form of an
9958// InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
9959template<typename Derived>
9960ExprResult
9961TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
9962 DesignatedInitUpdateExpr *E) {
9963 llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "::llvm::llvm_unreachable_internal("Unexpected DesignatedInitUpdateExpr in syntactic form of "
"initializer", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 9964)
9964 "initializer")::llvm::llvm_unreachable_internal("Unexpected DesignatedInitUpdateExpr in syntactic form of "
"initializer", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 9964)
;
9965 return ExprError();
9966}
9967
9968template<typename Derived>
9969ExprResult
9970TreeTransform<Derived>::TransformNoInitExpr(
9971 NoInitExpr *E) {
9972 llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer")::llvm::llvm_unreachable_internal("Unexpected NoInitExpr in syntactic form of initializer"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 9972)
;
9973 return ExprError();
9974}
9975
9976template<typename Derived>
9977ExprResult
9978TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
9979 llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer")::llvm::llvm_unreachable_internal("Unexpected ArrayInitLoopExpr outside of initializer"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 9979)
;
9980 return ExprError();
9981}
9982
9983template<typename Derived>
9984ExprResult
9985TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
9986 llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer")::llvm::llvm_unreachable_internal("Unexpected ArrayInitIndexExpr outside of initializer"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 9986)
;
9987 return ExprError();
9988}
9989
9990template<typename Derived>
9991ExprResult
9992TreeTransform<Derived>::TransformImplicitValueInitExpr(
9993 ImplicitValueInitExpr *E) {
9994 TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
9995
9996 // FIXME: Will we ever have proper type location here? Will we actually
9997 // need to transform the type?
9998 QualType T = getDerived().TransformType(E->getType());
9999 if (T.isNull())
10000 return ExprError();
10001
10002 if (!getDerived().AlwaysRebuild() &&
10003 T == E->getType())
10004 return E;
10005
10006 return getDerived().RebuildImplicitValueInitExpr(T);
10007}
10008
10009template<typename Derived>
10010ExprResult
10011TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
10012 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
10013 if (!TInfo)
10014 return ExprError();
10015
10016 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10017 if (SubExpr.isInvalid())
10018 return ExprError();
10019
10020 if (!getDerived().AlwaysRebuild() &&
10021 TInfo == E->getWrittenTypeInfo() &&
10022 SubExpr.get() == E->getSubExpr())
10023 return E;
10024
10025 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
10026 TInfo, E->getRParenLoc());
10027}
10028
10029template<typename Derived>
10030ExprResult
10031TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
10032 bool ArgumentChanged = false;
10033 SmallVector<Expr*, 4> Inits;
10034 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
10035 &ArgumentChanged))
10036 return ExprError();
10037
10038 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
10039 Inits,
10040 E->getRParenLoc());
10041}
10042
10043/// Transform an address-of-label expression.
10044///
10045/// By default, the transformation of an address-of-label expression always
10046/// rebuilds the expression, so that the label identifier can be resolved to
10047/// the corresponding label statement by semantic analysis.
10048template<typename Derived>
10049ExprResult
10050TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
10051 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
10052 E->getLabel());
10053 if (!LD)
10054 return ExprError();
10055
10056 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
10057 cast<LabelDecl>(LD));
10058}
10059
10060template<typename Derived>
10061ExprResult
10062TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
10063 SemaRef.ActOnStartStmtExpr();
10064 StmtResult SubStmt
10065 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
10066 if (SubStmt.isInvalid()) {
10067 SemaRef.ActOnStmtExprError();
10068 return ExprError();
10069 }
10070
10071 if (!getDerived().AlwaysRebuild() &&
10072 SubStmt.get() == E->getSubStmt()) {
10073 // Calling this an 'error' is unintuitive, but it does the right thing.
10074 SemaRef.ActOnStmtExprError();
10075 return SemaRef.MaybeBindToTemporary(E);
10076 }
10077
10078 return getDerived().RebuildStmtExpr(E->getLParenLoc(),
10079 SubStmt.get(),
10080 E->getRParenLoc());
10081}
10082
10083template<typename Derived>
10084ExprResult
10085TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
10086 ExprResult Cond = getDerived().TransformExpr(E->getCond());
10087 if (Cond.isInvalid())
10088 return ExprError();
10089
10090 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10091 if (LHS.isInvalid())
10092 return ExprError();
10093
10094 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10095 if (RHS.isInvalid())
10096 return ExprError();
10097
10098 if (!getDerived().AlwaysRebuild() &&
10099 Cond.get() == E->getCond() &&
10100 LHS.get() == E->getLHS() &&
10101 RHS.get() == E->getRHS())
10102 return E;
10103
10104 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
10105 Cond.get(), LHS.get(), RHS.get(),
10106 E->getRParenLoc());
10107}
10108
10109template<typename Derived>
10110ExprResult
10111TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
10112 return E;
10113}
10114
10115template<typename Derived>
10116ExprResult
10117TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10118 switch (E->getOperator()) {
10119 case OO_New:
10120 case OO_Delete:
10121 case OO_Array_New:
10122 case OO_Array_Delete:
10123 llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr")::llvm::llvm_unreachable_internal("new and delete operators cannot use CXXOperatorCallExpr"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 10123)
;
10124
10125 case OO_Call: {
10126 // This is a call to an object's operator().
10127 assert(E->getNumArgs() >= 1 && "Object call is missing arguments")((E->getNumArgs() >= 1 && "Object call is missing arguments"
) ? static_cast<void> (0) : __assert_fail ("E->getNumArgs() >= 1 && \"Object call is missing arguments\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 10127, __PRETTY_FUNCTION__))
;
10128
10129 // Transform the object itself.
10130 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
10131 if (Object.isInvalid())
10132 return ExprError();
10133
10134 // FIXME: Poor location information
10135 SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
10136 static_cast<Expr *>(Object.get())->getEndLoc());
10137
10138 // Transform the call arguments.
10139 SmallVector<Expr*, 8> Args;
10140 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
10141 Args))
10142 return ExprError();
10143
10144 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
10145 E->getEndLoc());
10146 }
10147
10148#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10149 case OO_##Name:
10150#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
10151#include "clang/Basic/OperatorKinds.def"
10152 case OO_Subscript:
10153 // Handled below.
10154 break;
10155
10156 case OO_Conditional:
10157 llvm_unreachable("conditional operator is not actually overloadable")::llvm::llvm_unreachable_internal("conditional operator is not actually overloadable"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 10157)
;
10158
10159 case OO_None:
10160 case NUM_OVERLOADED_OPERATORS:
10161 llvm_unreachable("not an overloaded operator?")::llvm::llvm_unreachable_internal("not an overloaded operator?"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 10161)
;
10162 }
10163
10164 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10165 if (Callee.isInvalid())
10166 return ExprError();
10167
10168 ExprResult First;
10169 if (E->getOperator() == OO_Amp)
10170 First = getDerived().TransformAddressOfOperand(E->getArg(0));
10171 else
10172 First = getDerived().TransformExpr(E->getArg(0));
10173 if (First.isInvalid())
10174 return ExprError();
10175
10176 ExprResult Second;
10177 if (E->getNumArgs() == 2) {
10178 Second = getDerived().TransformExpr(E->getArg(1));
10179 if (Second.isInvalid())
10180 return ExprError();
10181 }
10182
10183 if (!getDerived().AlwaysRebuild() &&
10184 Callee.get() == E->getCallee() &&
10185 First.get() == E->getArg(0) &&
10186 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
10187 return SemaRef.MaybeBindToTemporary(E);
10188
10189 Sema::FPContractStateRAII FPContractState(getSema());
10190 getSema().FPFeatures = E->getFPFeatures();
10191
10192 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
10193 E->getOperatorLoc(),
10194 Callee.get(),
10195 First.get(),
10196 Second.get());
10197}
10198
10199template<typename Derived>
10200ExprResult
10201TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
10202 return getDerived().TransformCallExpr(E);
10203}
10204
10205template <typename Derived>
10206ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
10207 bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
10208 getSema().CurContext != E->getParentContext();
10209
10210 if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
10211 return E;
10212
10213 return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getBeginLoc(),
10214 E->getEndLoc(),
10215 getSema().CurContext);
10216}
10217
10218template<typename Derived>
10219ExprResult
10220TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
10221 // Transform the callee.
10222 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10223 if (Callee.isInvalid())
10224 return ExprError();
10225
10226 // Transform exec config.
10227 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
10228 if (EC.isInvalid())
10229 return ExprError();
10230
10231 // Transform arguments.
10232 bool ArgChanged = false;
10233 SmallVector<Expr*, 8> Args;
10234 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10235 &ArgChanged))
10236 return ExprError();
10237
10238 if (!getDerived().AlwaysRebuild() &&
10239 Callee.get() == E->getCallee() &&
10240 !ArgChanged)
10241 return SemaRef.MaybeBindToTemporary(E);
10242
10243 // FIXME: Wrong source location information for the '('.
10244 SourceLocation FakeLParenLoc
10245 = ((Expr *)Callee.get())->getSourceRange().getBegin();
10246 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
10247 Args,
10248 E->getRParenLoc(), EC.get());
10249}
10250
10251template<typename Derived>
10252ExprResult
10253TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
10254 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
10255 if (!Type)
10256 return ExprError();
10257
10258 ExprResult SubExpr
10259 = getDerived().TransformExpr(E->getSubExprAsWritten());
10260 if (SubExpr.isInvalid())
10261 return ExprError();
10262
10263 if (!getDerived().AlwaysRebuild() &&
10264 Type == E->getTypeInfoAsWritten() &&
10265 SubExpr.get() == E->getSubExpr())
10266 return E;
10267 return getDerived().RebuildCXXNamedCastExpr(
10268 E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
10269 Type, E->getAngleBrackets().getEnd(),
10270 // FIXME. this should be '(' location
10271 E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
10272}
10273
10274template<typename Derived>
10275ExprResult
10276TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
10277 TypeSourceInfo *TSI =
10278 getDerived().TransformType(BCE->getTypeInfoAsWritten());
10279 if (!TSI)
10280 return ExprError();
10281
10282 ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
10283 if (Sub.isInvalid())
10284 return ExprError();
10285
10286 return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
10287 Sub.get(), BCE->getEndLoc());
10288}
10289
10290template<typename Derived>
10291ExprResult
10292TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
10293 return getDerived().TransformCXXNamedCastExpr(E);
10294}
10295
10296template<typename Derived>
10297ExprResult
10298TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
10299 return getDerived().TransformCXXNamedCastExpr(E);
10300}
10301
10302template<typename Derived>
10303ExprResult
10304TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
10305 CXXReinterpretCastExpr *E) {
10306 return getDerived().TransformCXXNamedCastExpr(E);
10307}
10308
10309template<typename Derived>
10310ExprResult
10311TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
10312 return getDerived().TransformCXXNamedCastExpr(E);
10313}
10314
10315template<typename Derived>
10316ExprResult
10317TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
10318 CXXFunctionalCastExpr *E) {
10319 TypeSourceInfo *Type =
10320 getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
10321 if (!Type)
10322 return ExprError();
10323
10324 ExprResult SubExpr
10325 = getDerived().TransformExpr(E->getSubExprAsWritten());
10326 if (SubExpr.isInvalid())
10327 return ExprError();
10328
10329 if (!getDerived().AlwaysRebuild() &&
10330 Type == E->getTypeInfoAsWritten() &&
10331 SubExpr.get() == E->getSubExpr())
10332 return E;
10333
10334 return getDerived().RebuildCXXFunctionalCastExpr(Type,
10335 E->getLParenLoc(),
10336 SubExpr.get(),
10337 E->getRParenLoc(),
10338 E->isListInitialization());
10339}
10340
10341template<typename Derived>
10342ExprResult
10343TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
10344 if (E->isTypeOperand()) {
10345 TypeSourceInfo *TInfo
10346 = getDerived().TransformType(E->getTypeOperandSourceInfo());
10347 if (!TInfo)
10348 return ExprError();
10349
10350 if (!getDerived().AlwaysRebuild() &&
10351 TInfo == E->getTypeOperandSourceInfo())
10352 return E;
10353
10354 return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10355 TInfo, E->getEndLoc());
10356 }
10357
10358 // We don't know whether the subexpression is potentially evaluated until
10359 // after we perform semantic analysis. We speculatively assume it is
10360 // unevaluated; it will get fixed later if the subexpression is in fact
10361 // potentially evaluated.
10362 EnterExpressionEvaluationContext Unevaluated(
10363 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
10364 Sema::ReuseLambdaContextDecl);
10365
10366 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10367 if (SubExpr.isInvalid())
10368 return ExprError();
10369
10370 if (!getDerived().AlwaysRebuild() &&
10371 SubExpr.get() == E->getExprOperand())
10372 return E;
10373
10374 return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10375 SubExpr.get(), E->getEndLoc());
10376}
10377
10378template<typename Derived>
10379ExprResult
10380TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
10381 if (E->isTypeOperand()) {
10382 TypeSourceInfo *TInfo
10383 = getDerived().TransformType(E->getTypeOperandSourceInfo());
10384 if (!TInfo)
10385 return ExprError();
10386
10387 if (!getDerived().AlwaysRebuild() &&
10388 TInfo == E->getTypeOperandSourceInfo())
10389 return E;
10390
10391 return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10392 TInfo, E->getEndLoc());
10393 }
10394
10395 EnterExpressionEvaluationContext Unevaluated(
10396 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10397
10398 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10399 if (SubExpr.isInvalid())
10400 return ExprError();
10401
10402 if (!getDerived().AlwaysRebuild() &&
10403 SubExpr.get() == E->getExprOperand())
10404 return E;
10405
10406 return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10407 SubExpr.get(), E->getEndLoc());
10408}
10409
10410template<typename Derived>
10411ExprResult
10412TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
10413 return E;
10414}
10415
10416template<typename Derived>
10417ExprResult
10418TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
10419 CXXNullPtrLiteralExpr *E) {
10420 return E;
10421}
10422
10423template<typename Derived>
10424ExprResult
10425TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
10426 QualType T = getSema().getCurrentThisType();
10427
10428 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
10429 // Mark it referenced in the new context regardless.
10430 // FIXME: this is a bit instantiation-specific.
10431 getSema().MarkThisReferenced(E);
10432 return E;
10433 }
10434
10435 return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
10436}
10437
10438template<typename Derived>
10439ExprResult
10440TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
10441 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10442 if (SubExpr.isInvalid())
10443 return ExprError();
10444
10445 if (!getDerived().AlwaysRebuild() &&
10446 SubExpr.get() == E->getSubExpr())
10447 return E;
10448
10449 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
10450 E->isThrownVariableInScope());
10451}
10452
10453template<typename Derived>
10454ExprResult
10455TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10456 ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
10457 getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
10458 if (!Param)
10459 return ExprError();
10460
10461 if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
10462 E->getUsedContext() == SemaRef.CurContext)
10463 return E;
10464
10465 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
10466}
10467
10468template<typename Derived>
10469ExprResult
10470TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
10471 FieldDecl *Field = cast_or_null<FieldDecl>(
10472 getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
10473 if (!Field)
10474 return ExprError();
10475
10476 if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
10477 E->getUsedContext() == SemaRef.CurContext)
10478 return E;
10479
10480 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
10481}
10482
10483template<typename Derived>
10484ExprResult
10485TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
10486 CXXScalarValueInitExpr *E) {
10487 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
10488 if (!T)
10489 return ExprError();
10490
10491 if (!getDerived().AlwaysRebuild() &&
10492 T == E->getTypeSourceInfo())
10493 return E;
10494
10495 return getDerived().RebuildCXXScalarValueInitExpr(T,
10496 /*FIXME:*/T->getTypeLoc().getEndLoc(),
10497 E->getRParenLoc());
10498}
10499
10500template<typename Derived>
10501ExprResult
10502TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
10503 // Transform the type that we're allocating
10504 TypeSourceInfo *AllocTypeInfo =
10505 getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
10506 if (!AllocTypeInfo)
10507 return ExprError();
10508
10509 // Transform the size of the array we're allocating (if any).
10510 Optional<Expr *> ArraySize;
10511 if (Optional<Expr *> OldArraySize = E->getArraySize()) {
10512 ExprResult NewArraySize;
10513 if (*OldArraySize) {
10514 NewArraySize = getDerived().TransformExpr(*OldArraySize);
10515 if (NewArraySize.isInvalid())
10516 return ExprError();
10517 }
10518 ArraySize = NewArraySize.get();
10519 }
10520
10521 // Transform the placement arguments (if any).
10522 bool ArgumentChanged = false;
10523 SmallVector<Expr*, 8> PlacementArgs;
10524 if (getDerived().TransformExprs(E->getPlacementArgs(),
10525 E->getNumPlacementArgs(), true,
10526 PlacementArgs, &ArgumentChanged))
10527 return ExprError();
10528
10529 // Transform the initializer (if any).
10530 Expr *OldInit = E->getInitializer();
10531 ExprResult NewInit;
10532 if (OldInit)
10533 NewInit = getDerived().TransformInitializer(OldInit, true);
10534 if (NewInit.isInvalid())
10535 return ExprError();
10536
10537 // Transform new operator and delete operator.
10538 FunctionDecl *OperatorNew = nullptr;
10539 if (E->getOperatorNew()) {
10540 OperatorNew = cast_or_null<FunctionDecl>(
10541 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
10542 if (!OperatorNew)
10543 return ExprError();
10544 }
10545
10546 FunctionDecl *OperatorDelete = nullptr;
10547 if (E->getOperatorDelete()) {
10548 OperatorDelete = cast_or_null<FunctionDecl>(
10549 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10550 if (!OperatorDelete)
10551 return ExprError();
10552 }
10553
10554 if (!getDerived().AlwaysRebuild() &&
10555 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
10556 ArraySize == E->getArraySize() &&
10557 NewInit.get() == OldInit &&
10558 OperatorNew == E->getOperatorNew() &&
10559 OperatorDelete == E->getOperatorDelete() &&
10560 !ArgumentChanged) {
10561 // Mark any declarations we need as referenced.
10562 // FIXME: instantiation-specific.
10563 if (OperatorNew)
10564 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
10565 if (OperatorDelete)
10566 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10567
10568 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
10569 QualType ElementType
10570 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
10571 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
10572 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
10573 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
10574 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
10575 }
10576 }
10577 }
10578
10579 return E;
10580 }
10581
10582 QualType AllocType = AllocTypeInfo->getType();
10583 if (!ArraySize) {
10584 // If no array size was specified, but the new expression was
10585 // instantiated with an array type (e.g., "new T" where T is
10586 // instantiated with "int[4]"), extract the outer bound from the
10587 // array type as our array size. We do this with constant and
10588 // dependently-sized array types.
10589 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
10590 if (!ArrayT) {
10591 // Do nothing
10592 } else if (const ConstantArrayType *ConsArrayT
10593 = dyn_cast<ConstantArrayType>(ArrayT)) {
10594 ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
10595 SemaRef.Context.getSizeType(),
10596 /*FIXME:*/ E->getBeginLoc());
10597 AllocType = ConsArrayT->getElementType();
10598 } else if (const DependentSizedArrayType *DepArrayT
10599 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
10600 if (DepArrayT->getSizeExpr()) {
10601 ArraySize = DepArrayT->getSizeExpr();
10602 AllocType = DepArrayT->getElementType();
10603 }
10604 }
10605 }
10606
10607 return getDerived().RebuildCXXNewExpr(
10608 E->getBeginLoc(), E->isGlobalNew(),
10609 /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
10610 /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
10611 AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
10612}
10613
10614template<typename Derived>
10615ExprResult
10616TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
10617 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
10618 if (Operand.isInvalid())
10619 return ExprError();
10620
10621 // Transform the delete operator, if known.
10622 FunctionDecl *OperatorDelete = nullptr;
10623 if (E->getOperatorDelete()) {
10624 OperatorDelete = cast_or_null<FunctionDecl>(
10625 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10626 if (!OperatorDelete)
10627 return ExprError();
10628 }
10629
10630 if (!getDerived().AlwaysRebuild() &&
10631 Operand.get() == E->getArgument() &&
10632 OperatorDelete == E->getOperatorDelete()) {
10633 // Mark any declarations we need as referenced.
10634 // FIXME: instantiation-specific.
10635 if (OperatorDelete)
10636 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10637
10638 if (!E->getArgument()->isTypeDependent()) {
10639 QualType Destroyed = SemaRef.Context.getBaseElementType(
10640 E->getDestroyedType());
10641 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10642 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10643 SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
10644 SemaRef.LookupDestructor(Record));
10645 }
10646 }
10647
10648 return E;
10649 }
10650
10651 return getDerived().RebuildCXXDeleteExpr(
10652 E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
10653}
10654
10655template<typename Derived>
10656ExprResult
10657TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
10658 CXXPseudoDestructorExpr *E) {
10659 ExprResult Base = getDerived().TransformExpr(E->getBase());
10660 if (Base.isInvalid())
10661 return ExprError();
10662
10663 ParsedType ObjectTypePtr;
10664 bool MayBePseudoDestructor = false;
10665 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
10666 E->getOperatorLoc(),
10667 E->isArrow()? tok::arrow : tok::period,
10668 ObjectTypePtr,
10669 MayBePseudoDestructor);
10670 if (Base.isInvalid())
10671 return ExprError();
10672
10673 QualType ObjectType = ObjectTypePtr.get();
10674 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
10675 if (QualifierLoc) {
10676 QualifierLoc
10677 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
10678 if (!QualifierLoc)
10679 return ExprError();
10680 }
10681 CXXScopeSpec SS;
10682 SS.Adopt(QualifierLoc);
10683
10684 PseudoDestructorTypeStorage Destroyed;
10685 if (E->getDestroyedTypeInfo()) {
10686 TypeSourceInfo *DestroyedTypeInfo
10687 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
10688 ObjectType, nullptr, SS);
10689 if (!DestroyedTypeInfo)
10690 return ExprError();
10691 Destroyed = DestroyedTypeInfo;
10692 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
10693 // We aren't likely to be able to resolve the identifier down to a type
10694 // now anyway, so just retain the identifier.
10695 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
10696 E->getDestroyedTypeLoc());
10697 } else {
10698 // Look for a destructor known with the given name.
10699 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
10700 *E->getDestroyedTypeIdentifier(),
10701 E->getDestroyedTypeLoc(),
10702 /*Scope=*/nullptr,
10703 SS, ObjectTypePtr,
10704 false);
10705 if (!T)
10706 return ExprError();
10707
10708 Destroyed
10709 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
10710 E->getDestroyedTypeLoc());
10711 }
10712
10713 TypeSourceInfo *ScopeTypeInfo = nullptr;
10714 if (E->getScopeTypeInfo()) {
10715 CXXScopeSpec EmptySS;
10716 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
10717 E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
10718 if (!ScopeTypeInfo)
10719 return ExprError();
10720 }
10721
10722 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
10723 E->getOperatorLoc(),
10724 E->isArrow(),
10725 SS,
10726 ScopeTypeInfo,
10727 E->getColonColonLoc(),
10728 E->getTildeLoc(),
10729 Destroyed);
10730}
10731
10732template <typename Derived>
10733bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
10734 bool RequiresADL,
10735 LookupResult &R) {
10736 // Transform all the decls.
10737 bool AllEmptyPacks = true;
10738 for (auto *OldD : Old->decls()) {
10739 Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
10740 if (!InstD) {
10741 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
10742 // This can happen because of dependent hiding.
10743 if (isa<UsingShadowDecl>(OldD))
10744 continue;
10745 else {
10746 R.clear();
10747 return true;
10748 }
10749 }
10750
10751 // Expand using pack declarations.
10752 NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
10753 ArrayRef<NamedDecl*> Decls = SingleDecl;
10754 if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
10755 Decls = UPD->expansions();
10756
10757 // Expand using declarations.
10758 for (auto *D : Decls) {
10759 if (auto *UD = dyn_cast<UsingDecl>(D)) {
10760 for (auto *SD : UD->shadows())
10761 R.addDecl(SD);
10762 } else {
10763 R.addDecl(D);
10764 }
10765 }
10766
10767 AllEmptyPacks &= Decls.empty();
10768 };
10769
10770 // C++ [temp.res]/8.4.2:
10771 // The program is ill-formed, no diagnostic required, if [...] lookup for
10772 // a name in the template definition found a using-declaration, but the
10773 // lookup in the corresponding scope in the instantiation odoes not find
10774 // any declarations because the using-declaration was a pack expansion and
10775 // the corresponding pack is empty
10776 if (AllEmptyPacks && !RequiresADL) {
10777 getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
10778 << isa<UnresolvedMemberExpr>(Old) << Old->getName();
10779 return true;
10780 }
10781
10782 // Resolve a kind, but don't do any further analysis. If it's
10783 // ambiguous, the callee needs to deal with it.
10784 R.resolveKind();
10785 return false;
10786}
10787
10788template<typename Derived>
10789ExprResult
10790TreeTransform<Derived>::TransformUnresolvedLookupExpr(
10791 UnresolvedLookupExpr *Old) {
10792 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
10793 Sema::LookupOrdinaryName);
10794
10795 // Transform the declaration set.
10796 if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
10797 return ExprError();
10798
10799 // Rebuild the nested-name qualifier, if present.
10800 CXXScopeSpec SS;
10801 if (Old->getQualifierLoc()) {
10802 NestedNameSpecifierLoc QualifierLoc
10803 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
10804 if (!QualifierLoc)
10805 return ExprError();
10806
10807 SS.Adopt(QualifierLoc);
10808 }
10809
10810 if (Old->getNamingClass()) {
10811 CXXRecordDecl *NamingClass
10812 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
10813 Old->getNameLoc(),
10814 Old->getNamingClass()));
10815 if (!NamingClass) {
10816 R.clear();
10817 return ExprError();
10818 }
10819
10820 R.setNamingClass(NamingClass);
10821 }
10822
10823 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
10824
10825 // If we have neither explicit template arguments, nor the template keyword,
10826 // it's a normal declaration name or member reference.
10827 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
10828 NamedDecl *D = R.getAsSingle<NamedDecl>();
10829 // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
10830 // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
10831 // give a good diagnostic.
10832 if (D && D->isCXXInstanceMember()) {
10833 return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10834 /*TemplateArgs=*/nullptr,
10835 /*Scope=*/nullptr);
10836 }
10837
10838 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
10839 }
10840
10841 // If we have template arguments, rebuild them, then rebuild the
10842 // templateid expression.
10843 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
10844 if (Old->hasExplicitTemplateArgs() &&
10845 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
10846 Old->getNumTemplateArgs(),
10847 TransArgs)) {
10848 R.clear();
10849 return ExprError();
10850 }
10851
10852 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
10853 Old->requiresADL(), &TransArgs);
10854}
10855
10856template<typename Derived>
10857ExprResult
10858TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
10859 bool ArgChanged = false;
10860 SmallVector<TypeSourceInfo *, 4> Args;
10861 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
10862 TypeSourceInfo *From = E->getArg(I);
10863 TypeLoc FromTL = From->getTypeLoc();
10864 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
10865 TypeLocBuilder TLB;
10866 TLB.reserve(FromTL.getFullDataSize());
10867 QualType To = getDerived().TransformType(TLB, FromTL);
10868 if (To.isNull())
10869 return ExprError();
10870
10871 if (To == From->getType())
10872 Args.push_back(From);
10873 else {
10874 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10875 ArgChanged = true;
10876 }
10877 continue;
10878 }
10879
10880 ArgChanged = true;
10881
10882 // We have a pack expansion. Instantiate it.
10883 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
10884 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
10885 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
10886 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
10887
10888 // Determine whether the set of unexpanded parameter packs can and should
10889 // be expanded.
10890 bool Expand = true;
10891 bool RetainExpansion = false;
10892 Optional<unsigned> OrigNumExpansions =
10893 ExpansionTL.getTypePtr()->getNumExpansions();
10894 Optional<unsigned> NumExpansions = OrigNumExpansions;
10895 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
10896 PatternTL.getSourceRange(),
10897 Unexpanded,
10898 Expand, RetainExpansion,
10899 NumExpansions))
10900 return ExprError();
10901
10902 if (!Expand) {
10903 // The transform has determined that we should perform a simple
10904 // transformation on the pack expansion, producing another pack
10905 // expansion.
10906 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
10907
10908 TypeLocBuilder TLB;
10909 TLB.reserve(From->getTypeLoc().getFullDataSize());
10910
10911 QualType To = getDerived().TransformType(TLB, PatternTL);
10912 if (To.isNull())
10913 return ExprError();
10914
10915 To = getDerived().RebuildPackExpansionType(To,
10916 PatternTL.getSourceRange(),
10917 ExpansionTL.getEllipsisLoc(),
10918 NumExpansions);
10919 if (To.isNull())
10920 return ExprError();
10921
10922 PackExpansionTypeLoc ToExpansionTL
10923 = TLB.push<PackExpansionTypeLoc>(To);
10924 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10925 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10926 continue;
10927 }
10928
10929 // Expand the pack expansion by substituting for each argument in the
10930 // pack(s).
10931 for (unsigned I = 0; I != *NumExpansions; ++I) {
10932 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
10933 TypeLocBuilder TLB;
10934 TLB.reserve(PatternTL.getFullDataSize());
10935 QualType To = getDerived().TransformType(TLB, PatternTL);
10936 if (To.isNull())
10937 return ExprError();
10938
10939 if (To->containsUnexpandedParameterPack()) {
10940 To = getDerived().RebuildPackExpansionType(To,
10941 PatternTL.getSourceRange(),
10942 ExpansionTL.getEllipsisLoc(),
10943 NumExpansions);
10944 if (To.isNull())
10945 return ExprError();
10946
10947 PackExpansionTypeLoc ToExpansionTL
10948 = TLB.push<PackExpansionTypeLoc>(To);
10949 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10950 }
10951
10952 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10953 }
10954
10955 if (!RetainExpansion)
10956 continue;
10957
10958 // If we're supposed to retain a pack expansion, do so by temporarily
10959 // forgetting the partially-substituted parameter pack.
10960 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
10961
10962 TypeLocBuilder TLB;
10963 TLB.reserve(From->getTypeLoc().getFullDataSize());
10964
10965 QualType To = getDerived().TransformType(TLB, PatternTL);
10966 if (To.isNull())
10967 return ExprError();
10968
10969 To = getDerived().RebuildPackExpansionType(To,
10970 PatternTL.getSourceRange(),
10971 ExpansionTL.getEllipsisLoc(),
10972 NumExpansions);
10973 if (To.isNull())
10974 return ExprError();
10975
10976 PackExpansionTypeLoc ToExpansionTL
10977 = TLB.push<PackExpansionTypeLoc>(To);
10978 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10979 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10980 }
10981
10982 if (!getDerived().AlwaysRebuild() && !ArgChanged)
10983 return E;
10984
10985 return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
10986 E->getEndLoc());
10987}
10988
10989template<typename Derived>
10990ExprResult
10991TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
10992 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
10993 if (!T)
10994 return ExprError();
10995
10996 if (!getDerived().AlwaysRebuild() &&
10997 T == E->getQueriedTypeSourceInfo())
10998 return E;
10999
11000 ExprResult SubExpr;
11001 {
11002 EnterExpressionEvaluationContext Unevaluated(
11003 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11004 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
11005 if (SubExpr.isInvalid())
11006 return ExprError();
11007
11008 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
11009 return E;
11010 }
11011
11012 return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
11013 SubExpr.get(), E->getEndLoc());
11014}
11015
11016template<typename Derived>
11017ExprResult
11018TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
11019 ExprResult SubExpr;
11020 {
11021 EnterExpressionEvaluationContext Unevaluated(
11022 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11023 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
11024 if (SubExpr.isInvalid())
11025 return ExprError();
11026
11027 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
11028 return E;
11029 }
11030
11031 return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
11032 SubExpr.get(), E->getEndLoc());
11033}
11034
11035template <typename Derived>
11036ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
11037 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
11038 TypeSourceInfo **RecoveryTSI) {
11039 ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
11040 DRE, AddrTaken, RecoveryTSI);
11041
11042 // Propagate both errors and recovered types, which return ExprEmpty.
11043 if (!NewDRE.isUsable())
11044 return NewDRE;
11045
11046 // We got an expr, wrap it up in parens.
11047 if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
11048 return PE;
11049 return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
11050 PE->getRParen());
11051}
11052
11053template <typename Derived>
11054ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11055 DependentScopeDeclRefExpr *E) {
11056 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
11057 nullptr);
11058}
11059
11060template<typename Derived>
11061ExprResult
11062TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11063 DependentScopeDeclRefExpr *E,
11064 bool IsAddressOfOperand,
11065 TypeSourceInfo **RecoveryTSI) {
11066 assert(E->getQualifierLoc())((E->getQualifierLoc()) ? static_cast<void> (0) : __assert_fail
("E->getQualifierLoc()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 11066, __PRETTY_FUNCTION__))
;
11067 NestedNameSpecifierLoc QualifierLoc
11068 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11069 if (!QualifierLoc)
11070 return ExprError();
11071 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11072
11073 // TODO: If this is a conversion-function-id, verify that the
11074 // destination type name (if present) resolves the same way after
11075 // instantiation as it did in the local scope.
11076
11077 DeclarationNameInfo NameInfo
11078 = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
11079 if (!NameInfo.getName())
11080 return ExprError();
11081
11082 if (!E->hasExplicitTemplateArgs()) {
11083 if (!getDerived().AlwaysRebuild() &&
11084 QualifierLoc == E->getQualifierLoc() &&
11085 // Note: it is sufficient to compare the Name component of NameInfo:
11086 // if name has not changed, DNLoc has not changed either.
11087 NameInfo.getName() == E->getDeclName())
11088 return E;
11089
11090 return getDerived().RebuildDependentScopeDeclRefExpr(
11091 QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
11092 IsAddressOfOperand, RecoveryTSI);
11093 }
11094
11095 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11096 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11097 E->getNumTemplateArgs(),
11098 TransArgs))
11099 return ExprError();
11100
11101 return getDerived().RebuildDependentScopeDeclRefExpr(
11102 QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
11103 RecoveryTSI);
11104}
11105
11106template<typename Derived>
11107ExprResult
11108TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
11109 // CXXConstructExprs other than for list-initialization and
11110 // CXXTemporaryObjectExpr are always implicit, so when we have
11111 // a 1-argument construction we just transform that argument.
11112 if ((E->getNumArgs() == 1 ||
11113 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
11114 (!getDerived().DropCallArgument(E->getArg(0))) &&
11115 !E->isListInitialization())
11116 return getDerived().TransformExpr(E->getArg(0));
11117
11118 TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
11119
11120 QualType T = getDerived().TransformType(E->getType());
11121 if (T.isNull())
11122 return ExprError();
11123
11124 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11125 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11126 if (!Constructor)
11127 return ExprError();
11128
11129 bool ArgumentChanged = false;
11130 SmallVector<Expr*, 8> Args;
11131 {
11132 EnterExpressionEvaluationContext Context(
11133 getSema(), EnterExpressionEvaluationContext::InitList,
11134 E->isListInitialization());
11135 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11136 &ArgumentChanged))
11137 return ExprError();
11138 }
11139
11140 if (!getDerived().AlwaysRebuild() &&
11141 T == E->getType() &&
11142 Constructor == E->getConstructor() &&
11143 !ArgumentChanged) {
11144 // Mark the constructor as referenced.
11145 // FIXME: Instantiation-specific
11146 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11147 return E;
11148 }
11149
11150 return getDerived().RebuildCXXConstructExpr(
11151 T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
11152 E->hadMultipleCandidates(), E->isListInitialization(),
11153 E->isStdInitListInitialization(), E->requiresZeroInitialization(),
11154 E->getConstructionKind(), E->getParenOrBraceRange());
11155}
11156
11157template<typename Derived>
11158ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
11159 CXXInheritedCtorInitExpr *E) {
11160 QualType T = getDerived().TransformType(E->getType());
11161 if (T.isNull())
11162 return ExprError();
11163
11164 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11165 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11166 if (!Constructor)
11167 return ExprError();
11168
11169 if (!getDerived().AlwaysRebuild() &&
11170 T == E->getType() &&
11171 Constructor == E->getConstructor()) {
11172 // Mark the constructor as referenced.
11173 // FIXME: Instantiation-specific
11174 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11175 return E;
11176 }
11177
11178 return getDerived().RebuildCXXInheritedCtorInitExpr(
11179 T, E->getLocation(), Constructor,
11180 E->constructsVBase(), E->inheritedFromVBase());
11181}
11182
11183/// Transform a C++ temporary-binding expression.
11184///
11185/// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
11186/// transform the subexpression and return that.
11187template<typename Derived>
11188ExprResult
11189TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11190 return getDerived().TransformExpr(E->getSubExpr());
11191}
11192
11193/// Transform a C++ expression that contains cleanups that should
11194/// be run after the expression is evaluated.
11195///
11196/// Since ExprWithCleanups nodes are implicitly generated, we
11197/// just transform the subexpression and return that.
11198template<typename Derived>
11199ExprResult
11200TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
11201 return getDerived().TransformExpr(E->getSubExpr());
11202}
11203
11204template<typename Derived>
11205ExprResult
11206TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
11207 CXXTemporaryObjectExpr *E) {
11208 TypeSourceInfo *T =
11209 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11210 if (!T)
11211 return ExprError();
11212
11213 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11214 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11215 if (!Constructor)
11216 return ExprError();
11217
11218 bool ArgumentChanged = false;
11219 SmallVector<Expr*, 8> Args;
11220 Args.reserve(E->getNumArgs());
11221 {
11222 EnterExpressionEvaluationContext Context(
11223 getSema(), EnterExpressionEvaluationContext::InitList,
11224 E->isListInitialization());
11225 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11226 &ArgumentChanged))
11227 return ExprError();
11228 }
11229
11230 if (!getDerived().AlwaysRebuild() &&
11231 T == E->getTypeSourceInfo() &&
11232 Constructor == E->getConstructor() &&
11233 !ArgumentChanged) {
11234 // FIXME: Instantiation-specific
11235 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11236 return SemaRef.MaybeBindToTemporary(E);
11237 }
11238
11239 // FIXME: We should just pass E->isListInitialization(), but we're not
11240 // prepared to handle list-initialization without a child InitListExpr.
11241 SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
11242 return getDerived().RebuildCXXTemporaryObjectExpr(
11243 T, LParenLoc, Args, E->getEndLoc(),
11244 /*ListInitialization=*/LParenLoc.isInvalid());
11245}
11246
11247template<typename Derived>
11248ExprResult
11249TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
11250 // Transform any init-capture expressions before entering the scope of the
11251 // lambda body, because they are not semantically within that scope.
11252 typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
11253 struct TransformedInitCapture {
11254 // The location of the ... if the result is retaining a pack expansion.
11255 SourceLocation EllipsisLoc;
11256 // Zero or more expansions of the init-capture.
11257 SmallVector<InitCaptureInfoTy, 4> Expansions;
11258 };
11259 SmallVector<TransformedInitCapture, 4> InitCaptures;
11260 InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
11261 for (LambdaExpr::capture_iterator C = E->capture_begin(),
11262 CEnd = E->capture_end();
11263 C != CEnd; ++C) {
11264 if (!E->isInitCapture(C))
11265 continue;
11266
11267 TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
11268 VarDecl *OldVD = C->getCapturedVar();
11269
11270 auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
11271 Optional<unsigned> NumExpansions) {
11272 ExprResult NewExprInitResult = getDerived().TransformInitializer(
11273 OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
11274
11275 if (NewExprInitResult.isInvalid()) {
11276 Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
11277 return;
11278 }
11279 Expr *NewExprInit = NewExprInitResult.get();
11280
11281 QualType NewInitCaptureType =
11282 getSema().buildLambdaInitCaptureInitialization(
11283 C->getLocation(), OldVD->getType()->isReferenceType(),
11284 EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
11285 C->getCapturedVar()->getInitStyle() != VarDecl::CInit,
11286 NewExprInit);
11287 Result.Expansions.push_back(
11288 InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
11289 };
11290
11291 // If this is an init-capture pack, consider expanding the pack now.
11292 if (OldVD->isParameterPack()) {
11293 PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
11294 ->getTypeLoc()
11295 .castAs<PackExpansionTypeLoc>();
11296 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11297 SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
11298
11299 // Determine whether the set of unexpanded parameter packs can and should
11300 // be expanded.
11301 bool Expand = true;
11302 bool RetainExpansion = false;
11303 Optional<unsigned> OrigNumExpansions =
11304 ExpansionTL.getTypePtr()->getNumExpansions();
11305 Optional<unsigned> NumExpansions = OrigNumExpansions;
11306 if (getDerived().TryExpandParameterPacks(
11307 ExpansionTL.getEllipsisLoc(),
11308 OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
11309 RetainExpansion, NumExpansions))
11310 return ExprError();
11311 if (Expand) {
11312 for (unsigned I = 0; I != *NumExpansions; ++I) {
11313 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11314 SubstInitCapture(SourceLocation(), None);
11315 }
11316 }
11317 if (!Expand || RetainExpansion) {
11318 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11319 SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
11320 Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
11321 }
11322 } else {
11323 SubstInitCapture(SourceLocation(), None);
11324 }
11325 }
11326
11327 LambdaScopeInfo *LSI = getSema().PushLambdaScope();
11328 Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
11329
11330 // Transform the template parameters, and add them to the current
11331 // instantiation scope. The null case is handled correctly.
11332 auto TPL = getDerived().TransformTemplateParameterList(
11333 E->getTemplateParameterList());
11334 LSI->GLTemplateParameterList = TPL;
11335
11336 // Transform the type of the original lambda's call operator.
11337 // The transformation MUST be done in the CurrentInstantiationScope since
11338 // it introduces a mapping of the original to the newly created
11339 // transformed parameters.
11340 TypeSourceInfo *NewCallOpTSI = nullptr;
11341 {
11342 TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
11343 FunctionProtoTypeLoc OldCallOpFPTL =
11344 OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
11345
11346 TypeLocBuilder NewCallOpTLBuilder;
11347 SmallVector<QualType, 4> ExceptionStorage;
11348 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
11349 QualType NewCallOpType = TransformFunctionProtoType(
11350 NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
11351 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
11352 return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
11353 ExceptionStorage, Changed);
11354 });
11355 if (NewCallOpType.isNull())
11356 return ExprError();
11357 NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
11358 NewCallOpType);
11359 }
11360
11361 // Create the local class that will describe the lambda.
11362 CXXRecordDecl *OldClass = E->getLambdaClass();
11363 CXXRecordDecl *Class
11364 = getSema().createLambdaClosureType(E->getIntroducerRange(),
11365 NewCallOpTSI,
11366 /*KnownDependent=*/false,
11367 E->getCaptureDefault());
11368 getDerived().transformedLocalDecl(OldClass, {Class});
11369
11370 Optional<std::pair<unsigned, Decl*>> Mangling;
11371 if (getDerived().ReplacingOriginal())
11372 Mangling = std::make_pair(OldClass->getLambdaManglingNumber(),
11373 OldClass->getLambdaContextDecl());
11374
11375 // Build the call operator.
11376 CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
11377 Class, E->getIntroducerRange(), NewCallOpTSI,
11378 E->getCallOperator()->getEndLoc(),
11379 NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
11380 E->getCallOperator()->getConstexprKind(), Mangling);
11381
11382 LSI->CallOperator = NewCallOperator;
11383
11384 for (unsigned I = 0, NumParams = NewCallOperator->getNumParams();
11385 I != NumParams; ++I) {
11386 auto *P = NewCallOperator->getParamDecl(I);
11387 if (P->hasUninstantiatedDefaultArg()) {
11388 EnterExpressionEvaluationContext Eval(
11389 getSema(),
11390 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, P);
11391 ExprResult R = getDerived().TransformExpr(
11392 E->getCallOperator()->getParamDecl(I)->getDefaultArg());
11393 P->setDefaultArg(R.get());
11394 }
11395 }
11396
11397 getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
11398 getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
11399
11400 // Introduce the context of the call operator.
11401 Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
11402 /*NewThisContext*/false);
11403
11404 // Enter the scope of the lambda.
11405 getSema().buildLambdaScope(LSI, NewCallOperator,
11406 E->getIntroducerRange(),
11407 E->getCaptureDefault(),
11408 E->getCaptureDefaultLoc(),
11409 E->hasExplicitParameters(),
11410 E->hasExplicitResultType(),
11411 E->isMutable());
11412
11413 bool Invalid = false;
11414
11415 // Transform captures.
11416 for (LambdaExpr::capture_iterator C = E->capture_begin(),
11417 CEnd = E->capture_end();
11418 C != CEnd; ++C) {
11419 // When we hit the first implicit capture, tell Sema that we've finished
11420 // the list of explicit captures.
11421 if (C->isImplicit())
11422 break;
11423
11424 // Capturing 'this' is trivial.
11425 if (C->capturesThis()) {
11426 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11427 /*BuildAndDiagnose*/ true, nullptr,
11428 C->getCaptureKind() == LCK_StarThis);
11429 continue;
11430 }
11431 // Captured expression will be recaptured during captured variables
11432 // rebuilding.
11433 if (C->capturesVLAType())
11434 continue;
11435
11436 // Rebuild init-captures, including the implied field declaration.
11437 if (E->isInitCapture(C)) {
11438 TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
11439
11440 VarDecl *OldVD = C->getCapturedVar();
11441 llvm::SmallVector<Decl*, 4> NewVDs;
11442
11443 for (InitCaptureInfoTy &Info : NewC.Expansions) {
11444 ExprResult Init = Info.first;
11445 QualType InitQualType = Info.second;
11446 if (Init.isInvalid() || InitQualType.isNull()) {
11447 Invalid = true;
11448 break;
11449 }
11450 VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
11451 OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
11452 OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get());
11453 if (!NewVD) {
11454 Invalid = true;
11455 break;
11456 }
11457 NewVDs.push_back(NewVD);
11458 getSema().addInitCapture(LSI, NewVD);
11459 }
11460
11461 if (Invalid)
11462 break;
11463
11464 getDerived().transformedLocalDecl(OldVD, NewVDs);
11465 continue;
11466 }
11467
11468 assert(C->capturesVariable() && "unexpected kind of lambda capture")((C->capturesVariable() && "unexpected kind of lambda capture"
) ? static_cast<void> (0) : __assert_fail ("C->capturesVariable() && \"unexpected kind of lambda capture\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 11468, __PRETTY_FUNCTION__))
;
11469
11470 // Determine the capture kind for Sema.
11471 Sema::TryCaptureKind Kind
11472 = C->isImplicit()? Sema::TryCapture_Implicit
11473 : C->getCaptureKind() == LCK_ByCopy
11474 ? Sema::TryCapture_ExplicitByVal
11475 : Sema::TryCapture_ExplicitByRef;
11476 SourceLocation EllipsisLoc;
11477 if (C->isPackExpansion()) {
11478 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
11479 bool ShouldExpand = false;
11480 bool RetainExpansion = false;
11481 Optional<unsigned> NumExpansions;
11482 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
11483 C->getLocation(),
11484 Unexpanded,
11485 ShouldExpand, RetainExpansion,
11486 NumExpansions)) {
11487 Invalid = true;
11488 continue;
11489 }
11490
11491 if (ShouldExpand) {
11492 // The transform has determined that we should perform an expansion;
11493 // transform and capture each of the arguments.
11494 // expansion of the pattern. Do so.
11495 VarDecl *Pack = C->getCapturedVar();
11496 for (unsigned I = 0; I != *NumExpansions; ++I) {
11497 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11498 VarDecl *CapturedVar
11499 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11500 Pack));
11501 if (!CapturedVar) {
11502 Invalid = true;
11503 continue;
11504 }
11505
11506 // Capture the transformed variable.
11507 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
11508 }
11509
11510 // FIXME: Retain a pack expansion if RetainExpansion is true.
11511
11512 continue;
11513 }
11514
11515 EllipsisLoc = C->getEllipsisLoc();
11516 }
11517
11518 // Transform the captured variable.
11519 VarDecl *CapturedVar
11520 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11521 C->getCapturedVar()));
11522 if (!CapturedVar || CapturedVar->isInvalidDecl()) {
11523 Invalid = true;
11524 continue;
11525 }
11526
11527 // Capture the transformed variable.
11528 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
11529 EllipsisLoc);
11530 }
11531 getSema().finishLambdaExplicitCaptures(LSI);
11532
11533 // FIXME: Sema's lambda-building mechanism expects us to push an expression
11534 // evaluation context even if we're not transforming the function body.
11535 getSema().PushExpressionEvaluationContext(
11536 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
11537
11538 // Instantiate the body of the lambda expression.
11539 StmtResult Body =
11540 Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
11541
11542 // ActOnLambda* will pop the function scope for us.
11543 FuncScopeCleanup.disable();
11544
11545 if (Body.isInvalid()) {
11546 SavedContext.pop();
11547 getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
11548 /*IsInstantiation=*/true);
11549 return ExprError();
11550 }
11551
11552 // Copy the LSI before ActOnFinishFunctionBody removes it.
11553 // FIXME: This is dumb. Store the lambda information somewhere that outlives
11554 // the call operator.
11555 auto LSICopy = *LSI;
11556 getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
11557 /*IsInstantiation*/ true);
11558 SavedContext.pop();
11559
11560 return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
11561 &LSICopy);
11562}
11563
11564template<typename Derived>
11565StmtResult
11566TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
11567 return TransformStmt(S);
11568}
11569
11570template<typename Derived>
11571StmtResult
11572TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
11573 // Transform captures.
11574 for (LambdaExpr::capture_iterator C = E->capture_begin(),
11575 CEnd = E->capture_end();
11576 C != CEnd; ++C) {
11577 // When we hit the first implicit capture, tell Sema that we've finished
11578 // the list of explicit captures.
11579 if (!C->isImplicit())
11580 continue;
11581
11582 // Capturing 'this' is trivial.
11583 if (C->capturesThis()) {
11584 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11585 /*BuildAndDiagnose*/ true, nullptr,
11586 C->getCaptureKind() == LCK_StarThis);
11587 continue;
11588 }
11589 // Captured expression will be recaptured during captured variables
11590 // rebuilding.
11591 if (C->capturesVLAType())
11592 continue;
11593
11594 assert(C->capturesVariable() && "unexpected kind of lambda capture")((C->capturesVariable() && "unexpected kind of lambda capture"
) ? static_cast<void> (0) : __assert_fail ("C->capturesVariable() && \"unexpected kind of lambda capture\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 11594, __PRETTY_FUNCTION__))
;
11595 assert(!E->isInitCapture(C) && "implicit init-capture?")((!E->isInitCapture(C) && "implicit init-capture?"
) ? static_cast<void> (0) : __assert_fail ("!E->isInitCapture(C) && \"implicit init-capture?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 11595, __PRETTY_FUNCTION__))
;
11596
11597 // Transform the captured variable.
11598 VarDecl *CapturedVar = cast_or_null<VarDecl>(
11599 getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
11600 if (!CapturedVar || CapturedVar->isInvalidDecl())
11601 return StmtError();
11602
11603 // Capture the transformed variable.
11604 getSema().tryCaptureVariable(CapturedVar, C->getLocation());
11605 }
11606
11607 return S;
11608}
11609
11610template<typename Derived>
11611ExprResult
11612TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
11613 CXXUnresolvedConstructExpr *E) {
11614 TypeSourceInfo *T =
11615 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11616 if (!T)
11617 return ExprError();
11618
11619 bool ArgumentChanged = false;
11620 SmallVector<Expr*, 8> Args;
11621 Args.reserve(E->arg_size());
11622 {
11623 EnterExpressionEvaluationContext Context(
11624 getSema(), EnterExpressionEvaluationContext::InitList,
11625 E->isListInitialization());
11626 if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
11627 &ArgumentChanged))
11628 return ExprError();
11629 }
11630
11631 if (!getDerived().AlwaysRebuild() &&
11632 T == E->getTypeSourceInfo() &&
11633 !ArgumentChanged)
11634 return E;
11635
11636 // FIXME: we're faking the locations of the commas
11637 return getDerived().RebuildCXXUnresolvedConstructExpr(
11638 T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
11639}
11640
11641template<typename Derived>
11642ExprResult
11643TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
11644 CXXDependentScopeMemberExpr *E) {
11645 // Transform the base of the expression.
11646 ExprResult Base((Expr*) nullptr);
11647 Expr *OldBase;
11648 QualType BaseType;
11649 QualType ObjectType;
11650 if (!E->isImplicitAccess()) {
11651 OldBase = E->getBase();
11652 Base = getDerived().TransformExpr(OldBase);
11653 if (Base.isInvalid())
11654 return ExprError();
11655
11656 // Start the member reference and compute the object's type.
11657 ParsedType ObjectTy;
11658 bool MayBePseudoDestructor = false;
11659 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
11660 E->getOperatorLoc(),
11661 E->isArrow()? tok::arrow : tok::period,
11662 ObjectTy,
11663 MayBePseudoDestructor);
11664 if (Base.isInvalid())
11665 return ExprError();
11666
11667 ObjectType = ObjectTy.get();
11668 BaseType = ((Expr*) Base.get())->getType();
11669 } else {
11670 OldBase = nullptr;
11671 BaseType = getDerived().TransformType(E->getBaseType());
11672 ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
11673 }
11674
11675 // Transform the first part of the nested-name-specifier that qualifies
11676 // the member name.
11677 NamedDecl *FirstQualifierInScope
11678 = getDerived().TransformFirstQualifierInScope(
11679 E->getFirstQualifierFoundInScope(),
11680 E->getQualifierLoc().getBeginLoc());
11681
11682 NestedNameSpecifierLoc QualifierLoc;
11683 if (E->getQualifier()) {
11684 QualifierLoc
11685 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
11686 ObjectType,
11687 FirstQualifierInScope);
11688 if (!QualifierLoc)
11689 return ExprError();
11690 }
11691
11692 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11693
11694 // TODO: If this is a conversion-function-id, verify that the
11695 // destination type name (if present) resolves the same way after
11696 // instantiation as it did in the local scope.
11697
11698 DeclarationNameInfo NameInfo
11699 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
11700 if (!NameInfo.getName())
11701 return ExprError();
11702
11703 if (!E->hasExplicitTemplateArgs()) {
11704 // This is a reference to a member without an explicitly-specified
11705 // template argument list. Optimize for this common case.
11706 if (!getDerived().AlwaysRebuild() &&
11707 Base.get() == OldBase &&
11708 BaseType == E->getBaseType() &&
11709 QualifierLoc == E->getQualifierLoc() &&
11710 NameInfo.getName() == E->getMember() &&
11711 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
11712 return E;
11713
11714 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11715 BaseType,
11716 E->isArrow(),
11717 E->getOperatorLoc(),
11718 QualifierLoc,
11719 TemplateKWLoc,
11720 FirstQualifierInScope,
11721 NameInfo,
11722 /*TemplateArgs*/nullptr);
11723 }
11724
11725 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11726 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11727 E->getNumTemplateArgs(),
11728 TransArgs))
11729 return ExprError();
11730
11731 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11732 BaseType,
11733 E->isArrow(),
11734 E->getOperatorLoc(),
11735 QualifierLoc,
11736 TemplateKWLoc,
11737 FirstQualifierInScope,
11738 NameInfo,
11739 &TransArgs);
11740}
11741
11742template<typename Derived>
11743ExprResult
11744TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
11745 // Transform the base of the expression.
11746 ExprResult Base((Expr*) nullptr);
11747 QualType BaseType;
11748 if (!Old->isImplicitAccess()) {
11749 Base = getDerived().TransformExpr(Old->getBase());
11750 if (Base.isInvalid())
11751 return ExprError();
11752 Base = getSema().PerformMemberExprBaseConversion(Base.get(),
11753 Old->isArrow());
11754 if (Base.isInvalid())
11755 return ExprError();
11756 BaseType = Base.get()->getType();
11757 } else {
11758 BaseType = getDerived().TransformType(Old->getBaseType());
11759 }
11760
11761 NestedNameSpecifierLoc QualifierLoc;
11762 if (Old->getQualifierLoc()) {
11763 QualifierLoc
11764 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
11765 if (!QualifierLoc)
11766 return ExprError();
11767 }
11768
11769 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
11770
11771 LookupResult R(SemaRef, Old->getMemberNameInfo(),
11772 Sema::LookupOrdinaryName);
11773
11774 // Transform the declaration set.
11775 if (TransformOverloadExprDecls(Old, /*RequiresADL*/false, R))
11776 return ExprError();
11777
11778 // Determine the naming class.
11779 if (Old->getNamingClass()) {
11780 CXXRecordDecl *NamingClass
11781 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
11782 Old->getMemberLoc(),
11783 Old->getNamingClass()));
11784 if (!NamingClass)
11785 return ExprError();
11786
11787 R.setNamingClass(NamingClass);
11788 }
11789
11790 TemplateArgumentListInfo TransArgs;
11791 if (Old->hasExplicitTemplateArgs()) {
11792 TransArgs.setLAngleLoc(Old->getLAngleLoc());
11793 TransArgs.setRAngleLoc(Old->getRAngleLoc());
11794 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11795 Old->getNumTemplateArgs(),
11796 TransArgs))
11797 return ExprError();
11798 }
11799
11800 // FIXME: to do this check properly, we will need to preserve the
11801 // first-qualifier-in-scope here, just in case we had a dependent
11802 // base (and therefore couldn't do the check) and a
11803 // nested-name-qualifier (and therefore could do the lookup).
11804 NamedDecl *FirstQualifierInScope = nullptr;
11805
11806 return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
11807 BaseType,
11808 Old->getOperatorLoc(),
11809 Old->isArrow(),
11810 QualifierLoc,
11811 TemplateKWLoc,
11812 FirstQualifierInScope,
11813 R,
11814 (Old->hasExplicitTemplateArgs()
11815 ? &TransArgs : nullptr));
11816}
11817
11818template<typename Derived>
11819ExprResult
11820TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
11821 EnterExpressionEvaluationContext Unevaluated(
11822 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11823 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
11824 if (SubExpr.isInvalid())
11825 return ExprError();
11826
11827 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
11828 return E;
11829
11830 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
11831}
11832
11833template<typename Derived>
11834ExprResult
11835TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
11836 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
11837 if (Pattern.isInvalid())
11838 return ExprError();
11839
11840 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
11841 return E;
11842
11843 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
11844 E->getNumExpansions());
11845}
11846
11847template<typename Derived>
11848ExprResult
11849TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
11850 // If E is not value-dependent, then nothing will change when we transform it.
11851 // Note: This is an instantiation-centric view.
11852 if (!E->isValueDependent())
11853 return E;
11854
11855 EnterExpressionEvaluationContext Unevaluated(
11856 getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
11857
11858 ArrayRef<TemplateArgument> PackArgs;
11859 TemplateArgument ArgStorage;
11860
11861 // Find the argument list to transform.
11862 if (E->isPartiallySubstituted()) {
11863 PackArgs = E->getPartialArguments();
11864 } else if (E->isValueDependent()) {
11865 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
11866 bool ShouldExpand = false;
11867 bool RetainExpansion = false;
11868 Optional<unsigned> NumExpansions;
11869 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
11870 Unexpanded,
11871 ShouldExpand, RetainExpansion,
11872 NumExpansions))
11873 return ExprError();
11874
11875 // If we need to expand the pack, build a template argument from it and
11876 // expand that.
11877 if (ShouldExpand) {
11878 auto *Pack = E->getPack();
11879 if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
11880 ArgStorage = getSema().Context.getPackExpansionType(
11881 getSema().Context.getTypeDeclType(TTPD), None);
11882 } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
11883 ArgStorage = TemplateArgument(TemplateName(TTPD), None);
11884 } else {
11885 auto *VD = cast<ValueDecl>(Pack);
11886 ExprResult DRE = getSema().BuildDeclRefExpr(
11887 VD, VD->getType().getNonLValueExprType(getSema().Context),
11888 VD->getType()->isReferenceType() ? VK_LValue : VK_RValue,
11889 E->getPackLoc());
11890 if (DRE.isInvalid())
11891 return ExprError();
11892 ArgStorage = new (getSema().Context) PackExpansionExpr(
11893 getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
11894 }
11895 PackArgs = ArgStorage;
11896 }
11897 }
11898
11899 // If we're not expanding the pack, just transform the decl.
11900 if (!PackArgs.size()) {
11901 auto *Pack = cast_or_null<NamedDecl>(
11902 getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
11903 if (!Pack)
11904 return ExprError();
11905 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
11906 E->getPackLoc(),
11907 E->getRParenLoc(), None, None);
11908 }
11909
11910 // Try to compute the result without performing a partial substitution.
11911 Optional<unsigned> Result = 0;
11912 for (const TemplateArgument &Arg : PackArgs) {
11913 if (!Arg.isPackExpansion()) {
11914 Result = *Result + 1;
11915 continue;
11916 }
11917
11918 TemplateArgumentLoc ArgLoc;
11919 InventTemplateArgumentLoc(Arg, ArgLoc);
11920
11921 // Find the pattern of the pack expansion.
11922 SourceLocation Ellipsis;
11923 Optional<unsigned> OrigNumExpansions;
11924 TemplateArgumentLoc Pattern =
11925 getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
11926 OrigNumExpansions);
11927
11928 // Substitute under the pack expansion. Do not expand the pack (yet).
11929 TemplateArgumentLoc OutPattern;
11930 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11931 if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
11932 /*Uneval*/ true))
11933 return true;
11934
11935 // See if we can determine the number of arguments from the result.
11936 Optional<unsigned> NumExpansions =
11937 getSema().getFullyPackExpandedSize(OutPattern.getArgument());
11938 if (!NumExpansions) {
11939 // No: we must be in an alias template expansion, and we're going to need
11940 // to actually expand the packs.
11941 Result = None;
11942 break;
11943 }
11944
11945 Result = *Result + *NumExpansions;
11946 }
11947
11948 // Common case: we could determine the number of expansions without
11949 // substituting.
11950 if (Result)
11951 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11952 E->getPackLoc(),
11953 E->getRParenLoc(), *Result, None);
11954
11955 TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
11956 E->getPackLoc());
11957 {
11958 TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
11959 typedef TemplateArgumentLocInventIterator<
11960 Derived, const TemplateArgument*> PackLocIterator;
11961 if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
11962 PackLocIterator(*this, PackArgs.end()),
11963 TransformedPackArgs, /*Uneval*/true))
11964 return ExprError();
11965 }
11966
11967 // Check whether we managed to fully-expand the pack.
11968 // FIXME: Is it possible for us to do so and not hit the early exit path?
11969 SmallVector<TemplateArgument, 8> Args;
11970 bool PartialSubstitution = false;
11971 for (auto &Loc : TransformedPackArgs.arguments()) {
11972 Args.push_back(Loc.getArgument());
11973 if (Loc.getArgument().isPackExpansion())
11974 PartialSubstitution = true;
11975 }
11976
11977 if (PartialSubstitution)
11978 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11979 E->getPackLoc(),
11980 E->getRParenLoc(), None, Args);
11981
11982 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11983 E->getPackLoc(), E->getRParenLoc(),
11984 Args.size(), None);
11985}
11986
11987template<typename Derived>
11988ExprResult
11989TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
11990 SubstNonTypeTemplateParmPackExpr *E) {
11991 // Default behavior is to do nothing with this transformation.
11992 return E;
11993}
11994
11995template<typename Derived>
11996ExprResult
11997TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
11998 SubstNonTypeTemplateParmExpr *E) {
11999 // Default behavior is to do nothing with this transformation.
12000 return E;
12001}
12002
12003template<typename Derived>
12004ExprResult
12005TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
12006 // Default behavior is to do nothing with this transformation.
12007 return E;
12008}
12009
12010template<typename Derived>
12011ExprResult
12012TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
12013 MaterializeTemporaryExpr *E) {
12014 return getDerived().TransformExpr(E->GetTemporaryExpr());
12015}
12016
12017template<typename Derived>
12018ExprResult
12019TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
12020 Expr *Pattern = E->getPattern();
12021
12022 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12023 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
12024 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")((!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? static_cast<void> (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 12024, __PRETTY_FUNCTION__))
;
12025
12026 // Determine whether the set of unexpanded parameter packs can and should
12027 // be expanded.
12028 bool Expand = true;
12029 bool RetainExpansion = false;
12030 Optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
12031 NumExpansions = OrigNumExpansions;
12032 if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
12033 Pattern->getSourceRange(),
12034 Unexpanded,
12035 Expand, RetainExpansion,
12036 NumExpansions))
12037 return true;
12038
12039 if (!Expand) {
12040 // Do not expand any packs here, just transform and rebuild a fold
12041 // expression.
12042 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12043
12044 ExprResult LHS =
12045 E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
12046 if (LHS.isInvalid())
12047 return true;
12048
12049 ExprResult RHS =
12050 E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
12051 if (RHS.isInvalid())
12052 return true;
12053
12054 if (!getDerived().AlwaysRebuild() &&
12055 LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
12056 return E;
12057
12058 return getDerived().RebuildCXXFoldExpr(
12059 E->getBeginLoc(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
12060 RHS.get(), E->getEndLoc(), NumExpansions);
12061 }
12062
12063 // The transform has determined that we should perform an elementwise
12064 // expansion of the pattern. Do so.
12065 ExprResult Result = getDerived().TransformExpr(E->getInit());
12066 if (Result.isInvalid())
12067 return true;
12068 bool LeftFold = E->isLeftFold();
12069
12070 // If we're retaining an expansion for a right fold, it is the innermost
12071 // component and takes the init (if any).
12072 if (!LeftFold && RetainExpansion) {
12073 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12074
12075 ExprResult Out = getDerived().TransformExpr(Pattern);
12076 if (Out.isInvalid())
12077 return true;
12078
12079 Result = getDerived().RebuildCXXFoldExpr(
12080 E->getBeginLoc(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
12081 Result.get(), E->getEndLoc(), OrigNumExpansions);
12082 if (Result.isInvalid())
12083 return true;
12084 }
12085
12086 for (unsigned I = 0; I != *NumExpansions; ++I) {
12087 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
12088 getSema(), LeftFold ? I : *NumExpansions - I - 1);
12089 ExprResult Out = getDerived().TransformExpr(Pattern);
12090 if (Out.isInvalid())
12091 return true;
12092
12093 if (Out.get()->containsUnexpandedParameterPack()) {
12094 // We still have a pack; retain a pack expansion for this slice.
12095 Result = getDerived().RebuildCXXFoldExpr(
12096 E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
12097 E->getOperator(), E->getEllipsisLoc(),
12098 LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
12099 OrigNumExpansions);
12100 } else if (Result.isUsable()) {
12101 // We've got down to a single element; build a binary operator.
12102 Result = getDerived().RebuildBinaryOperator(
12103 E->getEllipsisLoc(), E->getOperator(),
12104 LeftFold ? Result.get() : Out.get(),
12105 LeftFold ? Out.get() : Result.get());
12106 } else
12107 Result = Out;
12108
12109 if (Result.isInvalid())
12110 return true;
12111 }
12112
12113 // If we're retaining an expansion for a left fold, it is the outermost
12114 // component and takes the complete expansion so far as its init (if any).
12115 if (LeftFold && RetainExpansion) {
12116 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12117
12118 ExprResult Out = getDerived().TransformExpr(Pattern);
12119 if (Out.isInvalid())
12120 return true;
12121
12122 Result = getDerived().RebuildCXXFoldExpr(
12123 E->getBeginLoc(), Result.get(), E->getOperator(), E->getEllipsisLoc(),
12124 Out.get(), E->getEndLoc(), OrigNumExpansions);
12125 if (Result.isInvalid())
12126 return true;
12127 }
12128
12129 // If we had no init and an empty pack, and we're not retaining an expansion,
12130 // then produce a fallback value or error.
12131 if (Result.isUnset())
12132 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
12133 E->getOperator());
12134
12135 return Result;
12136}
12137
12138template<typename Derived>
12139ExprResult
12140TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
12141 CXXStdInitializerListExpr *E) {
12142 return getDerived().TransformExpr(E->getSubExpr());
12143}
12144
12145template<typename Derived>
12146ExprResult
12147TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
12148 return SemaRef.MaybeBindToTemporary(E);
12149}
12150
12151template<typename Derived>
12152ExprResult
12153TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
12154 return E;
12155}
12156
12157template<typename Derived>
12158ExprResult
12159TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
12160 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12161 if (SubExpr.isInvalid())
12162 return ExprError();
12163
12164 if (!getDerived().AlwaysRebuild() &&
12165 SubExpr.get() == E->getSubExpr())
12166 return E;
12167
12168 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
12169}
12170
12171template<typename Derived>
12172ExprResult
12173TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
12174 // Transform each of the elements.
12175 SmallVector<Expr *, 8> Elements;
12176 bool ArgChanged = false;
12177 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
12178 /*IsCall=*/false, Elements, &ArgChanged))
12179 return ExprError();
12180
12181 if (!getDerived().AlwaysRebuild() && !ArgChanged)
12182 return SemaRef.MaybeBindToTemporary(E);
12183
12184 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
12185 Elements.data(),
12186 Elements.size());
12187}
12188
12189template<typename Derived>
12190ExprResult
12191TreeTransform<Derived>::TransformObjCDictionaryLiteral(
12192 ObjCDictionaryLiteral *E) {
12193 // Transform each of the elements.
12194 SmallVector<ObjCDictionaryElement, 8> Elements;
12195 bool ArgChanged = false;
12196 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
12197 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
12198
12199 if (OrigElement.isPackExpansion()) {
12200 // This key/value element is a pack expansion.
12201 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12202 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
12203 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
12204 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")((!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? static_cast<void> (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 12204, __PRETTY_FUNCTION__))
;
12205
12206 // Determine whether the set of unexpanded parameter packs can
12207 // and should be expanded.
12208 bool Expand = true;
12209 bool RetainExpansion = false;
12210 Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
12211 Optional<unsigned> NumExpansions = OrigNumExpansions;
12212 SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
12213 OrigElement.Value->getEndLoc());
12214 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
12215 PatternRange, Unexpanded, Expand,
12216 RetainExpansion, NumExpansions))
12217 return ExprError();
12218
12219 if (!Expand) {
12220 // The transform has determined that we should perform a simple
12221 // transformation on the pack expansion, producing another pack
12222 // expansion.
12223 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12224 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12225 if (Key.isInvalid())
12226 return ExprError();
12227
12228 if (Key.get() != OrigElement.Key)
12229 ArgChanged = true;
12230
12231 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12232 if (Value.isInvalid())
12233 return ExprError();
12234
12235 if (Value.get() != OrigElement.Value)
12236 ArgChanged = true;
12237
12238 ObjCDictionaryElement Expansion = {
12239 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
12240 };
12241 Elements.push_back(Expansion);
12242 continue;
12243 }
12244
12245 // Record right away that the argument was changed. This needs
12246 // to happen even if the array expands to nothing.
12247 ArgChanged = true;
12248
12249 // The transform has determined that we should perform an elementwise
12250 // expansion of the pattern. Do so.
12251 for (unsigned I = 0; I != *NumExpansions; ++I) {
12252 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12253 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12254 if (Key.isInvalid())
12255 return ExprError();
12256
12257 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12258 if (Value.isInvalid())
12259 return ExprError();
12260
12261 ObjCDictionaryElement Element = {
12262 Key.get(), Value.get(), SourceLocation(), NumExpansions
12263 };
12264
12265 // If any unexpanded parameter packs remain, we still have a
12266 // pack expansion.
12267 // FIXME: Can this really happen?
12268 if (Key.get()->containsUnexpandedParameterPack() ||
12269 Value.get()->containsUnexpandedParameterPack())
12270 Element.EllipsisLoc = OrigElement.EllipsisLoc;
12271
12272 Elements.push_back(Element);
12273 }
12274
12275 // FIXME: Retain a pack expansion if RetainExpansion is true.
12276
12277 // We've finished with this pack expansion.
12278 continue;
12279 }
12280
12281 // Transform and check key.
12282 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12283 if (Key.isInvalid())
12284 return ExprError();
12285
12286 if (Key.get() != OrigElement.Key)
12287 ArgChanged = true;
12288
12289 // Transform and check value.
12290 ExprResult Value
12291 = getDerived().TransformExpr(OrigElement.Value);
12292 if (Value.isInvalid())
12293 return ExprError();
12294
12295 if (Value.get() != OrigElement.Value)
12296 ArgChanged = true;
12297
12298 ObjCDictionaryElement Element = {
12299 Key.get(), Value.get(), SourceLocation(), None
12300 };
12301 Elements.push_back(Element);
12302 }
12303
12304 if (!getDerived().AlwaysRebuild() && !ArgChanged)
12305 return SemaRef.MaybeBindToTemporary(E);
12306
12307 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
12308 Elements);
12309}
12310
12311template<typename Derived>
12312ExprResult
12313TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
12314 TypeSourceInfo *EncodedTypeInfo
12315 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
12316 if (!EncodedTypeInfo)
12317 return ExprError();
12318
12319 if (!getDerived().AlwaysRebuild() &&
12320 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
12321 return E;
12322
12323 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
12324 EncodedTypeInfo,
12325 E->getRParenLoc());
12326}
12327
12328template<typename Derived>
12329ExprResult TreeTransform<Derived>::
12330TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
12331 // This is a kind of implicit conversion, and it needs to get dropped
12332 // and recomputed for the same general reasons that ImplicitCastExprs
12333 // do, as well a more specific one: this expression is only valid when
12334 // it appears *immediately* as an argument expression.
12335 return getDerived().TransformExpr(E->getSubExpr());
12336}
12337
12338template<typename Derived>
12339ExprResult TreeTransform<Derived>::
12340TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
12341 TypeSourceInfo *TSInfo
12342 = getDerived().TransformType(E->getTypeInfoAsWritten());
12343 if (!TSInfo)
12344 return ExprError();
12345
12346 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
12347 if (Result.isInvalid())
12348 return ExprError();
12349
12350 if (!getDerived().AlwaysRebuild() &&
12351 TSInfo == E->getTypeInfoAsWritten() &&
12352 Result.get() == E->getSubExpr())
12353 return E;
12354
12355 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
12356 E->getBridgeKeywordLoc(), TSInfo,
12357 Result.get());
12358}
12359
12360template <typename Derived>
12361ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
12362 ObjCAvailabilityCheckExpr *E) {
12363 return E;
12364}
12365
12366template<typename Derived>
12367ExprResult
12368TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
12369 // Transform arguments.
12370 bool ArgChanged = false;
12371 SmallVector<Expr*, 8> Args;
12372 Args.reserve(E->getNumArgs());
12373 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
12374 &ArgChanged))
12375 return ExprError();
12376
12377 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
12378 // Class message: transform the receiver type.
12379 TypeSourceInfo *ReceiverTypeInfo
12380 = getDerived().TransformType(E->getClassReceiverTypeInfo());
12381 if (!ReceiverTypeInfo)
12382 return ExprError();
12383
12384 // If nothing changed, just retain the existing message send.
12385 if (!getDerived().AlwaysRebuild() &&
12386 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
12387 return SemaRef.MaybeBindToTemporary(E);
12388
12389 // Build a new class message send.
12390 SmallVector<SourceLocation, 16> SelLocs;
12391 E->getSelectorLocs(SelLocs);
12392 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
12393 E->getSelector(),
12394 SelLocs,
12395 E->getMethodDecl(),
12396 E->getLeftLoc(),
12397 Args,
12398 E->getRightLoc());
12399 }
12400 else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
12401 E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12402 if (!E->getMethodDecl())
12403 return ExprError();
12404
12405 // Build a new class message send to 'super'.
12406 SmallVector<SourceLocation, 16> SelLocs;
12407 E->getSelectorLocs(SelLocs);
12408 return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
12409 E->getSelector(),
12410 SelLocs,
12411 E->getReceiverType(),
12412 E->getMethodDecl(),
12413 E->getLeftLoc(),
12414 Args,
12415 E->getRightLoc());
12416 }
12417
12418 // Instance message: transform the receiver
12419 assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&((E->getReceiverKind() == ObjCMessageExpr::Instance &&
"Only class and instance messages may be instantiated") ? static_cast
<void> (0) : __assert_fail ("E->getReceiverKind() == ObjCMessageExpr::Instance && \"Only class and instance messages may be instantiated\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 12420, __PRETTY_FUNCTION__))
12420 "Only class and instance messages may be instantiated")((E->getReceiverKind() == ObjCMessageExpr::Instance &&
"Only class and instance messages may be instantiated") ? static_cast
<void> (0) : __assert_fail ("E->getReceiverKind() == ObjCMessageExpr::Instance && \"Only class and instance messages may be instantiated\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 12420, __PRETTY_FUNCTION__))
;
12421 ExprResult Receiver
12422 = getDerived().TransformExpr(E->getInstanceReceiver());
12423 if (Receiver.isInvalid())
12424 return ExprError();
12425
12426 // If nothing changed, just retain the existing message send.
12427 if (!getDerived().AlwaysRebuild() &&
12428 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
12429 return SemaRef.MaybeBindToTemporary(E);
12430
12431 // Build a new instance message send.
12432 SmallVector<SourceLocation, 16> SelLocs;
12433 E->getSelectorLocs(SelLocs);
12434 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
12435 E->getSelector(),
12436 SelLocs,
12437 E->getMethodDecl(),
12438 E->getLeftLoc(),
12439 Args,
12440 E->getRightLoc());
12441}
12442
12443template<typename Derived>
12444ExprResult
12445TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
12446 return E;
12447}
12448
12449template<typename Derived>
12450ExprResult
12451TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
12452 return E;
12453}
12454
12455template<typename Derived>
12456ExprResult
12457TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
12458 // Transform the base expression.
12459 ExprResult Base = getDerived().TransformExpr(E->getBase());
12460 if (Base.isInvalid())
12461 return ExprError();
12462
12463 // We don't need to transform the ivar; it will never change.
12464
12465 // If nothing changed, just retain the existing expression.
12466 if (!getDerived().AlwaysRebuild() &&
12467 Base.get() == E->getBase())
12468 return E;
12469
12470 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
12471 E->getLocation(),
12472 E->isArrow(), E->isFreeIvar());
12473}
12474
12475template<typename Derived>
12476ExprResult
12477TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
12478 // 'super' and types never change. Property never changes. Just
12479 // retain the existing expression.
12480 if (!E->isObjectReceiver())
12481 return E;
12482
12483 // Transform the base expression.
12484 ExprResult Base = getDerived().TransformExpr(E->getBase());
12485 if (Base.isInvalid())
12486 return ExprError();
12487
12488 // We don't need to transform the property; it will never change.
12489
12490 // If nothing changed, just retain the existing expression.
12491 if (!getDerived().AlwaysRebuild() &&
12492 Base.get() == E->getBase())
12493 return E;
12494
12495 if (E->isExplicitProperty())
12496 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12497 E->getExplicitProperty(),
12498 E->getLocation());
12499
12500 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12501 SemaRef.Context.PseudoObjectTy,
12502 E->getImplicitPropertyGetter(),
12503 E->getImplicitPropertySetter(),
12504 E->getLocation());
12505}
12506
12507template<typename Derived>
12508ExprResult
12509TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
12510 // Transform the base expression.
12511 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
12512 if (Base.isInvalid())
12513 return ExprError();
12514
12515 // Transform the key expression.
12516 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
12517 if (Key.isInvalid())
12518 return ExprError();
12519
12520 // If nothing changed, just retain the existing expression.
12521 if (!getDerived().AlwaysRebuild() &&
12522 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
12523 return E;
12524
12525 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
12526 Base.get(), Key.get(),
12527 E->getAtIndexMethodDecl(),
12528 E->setAtIndexMethodDecl());
12529}
12530
12531template<typename Derived>
12532ExprResult
12533TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
12534 // Transform the base expression.
12535 ExprResult Base = getDerived().TransformExpr(E->getBase());
12536 if (Base.isInvalid())
12537 return ExprError();
12538
12539 // If nothing changed, just retain the existing expression.
12540 if (!getDerived().AlwaysRebuild() &&
12541 Base.get() == E->getBase())
12542 return E;
12543
12544 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
12545 E->getOpLoc(),
12546 E->isArrow());
12547}
12548
12549template<typename Derived>
12550ExprResult
12551TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
12552 bool ArgumentChanged = false;
12553 SmallVector<Expr*, 8> SubExprs;
12554 SubExprs.reserve(E->getNumSubExprs());
12555 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12556 SubExprs, &ArgumentChanged))
12557 return ExprError();
12558
12559 if (!getDerived().AlwaysRebuild() &&
12560 !ArgumentChanged)
12561 return E;
12562
12563 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
12564 SubExprs,
12565 E->getRParenLoc());
12566}
12567
12568template<typename Derived>
12569ExprResult
12570TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
12571 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
12572 if (SrcExpr.isInvalid())
12573 return ExprError();
12574
12575 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
12576 if (!Type)
12577 return ExprError();
12578
12579 if (!getDerived().AlwaysRebuild() &&
12580 Type == E->getTypeSourceInfo() &&
12581 SrcExpr.get() == E->getSrcExpr())
12582 return E;
12583
12584 return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
12585 SrcExpr.get(), Type,
12586 E->getRParenLoc());
12587}
12588
12589template<typename Derived>
12590ExprResult
12591TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
12592 BlockDecl *oldBlock = E->getBlockDecl();
12593
12594 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
12595 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
12596
12597 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
12598 blockScope->TheDecl->setBlockMissingReturnType(
12599 oldBlock->blockMissingReturnType());
12600
12601 SmallVector<ParmVarDecl*, 4> params;
12602 SmallVector<QualType, 4> paramTypes;
12603
12604 const FunctionProtoType *exprFunctionType = E->getFunctionType();
12605
12606 // Parameter substitution.
12607 Sema::ExtParameterInfoBuilder extParamInfos;
12608 if (getDerived().TransformFunctionTypeParams(
12609 E->getCaretLocation(), oldBlock->parameters(), nullptr,
12610 exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
12611 extParamInfos)) {
12612 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12613 return ExprError();
12614 }
12615
12616 QualType exprResultType =
12617 getDerived().TransformType(exprFunctionType->getReturnType());
12618
12619 auto epi = exprFunctionType->getExtProtoInfo();
12620 epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
12621
12622 QualType functionType =
12623 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
12624 blockScope->FunctionType = functionType;
12625
12626 // Set the parameters on the block decl.
12627 if (!params.empty())
12628 blockScope->TheDecl->setParams(params);
12629
12630 if (!oldBlock->blockMissingReturnType()) {
12631 blockScope->HasImplicitReturnType = false;
12632 blockScope->ReturnType = exprResultType;
12633 }
12634
12635 // Transform the body
12636 StmtResult body = getDerived().TransformStmt(E->getBody());
12637 if (body.isInvalid()) {
12638 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12639 return ExprError();
12640 }
12641
12642#ifndef NDEBUG
12643 // In builds with assertions, make sure that we captured everything we
12644 // captured before.
12645 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
12646 for (const auto &I : oldBlock->captures()) {
12647 VarDecl *oldCapture = I.getVariable();
12648
12649 // Ignore parameter packs.
12650 if (oldCapture->isParameterPack())
12651 continue;
12652
12653 VarDecl *newCapture =
12654 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
12655 oldCapture));
12656 assert(blockScope->CaptureMap.count(newCapture))((blockScope->CaptureMap.count(newCapture)) ? static_cast<
void> (0) : __assert_fail ("blockScope->CaptureMap.count(newCapture)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 12656, __PRETTY_FUNCTION__))
;
12657 }
12658 assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured())((oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured
()) ? static_cast<void> (0) : __assert_fail ("oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 12658, __PRETTY_FUNCTION__))
;
12659 }
12660#endif
12661
12662 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
12663 /*Scope=*/nullptr);
12664}
12665
12666template<typename Derived>
12667ExprResult
12668TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
12669 llvm_unreachable("Cannot transform asType expressions yet")::llvm::llvm_unreachable_internal("Cannot transform asType expressions yet"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 12669)
;
12670}
12671
12672template<typename Derived>
12673ExprResult
12674TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
12675 bool ArgumentChanged = false;
12676 SmallVector<Expr*, 8> SubExprs;
12677 SubExprs.reserve(E->getNumSubExprs());
12678 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12679 SubExprs, &ArgumentChanged))
12680 return ExprError();
12681
12682 if (!getDerived().AlwaysRebuild() &&
12683 !ArgumentChanged)
12684 return E;
12685
12686 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
12687 E->getOp(), E->getRParenLoc());
12688}
12689
12690//===----------------------------------------------------------------------===//
12691// Type reconstruction
12692//===----------------------------------------------------------------------===//
12693
12694template<typename Derived>
12695QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
12696 SourceLocation Star) {
12697 return SemaRef.BuildPointerType(PointeeType, Star,
12698 getDerived().getBaseEntity());
12699}
12700
12701template<typename Derived>
12702QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
12703 SourceLocation Star) {
12704 return SemaRef.BuildBlockPointerType(PointeeType, Star,
12705 getDerived().getBaseEntity());
12706}
12707
12708template<typename Derived>
12709QualType
12710TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
12711 bool WrittenAsLValue,
12712 SourceLocation Sigil) {
12713 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
12714 Sigil, getDerived().getBaseEntity());
12715}
12716
12717template<typename Derived>
12718QualType
12719TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
12720 QualType ClassType,
12721 SourceLocation Sigil) {
12722 return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
12723 getDerived().getBaseEntity());
12724}
12725
12726template<typename Derived>
12727QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
12728 const ObjCTypeParamDecl *Decl,
12729 SourceLocation ProtocolLAngleLoc,
12730 ArrayRef<ObjCProtocolDecl *> Protocols,
12731 ArrayRef<SourceLocation> ProtocolLocs,
12732 SourceLocation ProtocolRAngleLoc) {
12733 return SemaRef.BuildObjCTypeParamType(Decl,
12734 ProtocolLAngleLoc, Protocols,
12735 ProtocolLocs, ProtocolRAngleLoc,
12736 /*FailOnError=*/true);
12737}
12738
12739template<typename Derived>
12740QualType TreeTransform<Derived>::RebuildObjCObjectType(
12741 QualType BaseType,
12742 SourceLocation Loc,
12743 SourceLocation TypeArgsLAngleLoc,
12744 ArrayRef<TypeSourceInfo *> TypeArgs,
12745 SourceLocation TypeArgsRAngleLoc,
12746 SourceLocation ProtocolLAngleLoc,
12747 ArrayRef<ObjCProtocolDecl *> Protocols,
12748 ArrayRef<SourceLocation> ProtocolLocs,
12749 SourceLocation ProtocolRAngleLoc) {
12750 return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
12751 TypeArgs, TypeArgsRAngleLoc,
12752 ProtocolLAngleLoc, Protocols, ProtocolLocs,
12753 ProtocolRAngleLoc,
12754 /*FailOnError=*/true);
12755}
12756
12757template<typename Derived>
12758QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
12759 QualType PointeeType,
12760 SourceLocation Star) {
12761 return SemaRef.Context.getObjCObjectPointerType(PointeeType);
12762}
12763
12764template<typename Derived>
12765QualType
12766TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
12767 ArrayType::ArraySizeModifier SizeMod,
12768 const llvm::APInt *Size,
12769 Expr *SizeExpr,
12770 unsigned IndexTypeQuals,
12771 SourceRange BracketsRange) {
12772 if (SizeExpr || !Size)
12773 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
12774 IndexTypeQuals, BracketsRange,
12775 getDerived().getBaseEntity());
12776
12777 QualType Types[] = {
12778 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
12779 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
12780 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
12781 };
12782 const unsigned NumTypes = llvm::array_lengthof(Types);
12783 QualType SizeType;
12784 for (unsigned I = 0; I != NumTypes; ++I)
12785 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
12786 SizeType = Types[I];
12787 break;
12788 }
12789
12790 // Note that we can return a VariableArrayType here in the case where
12791 // the element type was a dependent VariableArrayType.
12792 IntegerLiteral *ArraySize
12793 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
12794 /*FIXME*/BracketsRange.getBegin());
12795 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
12796 IndexTypeQuals, BracketsRange,
12797 getDerived().getBaseEntity());
12798}
12799
12800template<typename Derived>
12801QualType
12802TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
12803 ArrayType::ArraySizeModifier SizeMod,
12804 const llvm::APInt &Size,
12805 unsigned IndexTypeQuals,
12806 SourceRange BracketsRange) {
12807 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, nullptr,
12808 IndexTypeQuals, BracketsRange);
12809}
12810
12811template<typename Derived>
12812QualType
12813TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
12814 ArrayType::ArraySizeModifier SizeMod,
12815 unsigned IndexTypeQuals,
12816 SourceRange BracketsRange) {
12817 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
12818 IndexTypeQuals, BracketsRange);
12819}
12820
12821template<typename Derived>
12822QualType
12823TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
12824 ArrayType::ArraySizeModifier SizeMod,
12825 Expr *SizeExpr,
12826 unsigned IndexTypeQuals,
12827 SourceRange BracketsRange) {
12828 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12829 SizeExpr,
12830 IndexTypeQuals, BracketsRange);
12831}
12832
12833template<typename Derived>
12834QualType
12835TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
12836 ArrayType::ArraySizeModifier SizeMod,
12837 Expr *SizeExpr,
12838 unsigned IndexTypeQuals,
12839 SourceRange BracketsRange) {
12840 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12841 SizeExpr,
12842 IndexTypeQuals, BracketsRange);
12843}
12844
12845template <typename Derived>
12846QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
12847 QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
12848 return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
12849 AttributeLoc);
12850}
12851
12852template <typename Derived>
12853QualType
12854TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
12855 unsigned NumElements,
12856 VectorType::VectorKind VecKind) {
12857 // FIXME: semantic checking!
12858 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
12859}
12860
12861template <typename Derived>
12862QualType TreeTransform<Derived>::RebuildDependentVectorType(
12863 QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
12864 VectorType::VectorKind VecKind) {
12865 return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
12866}
12867
12868template<typename Derived>
12869QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
12870 unsigned NumElements,
12871 SourceLocation AttributeLoc) {
12872 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
12873 NumElements, true);
12874 IntegerLiteral *VectorSize
12875 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
12876 AttributeLoc);
12877 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
12878}
12879
12880template<typename Derived>
12881QualType
12882TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
12883 Expr *SizeExpr,
12884 SourceLocation AttributeLoc) {
12885 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
12886}
12887
12888template<typename Derived>
12889QualType TreeTransform<Derived>::RebuildFunctionProtoType(
12890 QualType T,
12891 MutableArrayRef<QualType> ParamTypes,
12892 const FunctionProtoType::ExtProtoInfo &EPI) {
12893 return SemaRef.BuildFunctionType(T, ParamTypes,
12894 getDerived().getBaseLocation(),
12895 getDerived().getBaseEntity(),
12896 EPI);
12897}
12898
12899template<typename Derived>
12900QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
12901 return SemaRef.Context.getFunctionNoProtoType(T);
12902}
12903
12904template<typename Derived>
12905QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
12906 Decl *D) {
12907 assert(D && "no decl found")((D && "no decl found") ? static_cast<void> (0)
: __assert_fail ("D && \"no decl found\"", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 12907, __PRETTY_FUNCTION__))
;
12908 if (D->isInvalidDecl()) return QualType();
12909
12910 // FIXME: Doesn't account for ObjCInterfaceDecl!
12911 TypeDecl *Ty;
12912 if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
12913 // A valid resolved using typename pack expansion decl can have multiple
12914 // UsingDecls, but they must each have exactly one type, and it must be
12915 // the same type in every case. But we must have at least one expansion!
12916 if (UPD->expansions().empty()) {
12917 getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
12918 << UPD->isCXXClassMember() << UPD;
12919 return QualType();
12920 }
12921
12922 // We might still have some unresolved types. Try to pick a resolved type
12923 // if we can. The final instantiation will check that the remaining
12924 // unresolved types instantiate to the type we pick.
12925 QualType FallbackT;
12926 QualType T;
12927 for (auto *E : UPD->expansions()) {
12928 QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
12929 if (ThisT.isNull())
12930 continue;
12931 else if (ThisT->getAs<UnresolvedUsingType>())
12932 FallbackT = ThisT;
12933 else if (T.isNull())
12934 T = ThisT;
12935 else
12936 assert(getSema().Context.hasSameType(ThisT, T) &&((getSema().Context.hasSameType(ThisT, T) && "mismatched resolved types in using pack expansion"
) ? static_cast<void> (0) : __assert_fail ("getSema().Context.hasSameType(ThisT, T) && \"mismatched resolved types in using pack expansion\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 12937, __PRETTY_FUNCTION__))
12937 "mismatched resolved types in using pack expansion")((getSema().Context.hasSameType(ThisT, T) && "mismatched resolved types in using pack expansion"
) ? static_cast<void> (0) : __assert_fail ("getSema().Context.hasSameType(ThisT, T) && \"mismatched resolved types in using pack expansion\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 12937, __PRETTY_FUNCTION__))
;
12938 }
12939 return T.isNull() ? FallbackT : T;
12940 } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
12941 assert(Using->hasTypename() &&((Using->hasTypename() && "UnresolvedUsingTypenameDecl transformed to non-typename using"
) ? static_cast<void> (0) : __assert_fail ("Using->hasTypename() && \"UnresolvedUsingTypenameDecl transformed to non-typename using\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 12942, __PRETTY_FUNCTION__))
12942 "UnresolvedUsingTypenameDecl transformed to non-typename using")((Using->hasTypename() && "UnresolvedUsingTypenameDecl transformed to non-typename using"
) ? static_cast<void> (0) : __assert_fail ("Using->hasTypename() && \"UnresolvedUsingTypenameDecl transformed to non-typename using\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 12942, __PRETTY_FUNCTION__))
;
12943
12944 // A valid resolved using typename decl points to exactly one type decl.
12945 assert(++Using->shadow_begin() == Using->shadow_end())((++Using->shadow_begin() == Using->shadow_end()) ? static_cast
<void> (0) : __assert_fail ("++Using->shadow_begin() == Using->shadow_end()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 12945, __PRETTY_FUNCTION__))
;
12946 Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
12947 } else {
12948 assert(isa<UnresolvedUsingTypenameDecl>(D) &&((isa<UnresolvedUsingTypenameDecl>(D) && "UnresolvedUsingTypenameDecl transformed to non-using decl"
) ? static_cast<void> (0) : __assert_fail ("isa<UnresolvedUsingTypenameDecl>(D) && \"UnresolvedUsingTypenameDecl transformed to non-using decl\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 12949, __PRETTY_FUNCTION__))
12949 "UnresolvedUsingTypenameDecl transformed to non-using decl")((isa<UnresolvedUsingTypenameDecl>(D) && "UnresolvedUsingTypenameDecl transformed to non-using decl"
) ? static_cast<void> (0) : __assert_fail ("isa<UnresolvedUsingTypenameDecl>(D) && \"UnresolvedUsingTypenameDecl transformed to non-using decl\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/TreeTransform.h"
, 12949, __PRETTY_FUNCTION__))
;
12950 Ty = cast<UnresolvedUsingTypenameDecl>(D);
12951 }
12952
12953 return SemaRef.Context.getTypeDeclType(Ty);
12954}
12955
12956template<typename Derived>
12957QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
12958 SourceLocation Loc) {
12959 return SemaRef.BuildTypeofExprType(E, Loc);
12960}
12961
12962template<typename Derived>
12963QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
12964 return SemaRef.Context.getTypeOfType(Underlying);
12965}
12966
12967template<typename Derived>
12968QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
12969 SourceLocation Loc) {
12970 return SemaRef.BuildDecltypeType(E, Loc);
12971}
12972
12973template<typename Derived>
12974QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
12975 UnaryTransformType::UTTKind UKind,
12976 SourceLocation Loc) {
12977 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
12978}
12979
12980template<typename Derived>
12981QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
12982 TemplateName Template,
12983 SourceLocation TemplateNameLoc,
12984 TemplateArgumentListInfo &TemplateArgs) {
12985 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
12986}
12987
12988template<typename Derived>
12989QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
12990 SourceLocation KWLoc) {
12991 return SemaRef.BuildAtomicType(ValueType, KWLoc);
12992}
12993
12994template<typename Derived>
12995QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
12996 SourceLocation KWLoc,
12997 bool isReadPipe) {
12998 return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
12999 : SemaRef.BuildWritePipeType(ValueType, KWLoc);
13000}
13001
13002template<typename Derived>
13003TemplateName
13004TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13005 bool TemplateKW,
13006 TemplateDecl *Template) {
13007 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
13008 Template);
13009}
13010
13011template<typename Derived>
13012TemplateName
13013TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13014 SourceLocation TemplateKWLoc,
13015 const IdentifierInfo &Name,
13016 SourceLocation NameLoc,
13017 QualType ObjectType,
13018 NamedDecl *FirstQualifierInScope,
13019 bool AllowInjectedClassName) {
13020 UnqualifiedId TemplateName;
13021 TemplateName.setIdentifier(&Name, NameLoc);
13022 Sema::TemplateTy Template;
13023 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13024 SS, TemplateKWLoc, TemplateName,
13025 ParsedType::make(ObjectType),
13026 /*EnteringContext=*/false,
13027 Template, AllowInjectedClassName);
13028 return Template.get();
13029}
13030
13031template<typename Derived>
13032TemplateName
13033TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13034 SourceLocation TemplateKWLoc,
13035 OverloadedOperatorKind Operator,
13036 SourceLocation NameLoc,
13037 QualType ObjectType,
13038 bool AllowInjectedClassName) {
13039 UnqualifiedId Name;
13040 // FIXME: Bogus location information.
13041 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
13042 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
13043 Sema::TemplateTy Template;
13044 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13045 SS, TemplateKWLoc, Name,
13046 ParsedType::make(ObjectType),
13047 /*EnteringContext=*/false,
13048 Template, AllowInjectedClassName);
13049 return Template.get();
13050}
13051
13052template<typename Derived>
13053ExprResult
13054TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
13055 SourceLocation OpLoc,
13056 Expr *OrigCallee,
13057 Expr *First,
13058 Expr *Second) {
13059 Expr *Callee = OrigCallee->IgnoreParenCasts();
13060 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
13061
13062 if (First->getObjectKind() == OK_ObjCProperty) {
13063 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13064 if (BinaryOperator::isAssignmentOp(Opc))
13065 return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
13066 First, Second);
13067 ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
13068 if (Result.isInvalid())
13069 return ExprError();
13070 First = Result.get();
13071 }
13072
13073 if (Second && Second->getObjectKind() == OK_ObjCProperty) {
13074 ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
13075 if (Result.isInvalid())
13076 return ExprError();
13077 Second = Result.get();
13078 }
13079
13080 // Determine whether this should be a builtin operation.
13081 if (Op == OO_Subscript) {
13082 if (!First->getType()->isOverloadableType() &&
13083 !Second->getType()->isOverloadableType())
13084 return getSema().CreateBuiltinArraySubscriptExpr(
13085 First, Callee->getBeginLoc(), Second, OpLoc);
13086 } else if (Op == OO_Arrow) {
13087 // -> is never a builtin operation.
13088 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
13089 } else if (Second == nullptr || isPostIncDec) {
13090 if (!First->getType()->isOverloadableType() ||
13091 (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
13092 // The argument is not of overloadable type, or this is an expression
13093 // of the form &Class::member, so try to create a built-in unary
13094 // operation.
13095 UnaryOperatorKind Opc
13096 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13097
13098 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
13099 }
13100 } else {
13101 if (!First->getType()->isOverloadableType() &&
13102 !Second->getType()->isOverloadableType()) {
13103 // Neither of the arguments is an overloadable type, so try to
13104 // create a built-in binary operation.
13105 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13106 ExprResult Result
13107 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
13108 if (Result.isInvalid())
13109 return ExprError();
13110
13111 return Result;
13112 }
13113 }
13114
13115 // Compute the transformed set of functions (and function templates) to be
13116 // used during overload resolution.
13117 UnresolvedSet<16> Functions;
13118 bool RequiresADL;
13119
13120 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
13121 Functions.append(ULE->decls_begin(), ULE->decls_end());
13122 // If the overload could not be resolved in the template definition
13123 // (because we had a dependent argument), ADL is performed as part of
13124 // template instantiation.
13125 RequiresADL = ULE->requiresADL();
13126 } else {
13127 // If we've resolved this to a particular non-member function, just call
13128 // that function. If we resolved it to a member function,
13129 // CreateOverloaded* will find that function for us.
13130 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
13131 if (!isa<CXXMethodDecl>(ND))
13132 Functions.addDecl(ND);
13133 RequiresADL = false;
13134 }
13135
13136 // Add any functions found via argument-dependent lookup.
13137 Expr *Args[2] = { First, Second };
13138 unsigned NumArgs = 1 + (Second != nullptr);
13139
13140 // Create the overloaded operator invocation for unary operators.
13141 if (NumArgs == 1 || isPostIncDec) {
13142 UnaryOperatorKind Opc
13143 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13144 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
13145 RequiresADL);
13146 }
13147
13148 if (Op == OO_Subscript) {
13149 SourceLocation LBrace;
13150 SourceLocation RBrace;
13151
13152 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
13153 DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
13154 LBrace = SourceLocation::getFromRawEncoding(
13155 NameLoc.CXXOperatorName.BeginOpNameLoc);
13156 RBrace = SourceLocation::getFromRawEncoding(
13157 NameLoc.CXXOperatorName.EndOpNameLoc);
13158 } else {
13159 LBrace = Callee->getBeginLoc();
13160 RBrace = OpLoc;
13161 }
13162
13163 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
13164 First, Second);
13165 }
13166
13167 // Create the overloaded operator invocation for binary operators.
13168 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13169 ExprResult Result = SemaRef.CreateOverloadedBinOp(
13170 OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
13171 if (Result.isInvalid())
13172 return ExprError();
13173
13174 return Result;
13175}
13176
13177template<typename Derived>
13178ExprResult
13179TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
13180 SourceLocation OperatorLoc,
13181 bool isArrow,
13182 CXXScopeSpec &SS,
13183 TypeSourceInfo *ScopeType,
13184 SourceLocation CCLoc,
13185 SourceLocation TildeLoc,
13186 PseudoDestructorTypeStorage Destroyed) {
13187 QualType BaseType = Base->getType();
13188 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
13189 (!isArrow && !BaseType->getAs<RecordType>()) ||
13190 (isArrow && BaseType->getAs<PointerType>() &&
13191 !BaseType->getAs<PointerType>()->getPointeeType()
13192 ->template getAs<RecordType>())){
13193 // This pseudo-destructor expression is still a pseudo-destructor.
13194 return SemaRef.BuildPseudoDestructorExpr(
13195 Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
13196 CCLoc, TildeLoc, Destroyed);
13197 }
13198
13199 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
13200 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
13201 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
13202 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
13203 NameInfo.setNamedTypeInfo(DestroyedType);
13204
13205 // The scope type is now known to be a valid nested name specifier
13206 // component. Tack it on to the end of the nested name specifier.
13207 if (ScopeType) {
13208 if (!ScopeType->getType()->getAs<TagType>()) {
13209 getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
13210 diag::err_expected_class_or_namespace)
13211 << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
13212 return ExprError();
13213 }
13214 SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
13215 CCLoc);
13216 }
13217
13218 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
13219 return getSema().BuildMemberReferenceExpr(Base, BaseType,
13220 OperatorLoc, isArrow,
13221 SS, TemplateKWLoc,
13222 /*FIXME: FirstQualifier*/ nullptr,
13223 NameInfo,
13224 /*TemplateArgs*/ nullptr,
13225 /*S*/nullptr);
13226}
13227
13228template<typename Derived>
13229StmtResult
13230TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
13231 SourceLocation Loc = S->getBeginLoc();
13232 CapturedDecl *CD = S->getCapturedDecl();
13233 unsigned NumParams = CD->getNumParams();
13234 unsigned ContextParamPos = CD->getContextParamPosition();
13235 SmallVector<Sema::CapturedParamNameType, 4> Params;
13236 for (unsigned I = 0; I < NumParams; ++I) {
13237 if (I != ContextParamPos) {
13238 Params.push_back(
13239 std::make_pair(
13240 CD->getParam(I)->getName(),
13241 getDerived().TransformType(CD->getParam(I)->getType())));
13242 } else {
13243 Params.push_back(std::make_pair(StringRef(), QualType()));
13244 }
13245 }
13246 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
13247 S->getCapturedRegionKind(), Params);
13248 StmtResult Body;
13249 {
13250 Sema::CompoundScopeRAII CompoundScope(getSema());
13251 Body = getDerived().TransformStmt(S->getCapturedStmt());
13252 }
13253
13254 if (Body.isInvalid()) {
13255 getSema().ActOnCapturedRegionError();
13256 return StmtError();
13257 }
13258
13259 return getSema().ActOnCapturedRegionEnd(Body.get());
13260}
13261
13262} // end namespace clang
13263
13264#endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H

/build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/include/clang/AST/TypeNodes.inc

1/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\
2|* *|
3|* An x-macro database of Clang type nodes *|
4|* *|
5|* Automatically generated file, do not edit! *|
6|* *|
7\*===----------------------------------------------------------------------===*/
8
9#ifndef ABSTRACT_TYPE
10# define ABSTRACT_TYPE(Class, Base) TYPE(Class, Base)
11#endif
12#ifndef NON_CANONICAL_TYPE
13# define NON_CANONICAL_TYPE(Class, Base) TYPE(Class, Base)
14#endif
15#ifndef DEPENDENT_TYPE
16# define DEPENDENT_TYPE(Class, Base) TYPE(Class, Base)
17#endif
18#ifndef NON_CANONICAL_UNLESS_DEPENDENT_TYPE
19# define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) TYPE(Class, Base)
20#endif
21NON_CANONICAL_TYPE(Adjusted, Type)
22ABSTRACT_TYPE(Array, Type)
23TYPE(Atomic, Type)
24NON_CANONICAL_TYPE(Attributed, Type)
25TYPE(Auto, DeducedType)
26TYPE(BlockPointer, Type)
27TYPE(Builtin, Type)
28TYPE(Complex, Type)
29TYPE(ConstantArray, ArrayType)
30NON_CANONICAL_TYPE(Decayed, AdjustedType)
31NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Decltype, Type)
32TYPE(DeducedTemplateSpecialization, DeducedType)
33ABSTRACT_TYPE(Deduced, Type)
34DEPENDENT_TYPE(DependentAddressSpace, Type)
35DEPENDENT_TYPE(DependentName, Type)
36DEPENDENT_TYPE(DependentSizedArray, ArrayType)
37DEPENDENT_TYPE(DependentSizedExtVector, Type)
38DEPENDENT_TYPE(DependentTemplateSpecialization, Type)
39DEPENDENT_TYPE(DependentVector, Type)
40NON_CANONICAL_TYPE(Elaborated, Type)
41TYPE(Enum, TagType)
42TYPE(ExtVector, VectorType)
43TYPE(FunctionNoProto, FunctionType)
44TYPE(FunctionProto, FunctionType)
45ABSTRACT_TYPE(Function, Type)
46TYPE(IncompleteArray, ArrayType)
47DEPENDENT_TYPE(InjectedClassName, Type)
48TYPE(LValueReference, ReferenceType)
49NON_CANONICAL_TYPE(MacroQualified, Type)
50TYPE(MemberPointer, Type)
51TYPE(ObjCInterface, ObjCObjectType)
52TYPE(ObjCObjectPointer, Type)
53TYPE(ObjCObject, Type)
54NON_CANONICAL_TYPE(ObjCTypeParam, Type)
55NON_CANONICAL_UNLESS_DEPENDENT_TYPE(PackExpansion, Type)
56NON_CANONICAL_TYPE(Paren, Type)
57TYPE(Pipe, Type)
58TYPE(Pointer, Type)
59TYPE(RValueReference, ReferenceType)
6
Calling 'TreeTransform::TransformRValueReferenceType'
60TYPE(Record, TagType)
61ABSTRACT_TYPE(Reference, Type)
62DEPENDENT_TYPE(SubstTemplateTypeParmPack, Type)
63NON_CANONICAL_TYPE(SubstTemplateTypeParm, Type)
64ABSTRACT_TYPE(Tag, Type)
65NON_CANONICAL_UNLESS_DEPENDENT_TYPE(TemplateSpecialization, Type)
66DEPENDENT_TYPE(TemplateTypeParm, Type)
67NON_CANONICAL_UNLESS_DEPENDENT_TYPE(TypeOfExpr, Type)
68NON_CANONICAL_UNLESS_DEPENDENT_TYPE(TypeOf, Type)
69NON_CANONICAL_TYPE(Typedef, Type)
70NON_CANONICAL_UNLESS_DEPENDENT_TYPE(UnaryTransform, Type)
71DEPENDENT_TYPE(UnresolvedUsing, Type)
72TYPE(VariableArray, ArrayType)
3
Calling 'TreeTransform::TransformVariableArrayType'
73TYPE(Vector, Type)
74#ifdef LAST_TYPE
75LAST_TYPE(Vector)
76#undef LAST_TYPE
77#endif
78#ifdef LEAF_TYPE
79LEAF_TYPE(Builtin)
80LEAF_TYPE(Enum)
81LEAF_TYPE(InjectedClassName)
82LEAF_TYPE(ObjCInterface)
83LEAF_TYPE(Record)
84LEAF_TYPE(TemplateTypeParm)
85#undef LEAF_TYPE
86#endif
87#undef TYPE
88#undef ABSTRACT_TYPE
89#undef ABSTRACT_TYPE
90#undef NON_CANONICAL_TYPE
91#undef DEPENDENT_TYPE
92#undef NON_CANONICAL_UNLESS_DEPENDENT_TYPE

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/NestedNameSpecifier.h"
21#include "clang/AST/TemplateName.h"
22#include "clang/Basic/AddressSpaces.h"
23#include "clang/Basic/AttrKinds.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/ExceptionSpecificationType.h"
26#include "clang/Basic/LLVM.h"
27#include "clang/Basic/Linkage.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/Specifiers.h"
31#include "clang/Basic/Visibility.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/APSInt.h"
34#include "llvm/ADT/ArrayRef.h"
35#include "llvm/ADT/FoldingSet.h"
36#include "llvm/ADT/None.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/Twine.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/PointerLikeTypeTraits.h"
47#include "llvm/Support/type_traits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include <cassert>
50#include <cstddef>
51#include <cstdint>
52#include <cstring>
53#include <string>
54#include <type_traits>
55#include <utility>
56
57namespace clang {
58
59class ExtQuals;
60class QualType;
61class TagDecl;
62class Type;
63
64enum {
65 TypeAlignmentInBits = 4,
66 TypeAlignment = 1 << TypeAlignmentInBits
67};
68
69} // namespace clang
70
71namespace llvm {
72
73 template <typename T>
74 struct PointerLikeTypeTraits;
75 template<>
76 struct PointerLikeTypeTraits< ::clang::Type*> {
77 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
78
79 static inline ::clang::Type *getFromVoidPointer(void *P) {
80 return static_cast< ::clang::Type*>(P);
81 }
82
83 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
84 };
85
86 template<>
87 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
88 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
89
90 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
91 return static_cast< ::clang::ExtQuals*>(P);
92 }
93
94 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
95 };
96
97} // namespace llvm
98
99namespace clang {
100
101class ASTContext;
102template <typename> class CanQual;
103class CXXRecordDecl;
104class DeclContext;
105class EnumDecl;
106class Expr;
107class ExtQualsTypeCommonBase;
108class FunctionDecl;
109class IdentifierInfo;
110class NamedDecl;
111class ObjCInterfaceDecl;
112class ObjCProtocolDecl;
113class ObjCTypeParamDecl;
114struct PrintingPolicy;
115class RecordDecl;
116class Stmt;
117class TagDecl;
118class TemplateArgument;
119class TemplateArgumentListInfo;
120class TemplateArgumentLoc;
121class TemplateTypeParmDecl;
122class TypedefNameDecl;
123class UnresolvedUsingTypenameDecl;
124
125using CanQualType = CanQual<Type>;
126
127// Provide forward declarations for all of the *Type classes.
128#define TYPE(Class, Base) class Class##Type;
129#include "clang/AST/TypeNodes.inc"
130
131/// The collection of all-type qualifiers we support.
132/// Clang supports five independent qualifiers:
133/// * C99: const, volatile, and restrict
134/// * MS: __unaligned
135/// * Embedded C (TR18037): address spaces
136/// * Objective C: the GC attributes (none, weak, or strong)
137class Qualifiers {
138public:
139 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
140 Const = 0x1,
141 Restrict = 0x2,
142 Volatile = 0x4,
143 CVRMask = Const | Volatile | Restrict
144 };
145
146 enum GC {
147 GCNone = 0,
148 Weak,
149 Strong
150 };
151
152 enum ObjCLifetime {
153 /// There is no lifetime qualification on this type.
154 OCL_None,
155
156 /// This object can be modified without requiring retains or
157 /// releases.
158 OCL_ExplicitNone,
159
160 /// Assigning into this object requires the old value to be
161 /// released and the new value to be retained. The timing of the
162 /// release of the old value is inexact: it may be moved to
163 /// immediately after the last known point where the value is
164 /// live.
165 OCL_Strong,
166
167 /// Reading or writing from this object requires a barrier call.
168 OCL_Weak,
169
170 /// Assigning into this object requires a lifetime extension.
171 OCL_Autoreleasing
172 };
173
174 enum {
175 /// The maximum supported address space number.
176 /// 23 bits should be enough for anyone.
177 MaxAddressSpace = 0x7fffffu,
178
179 /// The width of the "fast" qualifier mask.
180 FastWidth = 3,
181
182 /// The fast qualifier mask.
183 FastMask = (1 << FastWidth) - 1
184 };
185
186 /// Returns the common set of qualifiers while removing them from
187 /// the given sets.
188 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
189 // If both are only CVR-qualified, bit operations are sufficient.
190 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
191 Qualifiers Q;
192 Q.Mask = L.Mask & R.Mask;
193 L.Mask &= ~Q.Mask;
194 R.Mask &= ~Q.Mask;
195 return Q;
196 }
197
198 Qualifiers Q;
199 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
200 Q.addCVRQualifiers(CommonCRV);
201 L.removeCVRQualifiers(CommonCRV);
202 R.removeCVRQualifiers(CommonCRV);
203
204 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
205 Q.setObjCGCAttr(L.getObjCGCAttr());
206 L.removeObjCGCAttr();
207 R.removeObjCGCAttr();
208 }
209
210 if (L.getObjCLifetime() == R.getObjCLifetime()) {
211 Q.setObjCLifetime(L.getObjCLifetime());
212 L.removeObjCLifetime();
213 R.removeObjCLifetime();
214 }
215
216 if (L.getAddressSpace() == R.getAddressSpace()) {
217 Q.setAddressSpace(L.getAddressSpace());
218 L.removeAddressSpace();
219 R.removeAddressSpace();
220 }
221 return Q;
222 }
223
224 static Qualifiers fromFastMask(unsigned Mask) {
225 Qualifiers Qs;
226 Qs.addFastQualifiers(Mask);
227 return Qs;
228 }
229
230 static Qualifiers fromCVRMask(unsigned CVR) {
231 Qualifiers Qs;
232 Qs.addCVRQualifiers(CVR);
233 return Qs;
234 }
235
236 static Qualifiers fromCVRUMask(unsigned CVRU) {
237 Qualifiers Qs;
238 Qs.addCVRUQualifiers(CVRU);
239 return Qs;
240 }
241
242 // Deserialize qualifiers from an opaque representation.
243 static Qualifiers fromOpaqueValue(unsigned opaque) {
244 Qualifiers Qs;
245 Qs.Mask = opaque;
246 return Qs;
247 }
248
249 // Serialize these qualifiers into an opaque representation.
250 unsigned getAsOpaqueValue() const {
251 return Mask;
252 }
253
254 bool hasConst() const { return Mask & Const; }
255 bool hasOnlyConst() const { return Mask == Const; }
256 void removeConst() { Mask &= ~Const; }
257 void addConst() { Mask |= Const; }
258
259 bool hasVolatile() const { return Mask & Volatile; }
260 bool hasOnlyVolatile() const { return Mask == Volatile; }
261 void removeVolatile() { Mask &= ~Volatile; }
262 void addVolatile() { Mask |= Volatile; }
263
264 bool hasRestrict() const { return Mask & Restrict; }
265 bool hasOnlyRestrict() const { return Mask == Restrict; }
266 void removeRestrict() { Mask &= ~Restrict; }
267 void addRestrict() { Mask |= Restrict; }
268
269 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
270 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
271 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
272
273 void setCVRQualifiers(unsigned mask) {
274 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 274, __PRETTY_FUNCTION__))
;
275 Mask = (Mask & ~CVRMask) | mask;
276 }
277 void removeCVRQualifiers(unsigned mask) {
278 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 278, __PRETTY_FUNCTION__))
;
279 Mask &= ~mask;
280 }
281 void removeCVRQualifiers() {
282 removeCVRQualifiers(CVRMask);
283 }
284 void addCVRQualifiers(unsigned mask) {
285 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 285, __PRETTY_FUNCTION__))
;
286 Mask |= mask;
287 }
288 void addCVRUQualifiers(unsigned mask) {
289 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 289, __PRETTY_FUNCTION__))
;
290 Mask |= mask;
291 }
292
293 bool hasUnaligned() const { return Mask & UMask; }
294 void setUnaligned(bool flag) {
295 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
296 }
297 void removeUnaligned() { Mask &= ~UMask; }
298 void addUnaligned() { Mask |= UMask; }
299
300 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
301 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
302 void setObjCGCAttr(GC type) {
303 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
304 }
305 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
306 void addObjCGCAttr(GC type) {
307 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 307, __PRETTY_FUNCTION__))
;
308 setObjCGCAttr(type);
309 }
310 Qualifiers withoutObjCGCAttr() const {
311 Qualifiers qs = *this;
312 qs.removeObjCGCAttr();
313 return qs;
314 }
315 Qualifiers withoutObjCLifetime() const {
316 Qualifiers qs = *this;
317 qs.removeObjCLifetime();
318 return qs;
319 }
320 Qualifiers withoutAddressSpace() const {
321 Qualifiers qs = *this;
322 qs.removeAddressSpace();
323 return qs;
324 }
325
326 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
327 ObjCLifetime getObjCLifetime() const {
328 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
329 }
330 void setObjCLifetime(ObjCLifetime type) {
331 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
332 }
333 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
334 void addObjCLifetime(ObjCLifetime type) {
335 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 335, __PRETTY_FUNCTION__))
;
336 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 336, __PRETTY_FUNCTION__))
;
337 Mask |= (type << LifetimeShift);
338 }
339
340 /// True if the lifetime is neither None or ExplicitNone.
341 bool hasNonTrivialObjCLifetime() const {
342 ObjCLifetime lifetime = getObjCLifetime();
343 return (lifetime > OCL_ExplicitNone);
344 }
345
346 /// True if the lifetime is either strong or weak.
347 bool hasStrongOrWeakObjCLifetime() const {
348 ObjCLifetime lifetime = getObjCLifetime();
349 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
350 }
351
352 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
353 LangAS getAddressSpace() const {
354 return static_cast<LangAS>(Mask >> AddressSpaceShift);
355 }
356 bool hasTargetSpecificAddressSpace() const {
357 return isTargetAddressSpace(getAddressSpace());
358 }
359 /// Get the address space attribute value to be printed by diagnostics.
360 unsigned getAddressSpaceAttributePrintValue() const {
361 auto Addr = getAddressSpace();
362 // This function is not supposed to be used with language specific
363 // address spaces. If that happens, the diagnostic message should consider
364 // printing the QualType instead of the address space value.
365 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 365, __PRETTY_FUNCTION__))
;
366 if (Addr != LangAS::Default)
367 return toTargetAddressSpace(Addr);
368 // TODO: The diagnostic messages where Addr may be 0 should be fixed
369 // since it cannot differentiate the situation where 0 denotes the default
370 // address space or user specified __attribute__((address_space(0))).
371 return 0;
372 }
373 void setAddressSpace(LangAS space) {
374 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 374, __PRETTY_FUNCTION__))
;
375 Mask = (Mask & ~AddressSpaceMask)
376 | (((uint32_t) space) << AddressSpaceShift);
377 }
378 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
379 void addAddressSpace(LangAS space) {
380 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 380, __PRETTY_FUNCTION__))
;
381 setAddressSpace(space);
382 }
383
384 // Fast qualifiers are those that can be allocated directly
385 // on a QualType object.
386 bool hasFastQualifiers() const { return getFastQualifiers(); }
387 unsigned getFastQualifiers() const { return Mask & FastMask; }
388 void setFastQualifiers(unsigned mask) {
389 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 389, __PRETTY_FUNCTION__))
;
390 Mask = (Mask & ~FastMask) | mask;
391 }
392 void removeFastQualifiers(unsigned mask) {
393 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 393, __PRETTY_FUNCTION__))
;
394 Mask &= ~mask;
395 }
396 void removeFastQualifiers() {
397 removeFastQualifiers(FastMask);
398 }
399 void addFastQualifiers(unsigned mask) {
400 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 400, __PRETTY_FUNCTION__))
;
401 Mask |= mask;
402 }
403
404 /// Return true if the set contains any qualifiers which require an ExtQuals
405 /// node to be allocated.
406 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
407 Qualifiers getNonFastQualifiers() const {
408 Qualifiers Quals = *this;
409 Quals.setFastQualifiers(0);
410 return Quals;
411 }
412
413 /// Return true if the set contains any qualifiers.
414 bool hasQualifiers() const { return Mask; }
415 bool empty() const { return !Mask; }
416
417 /// Add the qualifiers from the given set to this set.
418 void addQualifiers(Qualifiers Q) {
419 // If the other set doesn't have any non-boolean qualifiers, just
420 // bit-or it in.
421 if (!(Q.Mask & ~CVRMask))
422 Mask |= Q.Mask;
423 else {
424 Mask |= (Q.Mask & CVRMask);
425 if (Q.hasAddressSpace())
426 addAddressSpace(Q.getAddressSpace());
427 if (Q.hasObjCGCAttr())
428 addObjCGCAttr(Q.getObjCGCAttr());
429 if (Q.hasObjCLifetime())
430 addObjCLifetime(Q.getObjCLifetime());
431 }
432 }
433
434 /// Remove the qualifiers from the given set from this set.
435 void removeQualifiers(Qualifiers Q) {
436 // If the other set doesn't have any non-boolean qualifiers, just
437 // bit-and the inverse in.
438 if (!(Q.Mask & ~CVRMask))
439 Mask &= ~Q.Mask;
440 else {
441 Mask &= ~(Q.Mask & CVRMask);
442 if (getObjCGCAttr() == Q.getObjCGCAttr())
443 removeObjCGCAttr();
444 if (getObjCLifetime() == Q.getObjCLifetime())
445 removeObjCLifetime();
446 if (getAddressSpace() == Q.getAddressSpace())
447 removeAddressSpace();
448 }
449 }
450
451 /// Add the qualifiers from the given set to this set, given that
452 /// they don't conflict.
453 void addConsistentQualifiers(Qualifiers qs) {
454 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
455 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
;
456 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
457 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
;
458 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
459 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
;
460 Mask |= qs.Mask;
461 }
462
463 /// Returns true if address space A is equal to or a superset of B.
464 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
465 /// overlapping address spaces.
466 /// CL1.1 or CL1.2:
467 /// every address space is a superset of itself.
468 /// CL2.0 adds:
469 /// __generic is a superset of any address space except for __constant.
470 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
471 // Address spaces must match exactly.
472 return A == B ||
473 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
474 // for __constant can be used as __generic.
475 (A == LangAS::opencl_generic && B != LangAS::opencl_constant);
476 }
477
478 /// Returns true if the address space in these qualifiers is equal to or
479 /// a superset of the address space in the argument qualifiers.
480 bool isAddressSpaceSupersetOf(Qualifiers other) const {
481 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
482 }
483
484 /// Determines if these qualifiers compatibly include another set.
485 /// Generally this answers the question of whether an object with the other
486 /// qualifiers can be safely used as an object with these qualifiers.
487 bool compatiblyIncludes(Qualifiers other) const {
488 return isAddressSpaceSupersetOf(other) &&
489 // ObjC GC qualifiers can match, be added, or be removed, but can't
490 // be changed.
491 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
492 !other.hasObjCGCAttr()) &&
493 // ObjC lifetime qualifiers must match exactly.
494 getObjCLifetime() == other.getObjCLifetime() &&
495 // CVR qualifiers may subset.
496 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
497 // U qualifier may superset.
498 (!other.hasUnaligned() || hasUnaligned());
499 }
500
501 /// Determines if these qualifiers compatibly include another set of
502 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
503 ///
504 /// One set of Objective-C lifetime qualifiers compatibly includes the other
505 /// if the lifetime qualifiers match, or if both are non-__weak and the
506 /// including set also contains the 'const' qualifier, or both are non-__weak
507 /// and one is None (which can only happen in non-ARC modes).
508 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
509 if (getObjCLifetime() == other.getObjCLifetime())
510 return true;
511
512 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
513 return false;
514
515 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
516 return true;
517
518 return hasConst();
519 }
520
521 /// Determine whether this set of qualifiers is a strict superset of
522 /// another set of qualifiers, not considering qualifier compatibility.
523 bool isStrictSupersetOf(Qualifiers Other) const;
524
525 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
526 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
527
528 explicit operator bool() const { return hasQualifiers(); }
529
530 Qualifiers &operator+=(Qualifiers R) {
531 addQualifiers(R);
532 return *this;
533 }
534
535 // Union two qualifier sets. If an enumerated qualifier appears
536 // in both sets, use the one from the right.
537 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
538 L += R;
539 return L;
540 }
541
542 Qualifiers &operator-=(Qualifiers R) {
543 removeQualifiers(R);
544 return *this;
545 }
546
547 /// Compute the difference between two qualifier sets.
548 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
549 L -= R;
550 return L;
551 }
552
553 std::string getAsString() const;
554 std::string getAsString(const PrintingPolicy &Policy) const;
555
556 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
557 void print(raw_ostream &OS, const PrintingPolicy &Policy,
558 bool appendSpaceIfNonEmpty = false) const;
559
560 void Profile(llvm::FoldingSetNodeID &ID) const {
561 ID.AddInteger(Mask);
562 }
563
564private:
565 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
566 // |C R V|U|GCAttr|Lifetime|AddressSpace|
567 uint32_t Mask = 0;
568
569 static const uint32_t UMask = 0x8;
570 static const uint32_t UShift = 3;
571 static const uint32_t GCAttrMask = 0x30;
572 static const uint32_t GCAttrShift = 4;
573 static const uint32_t LifetimeMask = 0x1C0;
574 static const uint32_t LifetimeShift = 6;
575 static const uint32_t AddressSpaceMask =
576 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
577 static const uint32_t AddressSpaceShift = 9;
578};
579
580/// A std::pair-like structure for storing a qualified type split
581/// into its local qualifiers and its locally-unqualified type.
582struct SplitQualType {
583 /// The locally-unqualified type.
584 const Type *Ty = nullptr;
585
586 /// The local qualifiers.
587 Qualifiers Quals;
588
589 SplitQualType() = default;
590 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
591
592 SplitQualType getSingleStepDesugaredType() const; // end of this file
593
594 // Make std::tie work.
595 std::pair<const Type *,Qualifiers> asPair() const {
596 return std::pair<const Type *, Qualifiers>(Ty, Quals);
597 }
598
599 friend bool operator==(SplitQualType a, SplitQualType b) {
600 return a.Ty == b.Ty && a.Quals == b.Quals;
601 }
602 friend bool operator!=(SplitQualType a, SplitQualType b) {
603 return a.Ty != b.Ty || a.Quals != b.Quals;
604 }
605};
606
607/// The kind of type we are substituting Objective-C type arguments into.
608///
609/// The kind of substitution affects the replacement of type parameters when
610/// no concrete type information is provided, e.g., when dealing with an
611/// unspecialized type.
612enum class ObjCSubstitutionContext {
613 /// An ordinary type.
614 Ordinary,
615
616 /// The result type of a method or function.
617 Result,
618
619 /// The parameter type of a method or function.
620 Parameter,
621
622 /// The type of a property.
623 Property,
624
625 /// The superclass of a type.
626 Superclass,
627};
628
629/// A (possibly-)qualified type.
630///
631/// For efficiency, we don't store CV-qualified types as nodes on their
632/// own: instead each reference to a type stores the qualifiers. This
633/// greatly reduces the number of nodes we need to allocate for types (for
634/// example we only need one for 'int', 'const int', 'volatile int',
635/// 'const volatile int', etc).
636///
637/// As an added efficiency bonus, instead of making this a pair, we
638/// just store the two bits we care about in the low bits of the
639/// pointer. To handle the packing/unpacking, we make QualType be a
640/// simple wrapper class that acts like a smart pointer. A third bit
641/// indicates whether there are extended qualifiers present, in which
642/// case the pointer points to a special structure.
643class QualType {
644 friend class QualifierCollector;
645
646 // Thankfully, these are efficiently composable.
647 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
648 Qualifiers::FastWidth> Value;
649
650 const ExtQuals *getExtQualsUnsafe() const {
651 return Value.getPointer().get<const ExtQuals*>();
652 }
653
654 const Type *getTypePtrUnsafe() const {
655 return Value.getPointer().get<const Type*>();
656 }
657
658 const ExtQualsTypeCommonBase *getCommonPtr() const {
659 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 659, __PRETTY_FUNCTION__))
;
660 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
661 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
662 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
663 }
664
665public:
666 QualType() = default;
667 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
668 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
669
670 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
671 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
672
673 /// Retrieves a pointer to the underlying (unqualified) type.
674 ///
675 /// This function requires that the type not be NULL. If the type might be
676 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
677 const Type *getTypePtr() const;
678
679 const Type *getTypePtrOrNull() const;
680
681 /// Retrieves a pointer to the name of the base type.
682 const IdentifierInfo *getBaseTypeIdentifier() const;
683
684 /// Divides a QualType into its unqualified type and a set of local
685 /// qualifiers.
686 SplitQualType split() const;
687
688 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
689
690 static QualType getFromOpaquePtr(const void *Ptr) {
691 QualType T;
692 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
693 return T;
694 }
695
696 const Type &operator*() const {
697 return *getTypePtr();
698 }
699
700 const Type *operator->() const {
701 return getTypePtr();
702 }
703
704 bool isCanonical() const;
705 bool isCanonicalAsParam() const;
706
707 /// Return true if this QualType doesn't point to a type yet.
708 bool isNull() const {
709 return Value.getPointer().isNull();
9
Calling 'PointerUnion::isNull'
12
Returning from 'PointerUnion::isNull'
13
Returning zero, which participates in a condition later
710 }
711
712 /// Determine whether this particular QualType instance has the
713 /// "const" qualifier set, without looking through typedefs that may have
714 /// added "const" at a different level.
715 bool isLocalConstQualified() const {
716 return (getLocalFastQualifiers() & Qualifiers::Const);
717 }
718
719 /// Determine whether this type is const-qualified.
720 bool isConstQualified() const;
721
722 /// Determine whether this particular QualType instance has the
723 /// "restrict" qualifier set, without looking through typedefs that may have
724 /// added "restrict" at a different level.
725 bool isLocalRestrictQualified() const {
726 return (getLocalFastQualifiers() & Qualifiers::Restrict);
727 }
728
729 /// Determine whether this type is restrict-qualified.
730 bool isRestrictQualified() const;
731
732 /// Determine whether this particular QualType instance has the
733 /// "volatile" qualifier set, without looking through typedefs that may have
734 /// added "volatile" at a different level.
735 bool isLocalVolatileQualified() const {
736 return (getLocalFastQualifiers() & Qualifiers::Volatile);
737 }
738
739 /// Determine whether this type is volatile-qualified.
740 bool isVolatileQualified() const;
741
742 /// Determine whether this particular QualType instance has any
743 /// qualifiers, without looking through any typedefs that might add
744 /// qualifiers at a different level.
745 bool hasLocalQualifiers() const {
746 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
747 }
748
749 /// Determine whether this type has any qualifiers.
750 bool hasQualifiers() const;
751
752 /// Determine whether this particular QualType instance has any
753 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
754 /// instance.
755 bool hasLocalNonFastQualifiers() const {
756 return Value.getPointer().is<const ExtQuals*>();
757 }
758
759 /// Retrieve the set of qualifiers local to this particular QualType
760 /// instance, not including any qualifiers acquired through typedefs or
761 /// other sugar.
762 Qualifiers getLocalQualifiers() const;
763
764 /// Retrieve the set of qualifiers applied to this type.
765 Qualifiers getQualifiers() const;
766
767 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
768 /// local to this particular QualType instance, not including any qualifiers
769 /// acquired through typedefs or other sugar.
770 unsigned getLocalCVRQualifiers() const {
771 return getLocalFastQualifiers();
772 }
773
774 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
775 /// applied to this type.
776 unsigned getCVRQualifiers() const;
777
778 bool isConstant(const ASTContext& Ctx) const {
779 return QualType::isConstant(*this, Ctx);
780 }
781
782 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
783 bool isPODType(const ASTContext &Context) const;
784
785 /// Return true if this is a POD type according to the rules of the C++98
786 /// standard, regardless of the current compilation's language.
787 bool isCXX98PODType(const ASTContext &Context) const;
788
789 /// Return true if this is a POD type according to the more relaxed rules
790 /// of the C++11 standard, regardless of the current compilation's language.
791 /// (C++0x [basic.types]p9). Note that, unlike
792 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
793 bool isCXX11PODType(const ASTContext &Context) const;
794
795 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
796 bool isTrivialType(const ASTContext &Context) const;
797
798 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
799 bool isTriviallyCopyableType(const ASTContext &Context) const;
800
801
802 /// Returns true if it is a class and it might be dynamic.
803 bool mayBeDynamicClass() const;
804
805 /// Returns true if it is not a class or if the class might not be dynamic.
806 bool mayBeNotDynamicClass() const;
807
808 // Don't promise in the API that anything besides 'const' can be
809 // easily added.
810
811 /// Add the `const` type qualifier to this QualType.
812 void addConst() {
813 addFastQualifiers(Qualifiers::Const);
814 }
815 QualType withConst() const {
816 return withFastQualifiers(Qualifiers::Const);
817 }
818
819 /// Add the `volatile` type qualifier to this QualType.
820 void addVolatile() {
821 addFastQualifiers(Qualifiers::Volatile);
822 }
823 QualType withVolatile() const {
824 return withFastQualifiers(Qualifiers::Volatile);
825 }
826
827 /// Add the `restrict` qualifier to this QualType.
828 void addRestrict() {
829 addFastQualifiers(Qualifiers::Restrict);
830 }
831 QualType withRestrict() const {
832 return withFastQualifiers(Qualifiers::Restrict);
833 }
834
835 QualType withCVRQualifiers(unsigned CVR) const {
836 return withFastQualifiers(CVR);
837 }
838
839 void addFastQualifiers(unsigned TQs) {
840 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
841 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
;
842 Value.setInt(Value.getInt() | TQs);
843 }
844
845 void removeLocalConst();
846 void removeLocalVolatile();
847 void removeLocalRestrict();
848 void removeLocalCVRQualifiers(unsigned Mask);
849
850 void removeLocalFastQualifiers() { Value.setInt(0); }
851 void removeLocalFastQualifiers(unsigned Mask) {
852 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 852, __PRETTY_FUNCTION__))
;
853 Value.setInt(Value.getInt() & ~Mask);
854 }
855
856 // Creates a type with the given qualifiers in addition to any
857 // qualifiers already on this type.
858 QualType withFastQualifiers(unsigned TQs) const {
859 QualType T = *this;
860 T.addFastQualifiers(TQs);
861 return T;
862 }
863
864 // Creates a type with exactly the given fast qualifiers, removing
865 // any existing fast qualifiers.
866 QualType withExactLocalFastQualifiers(unsigned TQs) const {
867 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
868 }
869
870 // Removes fast qualifiers, but leaves any extended qualifiers in place.
871 QualType withoutLocalFastQualifiers() const {
872 QualType T = *this;
873 T.removeLocalFastQualifiers();
874 return T;
875 }
876
877 QualType getCanonicalType() const;
878
879 /// Return this type with all of the instance-specific qualifiers
880 /// removed, but without removing any qualifiers that may have been applied
881 /// through typedefs.
882 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
883
884 /// Retrieve the unqualified variant of the given type,
885 /// removing as little sugar as possible.
886 ///
887 /// This routine looks through various kinds of sugar to find the
888 /// least-desugared type that is unqualified. For example, given:
889 ///
890 /// \code
891 /// typedef int Integer;
892 /// typedef const Integer CInteger;
893 /// typedef CInteger DifferenceType;
894 /// \endcode
895 ///
896 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
897 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
898 ///
899 /// The resulting type might still be qualified if it's sugar for an array
900 /// type. To strip qualifiers even from within a sugared array type, use
901 /// ASTContext::getUnqualifiedArrayType.
902 inline QualType getUnqualifiedType() const;
903
904 /// Retrieve the unqualified variant of the given type, removing as little
905 /// sugar as possible.
906 ///
907 /// Like getUnqualifiedType(), but also returns the set of
908 /// qualifiers that were built up.
909 ///
910 /// The resulting type might still be qualified if it's sugar for an array
911 /// type. To strip qualifiers even from within a sugared array type, use
912 /// ASTContext::getUnqualifiedArrayType.
913 inline SplitQualType getSplitUnqualifiedType() const;
914
915 /// Determine whether this type is more qualified than the other
916 /// given type, requiring exact equality for non-CVR qualifiers.
917 bool isMoreQualifiedThan(QualType Other) const;
918
919 /// Determine whether this type is at least as qualified as the other
920 /// given type, requiring exact equality for non-CVR qualifiers.
921 bool isAtLeastAsQualifiedAs(QualType Other) const;
922
923 QualType getNonReferenceType() const;
924
925 /// Determine the type of a (typically non-lvalue) expression with the
926 /// specified result type.
927 ///
928 /// This routine should be used for expressions for which the return type is
929 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
930 /// an lvalue. It removes a top-level reference (since there are no
931 /// expressions of reference type) and deletes top-level cvr-qualifiers
932 /// from non-class types (in C++) or all types (in C).
933 QualType getNonLValueExprType(const ASTContext &Context) const;
934
935 /// Return the specified type with any "sugar" removed from
936 /// the type. This takes off typedefs, typeof's etc. If the outer level of
937 /// the type is already concrete, it returns it unmodified. This is similar
938 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
939 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
940 /// concrete.
941 ///
942 /// Qualifiers are left in place.
943 QualType getDesugaredType(const ASTContext &Context) const {
944 return getDesugaredType(*this, Context);
945 }
946
947 SplitQualType getSplitDesugaredType() const {
948 return getSplitDesugaredType(*this);
949 }
950
951 /// Return the specified type with one level of "sugar" removed from
952 /// the type.
953 ///
954 /// This routine takes off the first typedef, typeof, etc. If the outer level
955 /// of the type is already concrete, it returns it unmodified.
956 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
957 return getSingleStepDesugaredTypeImpl(*this, Context);
958 }
959
960 /// Returns the specified type after dropping any
961 /// outer-level parentheses.
962 QualType IgnoreParens() const {
963 if (isa<ParenType>(*this))
964 return QualType::IgnoreParens(*this);
965 return *this;
966 }
967
968 /// Indicate whether the specified types and qualifiers are identical.
969 friend bool operator==(const QualType &LHS, const QualType &RHS) {
970 return LHS.Value == RHS.Value;
971 }
972 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
973 return LHS.Value != RHS.Value;
974 }
975 friend bool operator<(const QualType &LHS, const QualType &RHS) {
976 return LHS.Value < RHS.Value;
977 }
978
979 static std::string getAsString(SplitQualType split,
980 const PrintingPolicy &Policy) {
981 return getAsString(split.Ty, split.Quals, Policy);
982 }
983 static std::string getAsString(const Type *ty, Qualifiers qs,
984 const PrintingPolicy &Policy);
985
986 std::string getAsString() const;
987 std::string getAsString(const PrintingPolicy &Policy) const;
988
989 void print(raw_ostream &OS, const PrintingPolicy &Policy,
990 const Twine &PlaceHolder = Twine(),
991 unsigned Indentation = 0) const;
992
993 static void print(SplitQualType split, raw_ostream &OS,
994 const PrintingPolicy &policy, const Twine &PlaceHolder,
995 unsigned Indentation = 0) {
996 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
997 }
998
999 static void print(const Type *ty, Qualifiers qs,
1000 raw_ostream &OS, const PrintingPolicy &policy,
1001 const Twine &PlaceHolder,
1002 unsigned Indentation = 0);
1003
1004 void getAsStringInternal(std::string &Str,
1005 const PrintingPolicy &Policy) const;
1006
1007 static void getAsStringInternal(SplitQualType split, std::string &out,
1008 const PrintingPolicy &policy) {
1009 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1010 }
1011
1012 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1013 std::string &out,
1014 const PrintingPolicy &policy);
1015
1016 class StreamedQualTypeHelper {
1017 const QualType &T;
1018 const PrintingPolicy &Policy;
1019 const Twine &PlaceHolder;
1020 unsigned Indentation;
1021
1022 public:
1023 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1024 const Twine &PlaceHolder, unsigned Indentation)
1025 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1026 Indentation(Indentation) {}
1027
1028 friend raw_ostream &operator<<(raw_ostream &OS,
1029 const StreamedQualTypeHelper &SQT) {
1030 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1031 return OS;
1032 }
1033 };
1034
1035 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1036 const Twine &PlaceHolder = Twine(),
1037 unsigned Indentation = 0) const {
1038 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1039 }
1040
1041 void dump(const char *s) const;
1042 void dump() const;
1043 void dump(llvm::raw_ostream &OS) const;
1044
1045 void Profile(llvm::FoldingSetNodeID &ID) const {
1046 ID.AddPointer(getAsOpaquePtr());
1047 }
1048
1049 /// Return the address space of this type.
1050 inline LangAS getAddressSpace() const;
1051
1052 /// Returns gc attribute of this type.
1053 inline Qualifiers::GC getObjCGCAttr() const;
1054
1055 /// true when Type is objc's weak.
1056 bool isObjCGCWeak() const {
1057 return getObjCGCAttr() == Qualifiers::Weak;
1058 }
1059
1060 /// true when Type is objc's strong.
1061 bool isObjCGCStrong() const {
1062 return getObjCGCAttr() == Qualifiers::Strong;
1063 }
1064
1065 /// Returns lifetime attribute of this type.
1066 Qualifiers::ObjCLifetime getObjCLifetime() const {
1067 return getQualifiers().getObjCLifetime();
1068 }
1069
1070 bool hasNonTrivialObjCLifetime() const {
1071 return getQualifiers().hasNonTrivialObjCLifetime();
1072 }
1073
1074 bool hasStrongOrWeakObjCLifetime() const {
1075 return getQualifiers().hasStrongOrWeakObjCLifetime();
1076 }
1077
1078 // true when Type is objc's weak and weak is enabled but ARC isn't.
1079 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1080
1081 enum PrimitiveDefaultInitializeKind {
1082 /// The type does not fall into any of the following categories. Note that
1083 /// this case is zero-valued so that values of this enum can be used as a
1084 /// boolean condition for non-triviality.
1085 PDIK_Trivial,
1086
1087 /// The type is an Objective-C retainable pointer type that is qualified
1088 /// with the ARC __strong qualifier.
1089 PDIK_ARCStrong,
1090
1091 /// The type is an Objective-C retainable pointer type that is qualified
1092 /// with the ARC __weak qualifier.
1093 PDIK_ARCWeak,
1094
1095 /// The type is a struct containing a field whose type is not PCK_Trivial.
1096 PDIK_Struct
1097 };
1098
1099 /// Functions to query basic properties of non-trivial C struct types.
1100
1101 /// Check if this is a non-trivial type that would cause a C struct
1102 /// transitively containing this type to be non-trivial to default initialize
1103 /// and return the kind.
1104 PrimitiveDefaultInitializeKind
1105 isNonTrivialToPrimitiveDefaultInitialize() const;
1106
1107 enum PrimitiveCopyKind {
1108 /// The type does not fall into any of the following categories. Note that
1109 /// this case is zero-valued so that values of this enum can be used as a
1110 /// boolean condition for non-triviality.
1111 PCK_Trivial,
1112
1113 /// The type would be trivial except that it is volatile-qualified. Types
1114 /// that fall into one of the other non-trivial cases may additionally be
1115 /// volatile-qualified.
1116 PCK_VolatileTrivial,
1117
1118 /// The type is an Objective-C retainable pointer type that is qualified
1119 /// with the ARC __strong qualifier.
1120 PCK_ARCStrong,
1121
1122 /// The type is an Objective-C retainable pointer type that is qualified
1123 /// with the ARC __weak qualifier.
1124 PCK_ARCWeak,
1125
1126 /// The type is a struct containing a field whose type is neither
1127 /// PCK_Trivial nor PCK_VolatileTrivial.
1128 /// Note that a C++ struct type does not necessarily match this; C++ copying
1129 /// semantics are too complex to express here, in part because they depend
1130 /// on the exact constructor or assignment operator that is chosen by
1131 /// overload resolution to do the copy.
1132 PCK_Struct
1133 };
1134
1135 /// Check if this is a non-trivial type that would cause a C struct
1136 /// transitively containing this type to be non-trivial to copy and return the
1137 /// kind.
1138 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1139
1140 /// Check if this is a non-trivial type that would cause a C struct
1141 /// transitively containing this type to be non-trivial to destructively
1142 /// move and return the kind. Destructive move in this context is a C++-style
1143 /// move in which the source object is placed in a valid but unspecified state
1144 /// after it is moved, as opposed to a truly destructive move in which the
1145 /// source object is placed in an uninitialized state.
1146 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1147
1148 enum DestructionKind {
1149 DK_none,
1150 DK_cxx_destructor,
1151 DK_objc_strong_lifetime,
1152 DK_objc_weak_lifetime,
1153 DK_nontrivial_c_struct
1154 };
1155
1156 /// Returns a nonzero value if objects of this type require
1157 /// non-trivial work to clean up after. Non-zero because it's
1158 /// conceivable that qualifiers (objc_gc(weak)?) could make
1159 /// something require destruction.
1160 DestructionKind isDestructedType() const {
1161 return isDestructedTypeImpl(*this);
1162 }
1163
1164 /// Check if this is or contains a C union that is non-trivial to
1165 /// default-initialize, which is a union that has a member that is non-trivial
1166 /// to default-initialize. If this returns true,
1167 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1168 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1169
1170 /// Check if this is or contains a C union that is non-trivial to destruct,
1171 /// which is a union that has a member that is non-trivial to destruct. If
1172 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1173 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1174
1175 /// Check if this is or contains a C union that is non-trivial to copy, which
1176 /// is a union that has a member that is non-trivial to copy. If this returns
1177 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1178 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1179
1180 /// Determine whether expressions of the given type are forbidden
1181 /// from being lvalues in C.
1182 ///
1183 /// The expression types that are forbidden to be lvalues are:
1184 /// - 'void', but not qualified void
1185 /// - function types
1186 ///
1187 /// The exact rule here is C99 6.3.2.1:
1188 /// An lvalue is an expression with an object type or an incomplete
1189 /// type other than void.
1190 bool isCForbiddenLValueType() const;
1191
1192 /// Substitute type arguments for the Objective-C type parameters used in the
1193 /// subject type.
1194 ///
1195 /// \param ctx ASTContext in which the type exists.
1196 ///
1197 /// \param typeArgs The type arguments that will be substituted for the
1198 /// Objective-C type parameters in the subject type, which are generally
1199 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1200 /// parameters will be replaced with their bounds or id/Class, as appropriate
1201 /// for the context.
1202 ///
1203 /// \param context The context in which the subject type was written.
1204 ///
1205 /// \returns the resulting type.
1206 QualType substObjCTypeArgs(ASTContext &ctx,
1207 ArrayRef<QualType> typeArgs,
1208 ObjCSubstitutionContext context) const;
1209
1210 /// Substitute type arguments from an object type for the Objective-C type
1211 /// parameters used in the subject type.
1212 ///
1213 /// This operation combines the computation of type arguments for
1214 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1215 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1216 /// callers that need to perform a single substitution in isolation.
1217 ///
1218 /// \param objectType The type of the object whose member type we're
1219 /// substituting into. For example, this might be the receiver of a message
1220 /// or the base of a property access.
1221 ///
1222 /// \param dc The declaration context from which the subject type was
1223 /// retrieved, which indicates (for example) which type parameters should
1224 /// be substituted.
1225 ///
1226 /// \param context The context in which the subject type was written.
1227 ///
1228 /// \returns the subject type after replacing all of the Objective-C type
1229 /// parameters with their corresponding arguments.
1230 QualType substObjCMemberType(QualType objectType,
1231 const DeclContext *dc,
1232 ObjCSubstitutionContext context) const;
1233
1234 /// Strip Objective-C "__kindof" types from the given type.
1235 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1236
1237 /// Remove all qualifiers including _Atomic.
1238 QualType getAtomicUnqualifiedType() const;
1239
1240private:
1241 // These methods are implemented in a separate translation unit;
1242 // "static"-ize them to avoid creating temporary QualTypes in the
1243 // caller.
1244 static bool isConstant(QualType T, const ASTContext& Ctx);
1245 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1246 static SplitQualType getSplitDesugaredType(QualType T);
1247 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1248 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1249 const ASTContext &C);
1250 static QualType IgnoreParens(QualType T);
1251 static DestructionKind isDestructedTypeImpl(QualType type);
1252
1253 /// Check if \param RD is or contains a non-trivial C union.
1254 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1255 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1256 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1257};
1258
1259} // namespace clang
1260
1261namespace llvm {
1262
1263/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1264/// to a specific Type class.
1265template<> struct simplify_type< ::clang::QualType> {
1266 using SimpleType = const ::clang::Type *;
1267
1268 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1269 return Val.getTypePtr();
1270 }
1271};
1272
1273// Teach SmallPtrSet that QualType is "basically a pointer".
1274template<>
1275struct PointerLikeTypeTraits<clang::QualType> {
1276 static inline void *getAsVoidPointer(clang::QualType P) {
1277 return P.getAsOpaquePtr();
1278 }
1279
1280 static inline clang::QualType getFromVoidPointer(void *P) {
1281 return clang::QualType::getFromOpaquePtr(P);
1282 }
1283
1284 // Various qualifiers go in low bits.
1285 enum { NumLowBitsAvailable = 0 };
1286};
1287
1288} // namespace llvm
1289
1290namespace clang {
1291
1292/// Base class that is common to both the \c ExtQuals and \c Type
1293/// classes, which allows \c QualType to access the common fields between the
1294/// two.
1295class ExtQualsTypeCommonBase {
1296 friend class ExtQuals;
1297 friend class QualType;
1298 friend class Type;
1299
1300 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1301 /// a self-referential pointer (for \c Type).
1302 ///
1303 /// This pointer allows an efficient mapping from a QualType to its
1304 /// underlying type pointer.
1305 const Type *const BaseType;
1306
1307 /// The canonical type of this type. A QualType.
1308 QualType CanonicalType;
1309
1310 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1311 : BaseType(baseType), CanonicalType(canon) {}
1312};
1313
1314/// We can encode up to four bits in the low bits of a
1315/// type pointer, but there are many more type qualifiers that we want
1316/// to be able to apply to an arbitrary type. Therefore we have this
1317/// struct, intended to be heap-allocated and used by QualType to
1318/// store qualifiers.
1319///
1320/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1321/// in three low bits on the QualType pointer; a fourth bit records whether
1322/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1323/// Objective-C GC attributes) are much more rare.
1324class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1325 // NOTE: changing the fast qualifiers should be straightforward as
1326 // long as you don't make 'const' non-fast.
1327 // 1. Qualifiers:
1328 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1329 // Fast qualifiers must occupy the low-order bits.
1330 // b) Update Qualifiers::FastWidth and FastMask.
1331 // 2. QualType:
1332 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1333 // b) Update remove{Volatile,Restrict}, defined near the end of
1334 // this header.
1335 // 3. ASTContext:
1336 // a) Update get{Volatile,Restrict}Type.
1337
1338 /// The immutable set of qualifiers applied by this node. Always contains
1339 /// extended qualifiers.
1340 Qualifiers Quals;
1341
1342 ExtQuals *this_() { return this; }
1343
1344public:
1345 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1346 : ExtQualsTypeCommonBase(baseType,
1347 canon.isNull() ? QualType(this_(), 0) : canon),
1348 Quals(quals) {
1349 assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
1350 && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
;
1351 assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
1352 && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
;
1353 }
1354
1355 Qualifiers getQualifiers() const { return Quals; }
1356
1357 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1358 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1359
1360 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1361 Qualifiers::ObjCLifetime getObjCLifetime() const {
1362 return Quals.getObjCLifetime();
1363 }
1364
1365 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1366 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1367
1368 const Type *getBaseType() const { return BaseType; }
1369
1370public:
1371 void Profile(llvm::FoldingSetNodeID &ID) const {
1372 Profile(ID, getBaseType(), Quals);
1373 }
1374
1375 static void Profile(llvm::FoldingSetNodeID &ID,
1376 const Type *BaseType,
1377 Qualifiers Quals) {
1378 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1378, __PRETTY_FUNCTION__))
;
1379 ID.AddPointer(BaseType);
1380 Quals.Profile(ID);
1381 }
1382};
1383
1384/// The kind of C++11 ref-qualifier associated with a function type.
1385/// This determines whether a member function's "this" object can be an
1386/// lvalue, rvalue, or neither.
1387enum RefQualifierKind {
1388 /// No ref-qualifier was provided.
1389 RQ_None = 0,
1390
1391 /// An lvalue ref-qualifier was provided (\c &).
1392 RQ_LValue,
1393
1394 /// An rvalue ref-qualifier was provided (\c &&).
1395 RQ_RValue
1396};
1397
1398/// Which keyword(s) were used to create an AutoType.
1399enum class AutoTypeKeyword {
1400 /// auto
1401 Auto,
1402
1403 /// decltype(auto)
1404 DecltypeAuto,
1405
1406 /// __auto_type (GNU extension)
1407 GNUAutoType
1408};
1409
1410/// The base class of the type hierarchy.
1411///
1412/// A central concept with types is that each type always has a canonical
1413/// type. A canonical type is the type with any typedef names stripped out
1414/// of it or the types it references. For example, consider:
1415///
1416/// typedef int foo;
1417/// typedef foo* bar;
1418/// 'int *' 'foo *' 'bar'
1419///
1420/// There will be a Type object created for 'int'. Since int is canonical, its
1421/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1422/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1423/// there is a PointerType that represents 'int*', which, like 'int', is
1424/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1425/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1426/// is also 'int*'.
1427///
1428/// Non-canonical types are useful for emitting diagnostics, without losing
1429/// information about typedefs being used. Canonical types are useful for type
1430/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1431/// about whether something has a particular form (e.g. is a function type),
1432/// because they implicitly, recursively, strip all typedefs out of a type.
1433///
1434/// Types, once created, are immutable.
1435///
1436class alignas(8) Type : public ExtQualsTypeCommonBase {
1437public:
1438 enum TypeClass {
1439#define TYPE(Class, Base) Class,
1440#define LAST_TYPE(Class) TypeLast = Class
1441#define ABSTRACT_TYPE(Class, Base)
1442#include "clang/AST/TypeNodes.inc"
1443 };
1444
1445private:
1446 /// Bitfields required by the Type class.
1447 class TypeBitfields {
1448 friend class Type;
1449 template <class T> friend class TypePropertyCache;
1450
1451 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1452 unsigned TC : 8;
1453
1454 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1455 unsigned Dependent : 1;
1456
1457 /// Whether this type somehow involves a template parameter, even
1458 /// if the resolution of the type does not depend on a template parameter.
1459 unsigned InstantiationDependent : 1;
1460
1461 /// Whether this type is a variably-modified type (C99 6.7.5).
1462 unsigned VariablyModified : 1;
1463
1464 /// Whether this type contains an unexpanded parameter pack
1465 /// (for C++11 variadic templates).
1466 unsigned ContainsUnexpandedParameterPack : 1;
1467
1468 /// True if the cache (i.e. the bitfields here starting with
1469 /// 'Cache') is valid.
1470 mutable unsigned CacheValid : 1;
1471
1472 /// Linkage of this type.
1473 mutable unsigned CachedLinkage : 3;
1474
1475 /// Whether this type involves and local or unnamed types.
1476 mutable unsigned CachedLocalOrUnnamed : 1;
1477
1478 /// Whether this type comes from an AST file.
1479 mutable unsigned FromAST : 1;
1480
1481 bool isCacheValid() const {
1482 return CacheValid;
1483 }
1484
1485 Linkage getLinkage() const {
1486 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1486, __PRETTY_FUNCTION__))
;
1487 return static_cast<Linkage>(CachedLinkage);
1488 }
1489
1490 bool hasLocalOrUnnamedType() const {
1491 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1491, __PRETTY_FUNCTION__))
;
1492 return CachedLocalOrUnnamed;
1493 }
1494 };
1495 enum { NumTypeBits = 18 };
1496
1497protected:
1498 // These classes allow subclasses to somewhat cleanly pack bitfields
1499 // into Type.
1500
1501 class ArrayTypeBitfields {
1502 friend class ArrayType;
1503
1504 unsigned : NumTypeBits;
1505
1506 /// CVR qualifiers from declarations like
1507 /// 'int X[static restrict 4]'. For function parameters only.
1508 unsigned IndexTypeQuals : 3;
1509
1510 /// Storage class qualifiers from declarations like
1511 /// 'int X[static restrict 4]'. For function parameters only.
1512 /// Actually an ArrayType::ArraySizeModifier.
1513 unsigned SizeModifier : 3;
1514 };
1515
1516 class BuiltinTypeBitfields {
1517 friend class BuiltinType;
1518
1519 unsigned : NumTypeBits;
1520
1521 /// The kind (BuiltinType::Kind) of builtin type this is.
1522 unsigned Kind : 8;
1523 };
1524
1525 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1526 /// Only common bits are stored here. Additional uncommon bits are stored
1527 /// in a trailing object after FunctionProtoType.
1528 class FunctionTypeBitfields {
1529 friend class FunctionProtoType;
1530 friend class FunctionType;
1531
1532 unsigned : NumTypeBits;
1533
1534 /// Extra information which affects how the function is called, like
1535 /// regparm and the calling convention.
1536 unsigned ExtInfo : 12;
1537
1538 /// The ref-qualifier associated with a \c FunctionProtoType.
1539 ///
1540 /// This is a value of type \c RefQualifierKind.
1541 unsigned RefQualifier : 2;
1542
1543 /// Used only by FunctionProtoType, put here to pack with the
1544 /// other bitfields.
1545 /// The qualifiers are part of FunctionProtoType because...
1546 ///
1547 /// C++ 8.3.5p4: The return type, the parameter type list and the
1548 /// cv-qualifier-seq, [...], are part of the function type.
1549 unsigned FastTypeQuals : Qualifiers::FastWidth;
1550 /// Whether this function has extended Qualifiers.
1551 unsigned HasExtQuals : 1;
1552
1553 /// The number of parameters this function has, not counting '...'.
1554 /// According to [implimits] 8 bits should be enough here but this is
1555 /// somewhat easy to exceed with metaprogramming and so we would like to
1556 /// keep NumParams as wide as reasonably possible.
1557 unsigned NumParams : 16;
1558
1559 /// The type of exception specification this function has.
1560 unsigned ExceptionSpecType : 4;
1561
1562 /// Whether this function has extended parameter information.
1563 unsigned HasExtParameterInfos : 1;
1564
1565 /// Whether the function is variadic.
1566 unsigned Variadic : 1;
1567
1568 /// Whether this function has a trailing return type.
1569 unsigned HasTrailingReturn : 1;
1570 };
1571
1572 class ObjCObjectTypeBitfields {
1573 friend class ObjCObjectType;
1574
1575 unsigned : NumTypeBits;
1576
1577 /// The number of type arguments stored directly on this object type.
1578 unsigned NumTypeArgs : 7;
1579
1580 /// The number of protocols stored directly on this object type.
1581 unsigned NumProtocols : 6;
1582
1583 /// Whether this is a "kindof" type.
1584 unsigned IsKindOf : 1;
1585 };
1586
1587 class ReferenceTypeBitfields {
1588 friend class ReferenceType;
1589
1590 unsigned : NumTypeBits;
1591
1592 /// True if the type was originally spelled with an lvalue sigil.
1593 /// This is never true of rvalue references but can also be false
1594 /// on lvalue references because of C++0x [dcl.typedef]p9,
1595 /// as follows:
1596 ///
1597 /// typedef int &ref; // lvalue, spelled lvalue
1598 /// typedef int &&rvref; // rvalue
1599 /// ref &a; // lvalue, inner ref, spelled lvalue
1600 /// ref &&a; // lvalue, inner ref
1601 /// rvref &a; // lvalue, inner ref, spelled lvalue
1602 /// rvref &&a; // rvalue, inner ref
1603 unsigned SpelledAsLValue : 1;
1604
1605 /// True if the inner type is a reference type. This only happens
1606 /// in non-canonical forms.
1607 unsigned InnerRef : 1;
1608 };
1609
1610 class TypeWithKeywordBitfields {
1611 friend class TypeWithKeyword;
1612
1613 unsigned : NumTypeBits;
1614
1615 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1616 unsigned Keyword : 8;
1617 };
1618
1619 enum { NumTypeWithKeywordBits = 8 };
1620
1621 class ElaboratedTypeBitfields {
1622 friend class ElaboratedType;
1623
1624 unsigned : NumTypeBits;
1625 unsigned : NumTypeWithKeywordBits;
1626
1627 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1628 unsigned HasOwnedTagDecl : 1;
1629 };
1630
1631 class VectorTypeBitfields {
1632 friend class VectorType;
1633 friend class DependentVectorType;
1634
1635 unsigned : NumTypeBits;
1636
1637 /// The kind of vector, either a generic vector type or some
1638 /// target-specific vector type such as for AltiVec or Neon.
1639 unsigned VecKind : 3;
1640
1641 /// The number of elements in the vector.
1642 unsigned NumElements : 29 - NumTypeBits;
1643
1644 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1645 };
1646
1647 class AttributedTypeBitfields {
1648 friend class AttributedType;
1649
1650 unsigned : NumTypeBits;
1651
1652 /// An AttributedType::Kind
1653 unsigned AttrKind : 32 - NumTypeBits;
1654 };
1655
1656 class AutoTypeBitfields {
1657 friend class AutoType;
1658
1659 unsigned : NumTypeBits;
1660
1661 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1662 /// or '__auto_type'? AutoTypeKeyword value.
1663 unsigned Keyword : 2;
1664 };
1665
1666 class SubstTemplateTypeParmPackTypeBitfields {
1667 friend class SubstTemplateTypeParmPackType;
1668
1669 unsigned : NumTypeBits;
1670
1671 /// The number of template arguments in \c Arguments, which is
1672 /// expected to be able to hold at least 1024 according to [implimits].
1673 /// However as this limit is somewhat easy to hit with template
1674 /// metaprogramming we'd prefer to keep it as large as possible.
1675 /// At the moment it has been left as a non-bitfield since this type
1676 /// safely fits in 64 bits as an unsigned, so there is no reason to
1677 /// introduce the performance impact of a bitfield.
1678 unsigned NumArgs;
1679 };
1680
1681 class TemplateSpecializationTypeBitfields {
1682 friend class TemplateSpecializationType;
1683
1684 unsigned : NumTypeBits;
1685
1686 /// Whether this template specialization type is a substituted type alias.
1687 unsigned TypeAlias : 1;
1688
1689 /// The number of template arguments named in this class template
1690 /// specialization, which is expected to be able to hold at least 1024
1691 /// according to [implimits]. However, as this limit is somewhat easy to
1692 /// hit with template metaprogramming we'd prefer to keep it as large
1693 /// as possible. At the moment it has been left as a non-bitfield since
1694 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1695 /// to introduce the performance impact of a bitfield.
1696 unsigned NumArgs;
1697 };
1698
1699 class DependentTemplateSpecializationTypeBitfields {
1700 friend class DependentTemplateSpecializationType;
1701
1702 unsigned : NumTypeBits;
1703 unsigned : NumTypeWithKeywordBits;
1704
1705 /// The number of template arguments named in this class template
1706 /// specialization, which is expected to be able to hold at least 1024
1707 /// according to [implimits]. However, as this limit is somewhat easy to
1708 /// hit with template metaprogramming we'd prefer to keep it as large
1709 /// as possible. At the moment it has been left as a non-bitfield since
1710 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1711 /// to introduce the performance impact of a bitfield.
1712 unsigned NumArgs;
1713 };
1714
1715 class PackExpansionTypeBitfields {
1716 friend class PackExpansionType;
1717
1718 unsigned : NumTypeBits;
1719
1720 /// The number of expansions that this pack expansion will
1721 /// generate when substituted (+1), which is expected to be able to
1722 /// hold at least 1024 according to [implimits]. However, as this limit
1723 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1724 /// keep it as large as possible. At the moment it has been left as a
1725 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1726 /// there is no reason to introduce the performance impact of a bitfield.
1727 ///
1728 /// This field will only have a non-zero value when some of the parameter
1729 /// packs that occur within the pattern have been substituted but others
1730 /// have not.
1731 unsigned NumExpansions;
1732 };
1733
1734 union {
1735 TypeBitfields TypeBits;
1736 ArrayTypeBitfields ArrayTypeBits;
1737 AttributedTypeBitfields AttributedTypeBits;
1738 AutoTypeBitfields AutoTypeBits;
1739 BuiltinTypeBitfields BuiltinTypeBits;
1740 FunctionTypeBitfields FunctionTypeBits;
1741 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1742 ReferenceTypeBitfields ReferenceTypeBits;
1743 TypeWithKeywordBitfields TypeWithKeywordBits;
1744 ElaboratedTypeBitfields ElaboratedTypeBits;
1745 VectorTypeBitfields VectorTypeBits;
1746 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1747 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1748 DependentTemplateSpecializationTypeBitfields
1749 DependentTemplateSpecializationTypeBits;
1750 PackExpansionTypeBitfields PackExpansionTypeBits;
1751
1752 static_assert(sizeof(TypeBitfields) <= 8,
1753 "TypeBitfields is larger than 8 bytes!");
1754 static_assert(sizeof(ArrayTypeBitfields) <= 8,
1755 "ArrayTypeBitfields is larger than 8 bytes!");
1756 static_assert(sizeof(AttributedTypeBitfields) <= 8,
1757 "AttributedTypeBitfields is larger than 8 bytes!");
1758 static_assert(sizeof(AutoTypeBitfields) <= 8,
1759 "AutoTypeBitfields is larger than 8 bytes!");
1760 static_assert(sizeof(BuiltinTypeBitfields) <= 8,
1761 "BuiltinTypeBitfields is larger than 8 bytes!");
1762 static_assert(sizeof(FunctionTypeBitfields) <= 8,
1763 "FunctionTypeBitfields is larger than 8 bytes!");
1764 static_assert(sizeof(ObjCObjectTypeBitfields) <= 8,
1765 "ObjCObjectTypeBitfields is larger than 8 bytes!");
1766 static_assert(sizeof(ReferenceTypeBitfields) <= 8,
1767 "ReferenceTypeBitfields is larger than 8 bytes!");
1768 static_assert(sizeof(TypeWithKeywordBitfields) <= 8,
1769 "TypeWithKeywordBitfields is larger than 8 bytes!");
1770 static_assert(sizeof(ElaboratedTypeBitfields) <= 8,
1771 "ElaboratedTypeBitfields is larger than 8 bytes!");
1772 static_assert(sizeof(VectorTypeBitfields) <= 8,
1773 "VectorTypeBitfields is larger than 8 bytes!");
1774 static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8,
1775 "SubstTemplateTypeParmPackTypeBitfields is larger"
1776 " than 8 bytes!");
1777 static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8,
1778 "TemplateSpecializationTypeBitfields is larger"
1779 " than 8 bytes!");
1780 static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8,
1781 "DependentTemplateSpecializationTypeBitfields is larger"
1782 " than 8 bytes!");
1783 static_assert(sizeof(PackExpansionTypeBitfields) <= 8,
1784 "PackExpansionTypeBitfields is larger than 8 bytes");
1785 };
1786
1787private:
1788 template <class T> friend class TypePropertyCache;
1789
1790 /// Set whether this type comes from an AST file.
1791 void setFromAST(bool V = true) const {
1792 TypeBits.FromAST = V;
1793 }
1794
1795protected:
1796 friend class ASTContext;
1797
1798 Type(TypeClass tc, QualType canon, bool Dependent,
1799 bool InstantiationDependent, bool VariablyModified,
1800 bool ContainsUnexpandedParameterPack)
1801 : ExtQualsTypeCommonBase(this,
1802 canon.isNull() ? QualType(this_(), 0) : canon) {
1803 TypeBits.TC = tc;
1804 TypeBits.Dependent = Dependent;
1805 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1806 TypeBits.VariablyModified = VariablyModified;
1807 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1808 TypeBits.CacheValid = false;
1809 TypeBits.CachedLocalOrUnnamed = false;
1810 TypeBits.CachedLinkage = NoLinkage;
1811 TypeBits.FromAST = false;
1812 }
1813
1814 // silence VC++ warning C4355: 'this' : used in base member initializer list
1815 Type *this_() { return this; }
1816
1817 void setDependent(bool D = true) {
1818 TypeBits.Dependent = D;
1819 if (D)
1820 TypeBits.InstantiationDependent = true;
1821 }
1822
1823 void setInstantiationDependent(bool D = true) {
1824 TypeBits.InstantiationDependent = D; }
1825
1826 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1827
1828 void setContainsUnexpandedParameterPack(bool PP = true) {
1829 TypeBits.ContainsUnexpandedParameterPack = PP;
1830 }
1831
1832public:
1833 friend class ASTReader;
1834 friend class ASTWriter;
1835
1836 Type(const Type &) = delete;
1837 Type(Type &&) = delete;
1838 Type &operator=(const Type &) = delete;
1839 Type &operator=(Type &&) = delete;
1840
1841 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1842
1843 /// Whether this type comes from an AST file.
1844 bool isFromAST() const { return TypeBits.FromAST; }
1845
1846 /// Whether this type is or contains an unexpanded parameter
1847 /// pack, used to support C++0x variadic templates.
1848 ///
1849 /// A type that contains a parameter pack shall be expanded by the
1850 /// ellipsis operator at some point. For example, the typedef in the
1851 /// following example contains an unexpanded parameter pack 'T':
1852 ///
1853 /// \code
1854 /// template<typename ...T>
1855 /// struct X {
1856 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1857 /// };
1858 /// \endcode
1859 ///
1860 /// Note that this routine does not specify which
1861 bool containsUnexpandedParameterPack() const {
1862 return TypeBits.ContainsUnexpandedParameterPack;
1863 }
1864
1865 /// Determines if this type would be canonical if it had no further
1866 /// qualification.
1867 bool isCanonicalUnqualified() const {
1868 return CanonicalType == QualType(this, 0);
1869 }
1870
1871 /// Pull a single level of sugar off of this locally-unqualified type.
1872 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1873 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1874 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1875
1876 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1877 /// object types, function types, and incomplete types.
1878
1879 /// Return true if this is an incomplete type.
1880 /// A type that can describe objects, but which lacks information needed to
1881 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1882 /// routine will need to determine if the size is actually required.
1883 ///
1884 /// Def If non-null, and the type refers to some kind of declaration
1885 /// that can be completed (such as a C struct, C++ class, or Objective-C
1886 /// class), will be set to the declaration.
1887 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1888
1889 /// Return true if this is an incomplete or object
1890 /// type, in other words, not a function type.
1891 bool isIncompleteOrObjectType() const {
1892 return !isFunctionType();
1893 }
1894
1895 /// Determine whether this type is an object type.
1896 bool isObjectType() const {
1897 // C++ [basic.types]p8:
1898 // An object type is a (possibly cv-qualified) type that is not a
1899 // function type, not a reference type, and not a void type.
1900 return !isReferenceType() && !isFunctionType() && !isVoidType();
1901 }
1902
1903 /// Return true if this is a literal type
1904 /// (C++11 [basic.types]p10)
1905 bool isLiteralType(const ASTContext &Ctx) const;
1906
1907 /// Test if this type is a standard-layout type.
1908 /// (C++0x [basic.type]p9)
1909 bool isStandardLayoutType() const;
1910
1911 /// Helper methods to distinguish type categories. All type predicates
1912 /// operate on the canonical type, ignoring typedefs and qualifiers.
1913
1914 /// Returns true if the type is a builtin type.
1915 bool isBuiltinType() const;
1916
1917 /// Test for a particular builtin type.
1918 bool isSpecificBuiltinType(unsigned K) const;
1919
1920 /// Test for a type which does not represent an actual type-system type but
1921 /// is instead used as a placeholder for various convenient purposes within
1922 /// Clang. All such types are BuiltinTypes.
1923 bool isPlaceholderType() const;
1924 const BuiltinType *getAsPlaceholderType() const;
1925
1926 /// Test for a specific placeholder type.
1927 bool isSpecificPlaceholderType(unsigned K) const;
1928
1929 /// Test for a placeholder type other than Overload; see
1930 /// BuiltinType::isNonOverloadPlaceholderType.
1931 bool isNonOverloadPlaceholderType() const;
1932
1933 /// isIntegerType() does *not* include complex integers (a GCC extension).
1934 /// isComplexIntegerType() can be used to test for complex integers.
1935 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1936 bool isEnumeralType() const;
1937
1938 /// Determine whether this type is a scoped enumeration type.
1939 bool isScopedEnumeralType() const;
1940 bool isBooleanType() const;
1941 bool isCharType() const;
1942 bool isWideCharType() const;
1943 bool isChar8Type() const;
1944 bool isChar16Type() const;
1945 bool isChar32Type() const;
1946 bool isAnyCharacterType() const;
1947 bool isIntegralType(const ASTContext &Ctx) const;
1948
1949 /// Determine whether this type is an integral or enumeration type.
1950 bool isIntegralOrEnumerationType() const;
1951
1952 /// Determine whether this type is an integral or unscoped enumeration type.
1953 bool isIntegralOrUnscopedEnumerationType() const;
1954
1955 /// Floating point categories.
1956 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1957 /// isComplexType() does *not* include complex integers (a GCC extension).
1958 /// isComplexIntegerType() can be used to test for complex integers.
1959 bool isComplexType() const; // C99 6.2.5p11 (complex)
1960 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1961 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1962 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1963 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1964 bool isFloat128Type() const;
1965 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1966 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1967 bool isVoidType() const; // C99 6.2.5p19
1968 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1969 bool isAggregateType() const;
1970 bool isFundamentalType() const;
1971 bool isCompoundType() const;
1972
1973 // Type Predicates: Check to see if this type is structurally the specified
1974 // type, ignoring typedefs and qualifiers.
1975 bool isFunctionType() const;
1976 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1977 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1978 bool isPointerType() const;
1979 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1980 bool isBlockPointerType() const;
1981 bool isVoidPointerType() const;
1982 bool isReferenceType() const;
1983 bool isLValueReferenceType() const;
1984 bool isRValueReferenceType() const;
1985 bool isFunctionPointerType() const;
1986 bool isFunctionReferenceType() const;
1987 bool isMemberPointerType() const;
1988 bool isMemberFunctionPointerType() const;
1989 bool isMemberDataPointerType() const;
1990 bool isArrayType() const;
1991 bool isConstantArrayType() const;
1992 bool isIncompleteArrayType() const;
1993 bool isVariableArrayType() const;
1994 bool isDependentSizedArrayType() const;
1995 bool isRecordType() const;
1996 bool isClassType() const;
1997 bool isStructureType() const;
1998 bool isObjCBoxableRecordType() const;
1999 bool isInterfaceType() const;
2000 bool isStructureOrClassType() const;
2001 bool isUnionType() const;
2002 bool isComplexIntegerType() const; // GCC _Complex integer type.
2003 bool isVectorType() const; // GCC vector type.
2004 bool isExtVectorType() const; // Extended vector type.
2005 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2006 bool isObjCObjectPointerType() const; // pointer to ObjC object
2007 bool isObjCRetainableType() const; // ObjC object or block pointer
2008 bool isObjCLifetimeType() const; // (array of)* retainable type
2009 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2010 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2011 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2012 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2013 // for the common case.
2014 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2015 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2016 bool isObjCQualifiedIdType() const; // id<foo>
2017 bool isObjCQualifiedClassType() const; // Class<foo>
2018 bool isObjCObjectOrInterfaceType() const;
2019 bool isObjCIdType() const; // id
2020 bool isDecltypeType() const;
2021 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2022 /// qualifier?
2023 ///
2024 /// This approximates the answer to the following question: if this
2025 /// translation unit were compiled in ARC, would this type be qualified
2026 /// with __unsafe_unretained?
2027 bool isObjCInertUnsafeUnretainedType() const {
2028 return hasAttr(attr::ObjCInertUnsafeUnretained);
2029 }
2030
2031 /// Whether the type is Objective-C 'id' or a __kindof type of an
2032 /// object type, e.g., __kindof NSView * or __kindof id
2033 /// <NSCopying>.
2034 ///
2035 /// \param bound Will be set to the bound on non-id subtype types,
2036 /// which will be (possibly specialized) Objective-C class type, or
2037 /// null for 'id.
2038 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2039 const ObjCObjectType *&bound) const;
2040
2041 bool isObjCClassType() const; // Class
2042
2043 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2044 /// Class type, e.g., __kindof Class <NSCopying>.
2045 ///
2046 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2047 /// here because Objective-C's type system cannot express "a class
2048 /// object for a subclass of NSFoo".
2049 bool isObjCClassOrClassKindOfType() const;
2050
2051 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2052 bool isObjCSelType() const; // Class
2053 bool isObjCBuiltinType() const; // 'id' or 'Class'
2054 bool isObjCARCBridgableType() const;
2055 bool isCARCBridgableType() const;
2056 bool isTemplateTypeParmType() const; // C++ template type parameter
2057 bool isNullPtrType() const; // C++11 std::nullptr_t
2058 bool isNothrowT() const; // C++ std::nothrow_t
2059 bool isAlignValT() const; // C++17 std::align_val_t
2060 bool isStdByteType() const; // C++17 std::byte
2061 bool isAtomicType() const; // C11 _Atomic()
2062
2063#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2064 bool is##Id##Type() const;
2065#include "clang/Basic/OpenCLImageTypes.def"
2066
2067 bool isImageType() const; // Any OpenCL image type
2068
2069 bool isSamplerT() const; // OpenCL sampler_t
2070 bool isEventT() const; // OpenCL event_t
2071 bool isClkEventT() const; // OpenCL clk_event_t
2072 bool isQueueT() const; // OpenCL queue_t
2073 bool isReserveIDT() const; // OpenCL reserve_id_t
2074
2075#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2076 bool is##Id##Type() const;
2077#include "clang/Basic/OpenCLExtensionTypes.def"
2078 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2079 bool isOCLIntelSubgroupAVCType() const;
2080 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2081
2082 bool isPipeType() const; // OpenCL pipe type
2083 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2084
2085 /// Determines if this type, which must satisfy
2086 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2087 /// than implicitly __strong.
2088 bool isObjCARCImplicitlyUnretainedType() const;
2089
2090 /// Return the implicit lifetime for this type, which must not be dependent.
2091 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2092
2093 enum ScalarTypeKind {
2094 STK_CPointer,
2095 STK_BlockPointer,
2096 STK_ObjCObjectPointer,
2097 STK_MemberPointer,
2098 STK_Bool,
2099 STK_Integral,
2100 STK_Floating,
2101 STK_IntegralComplex,
2102 STK_FloatingComplex,
2103 STK_FixedPoint
2104 };
2105
2106 /// Given that this is a scalar type, classify it.
2107 ScalarTypeKind getScalarTypeKind() const;
2108
2109 /// Whether this type is a dependent type, meaning that its definition
2110 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2111 bool isDependentType() const { return TypeBits.Dependent; }
2112
2113 /// Determine whether this type is an instantiation-dependent type,
2114 /// meaning that the type involves a template parameter (even if the
2115 /// definition does not actually depend on the type substituted for that
2116 /// template parameter).
2117 bool isInstantiationDependentType() const {
2118 return TypeBits.InstantiationDependent;
2119 }
2120
2121 /// Determine whether this type is an undeduced type, meaning that
2122 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2123 /// deduced.
2124 bool isUndeducedType() const;
2125
2126 /// Whether this type is a variably-modified type (C99 6.7.5).
2127 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
2128
2129 /// Whether this type involves a variable-length array type
2130 /// with a definite size.
2131 bool hasSizedVLAType() const;
2132
2133 /// Whether this type is or contains a local or unnamed type.
2134 bool hasUnnamedOrLocalType() const;
2135
2136 bool isOverloadableType() const;
2137
2138 /// Determine wither this type is a C++ elaborated-type-specifier.
2139 bool isElaboratedTypeSpecifier() const;
2140
2141 bool canDecayToPointerType() const;
2142
2143 /// Whether this type is represented natively as a pointer. This includes
2144 /// pointers, references, block pointers, and Objective-C interface,
2145 /// qualified id, and qualified interface types, as well as nullptr_t.
2146 bool hasPointerRepresentation() const;
2147
2148 /// Whether this type can represent an objective pointer type for the
2149 /// purpose of GC'ability
2150 bool hasObjCPointerRepresentation() const;
2151
2152 /// Determine whether this type has an integer representation
2153 /// of some sort, e.g., it is an integer type or a vector.
2154 bool hasIntegerRepresentation() const;
2155
2156 /// Determine whether this type has an signed integer representation
2157 /// of some sort, e.g., it is an signed integer type or a vector.
2158 bool hasSignedIntegerRepresentation() const;
2159
2160 /// Determine whether this type has an unsigned integer representation
2161 /// of some sort, e.g., it is an unsigned integer type or a vector.
2162 bool hasUnsignedIntegerRepresentation() const;
2163
2164 /// Determine whether this type has a floating-point representation
2165 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2166 bool hasFloatingRepresentation() const;
2167
2168 // Type Checking Functions: Check to see if this type is structurally the
2169 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2170 // the best type we can.
2171 const RecordType *getAsStructureType() const;
2172 /// NOTE: getAs*ArrayType are methods on ASTContext.
2173 const RecordType *getAsUnionType() const;
2174 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2175 const ObjCObjectType *getAsObjCInterfaceType() const;
2176
2177 // The following is a convenience method that returns an ObjCObjectPointerType
2178 // for object declared using an interface.
2179 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2180 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2181 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2182 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2183
2184 /// Retrieves the CXXRecordDecl that this type refers to, either
2185 /// because the type is a RecordType or because it is the injected-class-name
2186 /// type of a class template or class template partial specialization.
2187 CXXRecordDecl *getAsCXXRecordDecl() const;
2188
2189 /// Retrieves the RecordDecl this type refers to.
2190 RecordDecl *getAsRecordDecl() const;
2191
2192 /// Retrieves the TagDecl that this type refers to, either
2193 /// because the type is a TagType or because it is the injected-class-name
2194 /// type of a class template or class template partial specialization.
2195 TagDecl *getAsTagDecl() const;
2196
2197 /// If this is a pointer or reference to a RecordType, return the
2198 /// CXXRecordDecl that the type refers to.
2199 ///
2200 /// If this is not a pointer or reference, or the type being pointed to does
2201 /// not refer to a CXXRecordDecl, returns NULL.
2202 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2203
2204 /// Get the DeducedType whose type will be deduced for a variable with
2205 /// an initializer of this type. This looks through declarators like pointer
2206 /// types, but not through decltype or typedefs.
2207 DeducedType *getContainedDeducedType() const;
2208
2209 /// Get the AutoType whose type will be deduced for a variable with
2210 /// an initializer of this type. This looks through declarators like pointer
2211 /// types, but not through decltype or typedefs.
2212 AutoType *getContainedAutoType() const {
2213 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2214 }
2215
2216 /// Determine whether this type was written with a leading 'auto'
2217 /// corresponding to a trailing return type (possibly for a nested
2218 /// function type within a pointer to function type or similar).
2219 bool hasAutoForTrailingReturnType() const;
2220
2221 /// Member-template getAs<specific type>'. Look through sugar for
2222 /// an instance of \<specific type>. This scheme will eventually
2223 /// replace the specific getAsXXXX methods above.
2224 ///
2225 /// There are some specializations of this member template listed
2226 /// immediately following this class.
2227 template <typename T> const T *getAs() const;
2228
2229 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2230 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2231 /// This is used when you need to walk over sugar nodes that represent some
2232 /// kind of type adjustment from a type that was written as a \<specific type>
2233 /// to another type that is still canonically a \<specific type>.
2234 template <typename T> const T *getAsAdjusted() const;
2235
2236 /// A variant of getAs<> for array types which silently discards
2237 /// qualifiers from the outermost type.
2238 const ArrayType *getAsArrayTypeUnsafe() const;
2239
2240 /// Member-template castAs<specific type>. Look through sugar for
2241 /// the underlying instance of \<specific type>.
2242 ///
2243 /// This method has the same relationship to getAs<T> as cast<T> has
2244 /// to dyn_cast<T>; which is to say, the underlying type *must*
2245 /// have the intended type, and this method will never return null.
2246 template <typename T> const T *castAs() const;
2247
2248 /// A variant of castAs<> for array type which silently discards
2249 /// qualifiers from the outermost type.
2250 const ArrayType *castAsArrayTypeUnsafe() const;
2251
2252 /// Determine whether this type had the specified attribute applied to it
2253 /// (looking through top-level type sugar).
2254 bool hasAttr(attr::Kind AK) const;
2255
2256 /// Get the base element type of this type, potentially discarding type
2257 /// qualifiers. This should never be used when type qualifiers
2258 /// are meaningful.
2259 const Type *getBaseElementTypeUnsafe() const;
2260
2261 /// If this is an array type, return the element type of the array,
2262 /// potentially with type qualifiers missing.
2263 /// This should never be used when type qualifiers are meaningful.
2264 const Type *getArrayElementTypeNoTypeQual() const;
2265
2266 /// If this is a pointer type, return the pointee type.
2267 /// If this is an array type, return the array element type.
2268 /// This should never be used when type qualifiers are meaningful.
2269 const Type *getPointeeOrArrayElementType() const;
2270
2271 /// If this is a pointer, ObjC object pointer, or block
2272 /// pointer, this returns the respective pointee.
2273 QualType getPointeeType() const;
2274
2275 /// Return the specified type with any "sugar" removed from the type,
2276 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2277 const Type *getUnqualifiedDesugaredType() const;
2278
2279 /// More type predicates useful for type checking/promotion
2280 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2281
2282 /// Return true if this is an integer type that is
2283 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2284 /// or an enum decl which has a signed representation.
2285 bool isSignedIntegerType() const;
2286
2287 /// Return true if this is an integer type that is
2288 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2289 /// or an enum decl which has an unsigned representation.
2290 bool isUnsignedIntegerType() const;
2291
2292 /// Determines whether this is an integer type that is signed or an
2293 /// enumeration types whose underlying type is a signed integer type.
2294 bool isSignedIntegerOrEnumerationType() const;
2295
2296 /// Determines whether this is an integer type that is unsigned or an
2297 /// enumeration types whose underlying type is a unsigned integer type.
2298 bool isUnsignedIntegerOrEnumerationType() const;
2299
2300 /// Return true if this is a fixed point type according to
2301 /// ISO/IEC JTC1 SC22 WG14 N1169.
2302 bool isFixedPointType() const;
2303
2304 /// Return true if this is a fixed point or integer type.
2305 bool isFixedPointOrIntegerType() const;
2306
2307 /// Return true if this is a saturated fixed point type according to
2308 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2309 bool isSaturatedFixedPointType() const;
2310
2311 /// Return true if this is a saturated fixed point type according to
2312 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2313 bool isUnsaturatedFixedPointType() const;
2314
2315 /// Return true if this is a fixed point type that is signed according
2316 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2317 bool isSignedFixedPointType() const;
2318
2319 /// Return true if this is a fixed point type that is unsigned according
2320 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2321 bool isUnsignedFixedPointType() const;
2322
2323 /// Return true if this is not a variable sized type,
2324 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2325 /// incomplete types.
2326 bool isConstantSizeType() const;
2327
2328 /// Returns true if this type can be represented by some
2329 /// set of type specifiers.
2330 bool isSpecifierType() const;
2331
2332 /// Determine the linkage of this type.
2333 Linkage getLinkage() const;
2334
2335 /// Determine the visibility of this type.
2336 Visibility getVisibility() const {
2337 return getLinkageAndVisibility().getVisibility();
2338 }
2339
2340 /// Return true if the visibility was explicitly set is the code.
2341 bool isVisibilityExplicit() const {
2342 return getLinkageAndVisibility().isVisibilityExplicit();
2343 }
2344
2345 /// Determine the linkage and visibility of this type.
2346 LinkageInfo getLinkageAndVisibility() const;
2347
2348 /// True if the computed linkage is valid. Used for consistency
2349 /// checking. Should always return true.
2350 bool isLinkageValid() const;
2351
2352 /// Determine the nullability of the given type.
2353 ///
2354 /// Note that nullability is only captured as sugar within the type
2355 /// system, not as part of the canonical type, so nullability will
2356 /// be lost by canonicalization and desugaring.
2357 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2358
2359 /// Determine whether the given type can have a nullability
2360 /// specifier applied to it, i.e., if it is any kind of pointer type.
2361 ///
2362 /// \param ResultIfUnknown The value to return if we don't yet know whether
2363 /// this type can have nullability because it is dependent.
2364 bool canHaveNullability(bool ResultIfUnknown = true) const;
2365
2366 /// Retrieve the set of substitutions required when accessing a member
2367 /// of the Objective-C receiver type that is declared in the given context.
2368 ///
2369 /// \c *this is the type of the object we're operating on, e.g., the
2370 /// receiver for a message send or the base of a property access, and is
2371 /// expected to be of some object or object pointer type.
2372 ///
2373 /// \param dc The declaration context for which we are building up a
2374 /// substitution mapping, which should be an Objective-C class, extension,
2375 /// category, or method within.
2376 ///
2377 /// \returns an array of type arguments that can be substituted for
2378 /// the type parameters of the given declaration context in any type described
2379 /// within that context, or an empty optional to indicate that no
2380 /// substitution is required.
2381 Optional<ArrayRef<QualType>>
2382 getObjCSubstitutions(const DeclContext *dc) const;
2383
2384 /// Determines if this is an ObjC interface type that may accept type
2385 /// parameters.
2386 bool acceptsObjCTypeParams() const;
2387
2388 const char *getTypeClassName() const;
2389
2390 QualType getCanonicalTypeInternal() const {
2391 return CanonicalType;
2392 }
2393
2394 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2395 void dump() const;
2396 void dump(llvm::raw_ostream &OS) const;
2397};
2398
2399/// This will check for a TypedefType by removing any existing sugar
2400/// until it reaches a TypedefType or a non-sugared type.
2401template <> const TypedefType *Type::getAs() const;
2402
2403/// This will check for a TemplateSpecializationType by removing any
2404/// existing sugar until it reaches a TemplateSpecializationType or a
2405/// non-sugared type.
2406template <> const TemplateSpecializationType *Type::getAs() const;
2407
2408/// This will check for an AttributedType by removing any existing sugar
2409/// until it reaches an AttributedType or a non-sugared type.
2410template <> const AttributedType *Type::getAs() const;
2411
2412// We can do canonical leaf types faster, because we don't have to
2413// worry about preserving child type decoration.
2414#define TYPE(Class, Base)
2415#define LEAF_TYPE(Class) \
2416template <> inline const Class##Type *Type::getAs() const { \
2417 return dyn_cast<Class##Type>(CanonicalType); \
2418} \
2419template <> inline const Class##Type *Type::castAs() const { \
2420 return cast<Class##Type>(CanonicalType); \
2421}
2422#include "clang/AST/TypeNodes.inc"
2423
2424/// This class is used for builtin types like 'int'. Builtin
2425/// types are always canonical and have a literal name field.
2426class BuiltinType : public Type {
2427public:
2428 enum Kind {
2429// OpenCL image types
2430#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2431#include "clang/Basic/OpenCLImageTypes.def"
2432// OpenCL extension types
2433#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2434#include "clang/Basic/OpenCLExtensionTypes.def"
2435// SVE Types
2436#define SVE_TYPE(Name, Id, SingletonId) Id,
2437#include "clang/Basic/AArch64SVEACLETypes.def"
2438// All other builtin types
2439#define BUILTIN_TYPE(Id, SingletonId) Id,
2440#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2441#include "clang/AST/BuiltinTypes.def"
2442 };
2443
2444private:
2445 friend class ASTContext; // ASTContext creates these.
2446
2447 BuiltinType(Kind K)
2448 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2449 /*InstantiationDependent=*/(K == Dependent),
2450 /*VariablyModified=*/false,
2451 /*Unexpanded parameter pack=*/false) {
2452 BuiltinTypeBits.Kind = K;
2453 }
2454
2455public:
2456 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2457 StringRef getName(const PrintingPolicy &Policy) const;
2458
2459 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2460 // The StringRef is null-terminated.
2461 StringRef str = getName(Policy);
2462 assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast
<void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 2462, __PRETTY_FUNCTION__))
;
2463 return str.data();
2464 }
2465
2466 bool isSugared() const { return false; }
2467 QualType desugar() const { return QualType(this, 0); }
2468
2469 bool isInteger() const {
2470 return getKind() >= Bool && getKind() <= Int128;
2471 }
2472
2473 bool isSignedInteger() const {
2474 return getKind() >= Char_S && getKind() <= Int128;
2475 }
2476
2477 bool isUnsignedInteger() const {
2478 return getKind() >= Bool && getKind() <= UInt128;
2479 }
2480
2481 bool isFloatingPoint() const {
2482 return getKind() >= Half && getKind() <= Float128;
2483 }
2484
2485 /// Determines whether the given kind corresponds to a placeholder type.
2486 static bool isPlaceholderTypeKind(Kind K) {
2487 return K >= Overload;
2488 }
2489
2490 /// Determines whether this type is a placeholder type, i.e. a type
2491 /// which cannot appear in arbitrary positions in a fully-formed
2492 /// expression.
2493 bool isPlaceholderType() const {
2494 return isPlaceholderTypeKind(getKind());
2495 }
2496
2497 /// Determines whether this type is a placeholder type other than
2498 /// Overload. Most placeholder types require only syntactic
2499 /// information about their context in order to be resolved (e.g.
2500 /// whether it is a call expression), which means they can (and
2501 /// should) be resolved in an earlier "phase" of analysis.
2502 /// Overload expressions sometimes pick up further information
2503 /// from their context, like whether the context expects a
2504 /// specific function-pointer type, and so frequently need
2505 /// special treatment.
2506 bool isNonOverloadPlaceholderType() const {
2507 return getKind() > Overload;
2508 }
2509
2510 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2511};
2512
2513/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2514/// types (_Complex float etc) as well as the GCC integer complex extensions.
2515class ComplexType : public Type, public llvm::FoldingSetNode {
2516 friend class ASTContext; // ASTContext creates these.
2517
2518 QualType ElementType;
2519
2520 ComplexType(QualType Element, QualType CanonicalPtr)
2521 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2522 Element->isInstantiationDependentType(),
2523 Element->isVariablyModifiedType(),
2524 Element->containsUnexpandedParameterPack()),
2525 ElementType(Element) {}
2526
2527public:
2528 QualType getElementType() const { return ElementType; }
2529
2530 bool isSugared() const { return false; }
2531 QualType desugar() const { return QualType(this, 0); }
2532
2533 void Profile(llvm::FoldingSetNodeID &ID) {
2534 Profile(ID, getElementType());
2535 }
2536
2537 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2538 ID.AddPointer(Element.getAsOpaquePtr());
2539 }
2540
2541 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2542};
2543
2544/// Sugar for parentheses used when specifying types.
2545class ParenType : public Type, public llvm::FoldingSetNode {
2546 friend class ASTContext; // ASTContext creates these.
2547
2548 QualType Inner;
2549
2550 ParenType(QualType InnerType, QualType CanonType)
2551 : Type(Paren, CanonType, InnerType->isDependentType(),
2552 InnerType->isInstantiationDependentType(),
2553 InnerType->isVariablyModifiedType(),
2554 InnerType->containsUnexpandedParameterPack()),
2555 Inner(InnerType) {}
2556
2557public:
2558 QualType getInnerType() const { return Inner; }
2559
2560 bool isSugared() const { return true; }
2561 QualType desugar() const { return getInnerType(); }
2562
2563 void Profile(llvm::FoldingSetNodeID &ID) {
2564 Profile(ID, getInnerType());
2565 }
2566
2567 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2568 Inner.Profile(ID);
2569 }
2570
2571 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2572};
2573
2574/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2575class PointerType : public Type, public llvm::FoldingSetNode {
2576 friend class ASTContext; // ASTContext creates these.
2577
2578 QualType PointeeType;
2579
2580 PointerType(QualType Pointee, QualType CanonicalPtr)
2581 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2582 Pointee->isInstantiationDependentType(),
2583 Pointee->isVariablyModifiedType(),
2584 Pointee->containsUnexpandedParameterPack()),
2585 PointeeType(Pointee) {}
2586
2587public:
2588 QualType getPointeeType() const { return PointeeType; }
2589
2590 /// Returns true if address spaces of pointers overlap.
2591 /// OpenCL v2.0 defines conversion rules for pointers to different
2592 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2593 /// address spaces.
2594 /// CL1.1 or CL1.2:
2595 /// address spaces overlap iff they are they same.
2596 /// CL2.0 adds:
2597 /// __generic overlaps with any address space except for __constant.
2598 bool isAddressSpaceOverlapping(const PointerType &other) const {
2599 Qualifiers thisQuals = PointeeType.getQualifiers();
2600 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2601 // Address spaces overlap if at least one of them is a superset of another
2602 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2603 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2604 }
2605
2606 bool isSugared() const { return false; }
2607 QualType desugar() const { return QualType(this, 0); }
2608
2609 void Profile(llvm::FoldingSetNodeID &ID) {
2610 Profile(ID, getPointeeType());
2611 }
2612
2613 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2614 ID.AddPointer(Pointee.getAsOpaquePtr());
2615 }
2616
2617 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2618};
2619
2620/// Represents a type which was implicitly adjusted by the semantic
2621/// engine for arbitrary reasons. For example, array and function types can
2622/// decay, and function types can have their calling conventions adjusted.
2623class AdjustedType : public Type, public llvm::FoldingSetNode {
2624 QualType OriginalTy;
2625 QualType AdjustedTy;
2626
2627protected:
2628 friend class ASTContext; // ASTContext creates these.
2629
2630 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2631 QualType CanonicalPtr)
2632 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2633 OriginalTy->isInstantiationDependentType(),
2634 OriginalTy->isVariablyModifiedType(),
2635 OriginalTy->containsUnexpandedParameterPack()),
2636 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2637
2638public:
2639 QualType getOriginalType() const { return OriginalTy; }
2640 QualType getAdjustedType() const { return AdjustedTy; }
2641
2642 bool isSugared() const { return true; }
2643 QualType desugar() const { return AdjustedTy; }
2644
2645 void Profile(llvm::FoldingSetNodeID &ID) {
2646 Profile(ID, OriginalTy, AdjustedTy);
2647 }
2648
2649 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2650 ID.AddPointer(Orig.getAsOpaquePtr());
2651 ID.AddPointer(New.getAsOpaquePtr());
2652 }
2653
2654 static bool classof(const Type *T) {
2655 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2656 }
2657};
2658
2659/// Represents a pointer type decayed from an array or function type.
2660class DecayedType : public AdjustedType {
2661 friend class ASTContext; // ASTContext creates these.
2662
2663 inline
2664 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2665
2666public:
2667 QualType getDecayedType() const { return getAdjustedType(); }
2668
2669 inline QualType getPointeeType() const;
2670
2671 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2672};
2673
2674/// Pointer to a block type.
2675/// This type is to represent types syntactically represented as
2676/// "void (^)(int)", etc. Pointee is required to always be a function type.
2677class BlockPointerType : public Type, public llvm::FoldingSetNode {
2678 friend class ASTContext; // ASTContext creates these.
2679
2680 // Block is some kind of pointer type
2681 QualType PointeeType;
2682
2683 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2684 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2685 Pointee->isInstantiationDependentType(),
2686 Pointee->isVariablyModifiedType(),
2687 Pointee->containsUnexpandedParameterPack()),
2688 PointeeType(Pointee) {}
2689
2690public:
2691 // Get the pointee type. Pointee is required to always be a function type.
2692 QualType getPointeeType() const { return PointeeType; }
2693
2694 bool isSugared() const { return false; }
2695 QualType desugar() const { return QualType(this, 0); }
2696
2697 void Profile(llvm::FoldingSetNodeID &ID) {
2698 Profile(ID, getPointeeType());
2699 }
2700
2701 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2702 ID.AddPointer(Pointee.getAsOpaquePtr());
2703 }
2704
2705 static bool classof(const Type *T) {
2706 return T->getTypeClass() == BlockPointer;
2707 }
2708};
2709
2710/// Base for LValueReferenceType and RValueReferenceType
2711class ReferenceType : public Type, public llvm::FoldingSetNode {
2712 QualType PointeeType;
2713
2714protected:
2715 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2716 bool SpelledAsLValue)
2717 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2718 Referencee->isInstantiationDependentType(),
2719 Referencee->isVariablyModifiedType(),
2720 Referencee->containsUnexpandedParameterPack()),
2721 PointeeType(Referencee) {
2722 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2723 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2724 }
2725
2726public:
2727 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2728 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2729
2730 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2731
2732 QualType getPointeeType() const {
2733 // FIXME: this might strip inner qualifiers; okay?
2734 const ReferenceType *T = this;
2735 while (T->isInnerRef())
2736 T = T->PointeeType->castAs<ReferenceType>();
2737 return T->PointeeType;
2738 }
2739
2740 void Profile(llvm::FoldingSetNodeID &ID) {
2741 Profile(ID, PointeeType, isSpelledAsLValue());
2742 }
2743
2744 static void Profile(llvm::FoldingSetNodeID &ID,
2745 QualType Referencee,
2746 bool SpelledAsLValue) {
2747 ID.AddPointer(Referencee.getAsOpaquePtr());
2748 ID.AddBoolean(SpelledAsLValue);
2749 }
2750
2751 static bool classof(const Type *T) {
2752 return T->getTypeClass() == LValueReference ||
2753 T->getTypeClass() == RValueReference;
2754 }
2755};
2756
2757/// An lvalue reference type, per C++11 [dcl.ref].
2758class LValueReferenceType : public ReferenceType {
2759 friend class ASTContext; // ASTContext creates these
2760
2761 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2762 bool SpelledAsLValue)
2763 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2764 SpelledAsLValue) {}
2765
2766public:
2767 bool isSugared() const { return false; }
2768 QualType desugar() const { return QualType(this, 0); }
2769
2770 static bool classof(const Type *T) {
2771 return T->getTypeClass() == LValueReference;
2772 }
2773};
2774
2775/// An rvalue reference type, per C++11 [dcl.ref].
2776class RValueReferenceType : public ReferenceType {
2777 friend class ASTContext; // ASTContext creates these
2778
2779 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2780 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2781
2782public:
2783 bool isSugared() const { return false; }
2784 QualType desugar() const { return QualType(this, 0); }
2785
2786 static bool classof(const Type *T) {
2787 return T->getTypeClass() == RValueReference;
2788 }
2789};
2790
2791/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2792///
2793/// This includes both pointers to data members and pointer to member functions.
2794class MemberPointerType : public Type, public llvm::FoldingSetNode {
2795 friend class ASTContext; // ASTContext creates these.
2796
2797 QualType PointeeType;
2798
2799 /// The class of which the pointee is a member. Must ultimately be a
2800 /// RecordType, but could be a typedef or a template parameter too.
2801 const Type *Class;
2802
2803 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2804 : Type(MemberPointer, CanonicalPtr,
2805 Cls->isDependentType() || Pointee->isDependentType(),
2806 (Cls->isInstantiationDependentType() ||
2807 Pointee->isInstantiationDependentType()),
2808 Pointee->isVariablyModifiedType(),
2809 (Cls->containsUnexpandedParameterPack() ||
2810 Pointee->containsUnexpandedParameterPack())),
2811 PointeeType(Pointee), Class(Cls) {}
2812
2813public:
2814 QualType getPointeeType() const { return PointeeType; }
2815
2816 /// Returns true if the member type (i.e. the pointee type) is a
2817 /// function type rather than a data-member type.
2818 bool isMemberFunctionPointer() const {
2819 return PointeeType->isFunctionProtoType();
2820 }
2821
2822 /// Returns true if the member type (i.e. the pointee type) is a
2823 /// data type rather than a function type.
2824 bool isMemberDataPointer() const {
2825 return !PointeeType->isFunctionProtoType();
2826 }
2827
2828 const Type *getClass() const { return Class; }
2829 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2830
2831 bool isSugared() const { return false; }
2832 QualType desugar() const { return QualType(this, 0); }
2833
2834 void Profile(llvm::FoldingSetNodeID &ID) {
2835 Profile(ID, getPointeeType(), getClass());
2836 }
2837
2838 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2839 const Type *Class) {
2840 ID.AddPointer(Pointee.getAsOpaquePtr());
2841 ID.AddPointer(Class);
2842 }
2843
2844 static bool classof(const Type *T) {
2845 return T->getTypeClass() == MemberPointer;
2846 }
2847};
2848
2849/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2850class ArrayType : public Type, public llvm::FoldingSetNode {
2851public:
2852 /// Capture whether this is a normal array (e.g. int X[4])
2853 /// an array with a static size (e.g. int X[static 4]), or an array
2854 /// with a star size (e.g. int X[*]).
2855 /// 'static' is only allowed on function parameters.
2856 enum ArraySizeModifier {
2857 Normal, Static, Star
2858 };
2859
2860private:
2861 /// The element type of the array.
2862 QualType ElementType;
2863
2864protected:
2865 friend class ASTContext; // ASTContext creates these.
2866
2867 // C++ [temp.dep.type]p1:
2868 // A type is dependent if it is...
2869 // - an array type constructed from any dependent type or whose
2870 // size is specified by a constant expression that is
2871 // value-dependent,
2872 ArrayType(TypeClass tc, QualType et, QualType can,
2873 ArraySizeModifier sm, unsigned tq,
2874 bool ContainsUnexpandedParameterPack)
2875 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2876 et->isInstantiationDependentType() || tc == DependentSizedArray,
2877 (tc == VariableArray || et->isVariablyModifiedType()),
2878 ContainsUnexpandedParameterPack),
2879 ElementType(et) {
2880 ArrayTypeBits.IndexTypeQuals = tq;
2881 ArrayTypeBits.SizeModifier = sm;
2882 }
2883
2884public:
2885 QualType getElementType() const { return ElementType; }
2886
2887 ArraySizeModifier getSizeModifier() const {
2888 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2889 }
2890
2891 Qualifiers getIndexTypeQualifiers() const {
2892 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2893 }
2894
2895 unsigned getIndexTypeCVRQualifiers() const {
2896 return ArrayTypeBits.IndexTypeQuals;
2897 }
2898
2899 static bool classof(const Type *T) {
2900 return T->getTypeClass() == ConstantArray ||
2901 T->getTypeClass() == VariableArray ||
2902 T->getTypeClass() == IncompleteArray ||
2903 T->getTypeClass() == DependentSizedArray;
2904 }
2905};
2906
2907/// Represents the canonical version of C arrays with a specified constant size.
2908/// For example, the canonical type for 'int A[4 + 4*100]' is a
2909/// ConstantArrayType where the element type is 'int' and the size is 404.
2910class ConstantArrayType : public ArrayType {
2911 llvm::APInt Size; // Allows us to unique the type.
2912
2913 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2914 ArraySizeModifier sm, unsigned tq)
2915 : ArrayType(ConstantArray, et, can, sm, tq,
2916 et->containsUnexpandedParameterPack()),
2917 Size(size) {}
2918
2919protected:
2920 friend class ASTContext; // ASTContext creates these.
2921
2922 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2923 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2924 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2925 Size(size) {}
2926
2927public:
2928 const llvm::APInt &getSize() const { return Size; }
2929 bool isSugared() const { return false; }
2930 QualType desugar() const { return QualType(this, 0); }
2931
2932 /// Determine the number of bits required to address a member of
2933 // an array with the given element type and number of elements.
2934 static unsigned getNumAddressingBits(const ASTContext &Context,
2935 QualType ElementType,
2936 const llvm::APInt &NumElements);
2937
2938 /// Determine the maximum number of active bits that an array's size
2939 /// can require, which limits the maximum size of the array.
2940 static unsigned getMaxSizeBits(const ASTContext &Context);
2941
2942 void Profile(llvm::FoldingSetNodeID &ID) {
2943 Profile(ID, getElementType(), getSize(),
2944 getSizeModifier(), getIndexTypeCVRQualifiers());
2945 }
2946
2947 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2948 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2949 unsigned TypeQuals) {
2950 ID.AddPointer(ET.getAsOpaquePtr());
2951 ID.AddInteger(ArraySize.getZExtValue());
2952 ID.AddInteger(SizeMod);
2953 ID.AddInteger(TypeQuals);
2954 }
2955
2956 static bool classof(const Type *T) {
2957 return T->getTypeClass() == ConstantArray;
2958 }
2959};
2960
2961/// Represents a C array with an unspecified size. For example 'int A[]' has
2962/// an IncompleteArrayType where the element type is 'int' and the size is
2963/// unspecified.
2964class IncompleteArrayType : public ArrayType {
2965 friend class ASTContext; // ASTContext creates these.
2966
2967 IncompleteArrayType(QualType et, QualType can,
2968 ArraySizeModifier sm, unsigned tq)
2969 : ArrayType(IncompleteArray, et, can, sm, tq,
2970 et->containsUnexpandedParameterPack()) {}
2971
2972public:
2973 friend class StmtIteratorBase;
2974
2975 bool isSugared() const { return false; }
2976 QualType desugar() const { return QualType(this, 0); }
2977
2978 static bool classof(const Type *T) {
2979 return T->getTypeClass() == IncompleteArray;
2980 }
2981
2982 void Profile(llvm::FoldingSetNodeID &ID) {
2983 Profile(ID, getElementType(), getSizeModifier(),
2984 getIndexTypeCVRQualifiers());
2985 }
2986
2987 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2988 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2989 ID.AddPointer(ET.getAsOpaquePtr());
2990 ID.AddInteger(SizeMod);
2991 ID.AddInteger(TypeQuals);
2992 }
2993};
2994
2995/// Represents a C array with a specified size that is not an
2996/// integer-constant-expression. For example, 'int s[x+foo()]'.
2997/// Since the size expression is an arbitrary expression, we store it as such.
2998///
2999/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3000/// should not be: two lexically equivalent variable array types could mean
3001/// different things, for example, these variables do not have the same type
3002/// dynamically:
3003///
3004/// void foo(int x) {
3005/// int Y[x];
3006/// ++x;
3007/// int Z[x];
3008/// }
3009class VariableArrayType : public ArrayType {
3010 friend class ASTContext; // ASTContext creates these.
3011
3012 /// An assignment-expression. VLA's are only permitted within
3013 /// a function block.
3014 Stmt *SizeExpr;
3015
3016 /// The range spanned by the left and right array brackets.
3017 SourceRange Brackets;
3018
3019 VariableArrayType(QualType et, QualType can, Expr *e,
3020 ArraySizeModifier sm, unsigned tq,
3021 SourceRange brackets)
3022 : ArrayType(VariableArray, et, can, sm, tq,
3023 et->containsUnexpandedParameterPack()),
3024 SizeExpr((Stmt*) e), Brackets(brackets) {}
3025
3026public:
3027 friend class StmtIteratorBase;
3028
3029 Expr *getSizeExpr() const {
3030 // We use C-style casts instead of cast<> here because we do not wish
3031 // to have a dependency of Type.h on Stmt.h/Expr.h.
3032 return (Expr*) SizeExpr;
3033 }
3034
3035 SourceRange getBracketsRange() const { return Brackets; }
3036 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3037 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3038
3039 bool isSugared() const { return false; }
3040 QualType desugar() const { return QualType(this, 0); }
3041
3042 static bool classof(const Type *T) {
3043 return T->getTypeClass() == VariableArray;
3044 }
3045
3046 void Profile(llvm::FoldingSetNodeID &ID) {
3047 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3047)
;
3048 }
3049};
3050
3051/// Represents an array type in C++ whose size is a value-dependent expression.
3052///
3053/// For example:
3054/// \code
3055/// template<typename T, int Size>
3056/// class array {
3057/// T data[Size];
3058/// };
3059/// \endcode
3060///
3061/// For these types, we won't actually know what the array bound is
3062/// until template instantiation occurs, at which point this will
3063/// become either a ConstantArrayType or a VariableArrayType.
3064class DependentSizedArrayType : public ArrayType {
3065 friend class ASTContext; // ASTContext creates these.
3066
3067 const ASTContext &Context;
3068
3069 /// An assignment expression that will instantiate to the
3070 /// size of the array.
3071 ///
3072 /// The expression itself might be null, in which case the array
3073 /// type will have its size deduced from an initializer.
3074 Stmt *SizeExpr;
3075
3076 /// The range spanned by the left and right array brackets.
3077 SourceRange Brackets;
3078
3079 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3080 Expr *e, ArraySizeModifier sm, unsigned tq,
3081 SourceRange brackets);
3082
3083public:
3084 friend class StmtIteratorBase;
3085
3086 Expr *getSizeExpr() const {
3087 // We use C-style casts instead of cast<> here because we do not wish
3088 // to have a dependency of Type.h on Stmt.h/Expr.h.
3089 return (Expr*) SizeExpr;
3090 }
3091
3092 SourceRange getBracketsRange() const { return Brackets; }
3093 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3094 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3095
3096 bool isSugared() const { return false; }
3097 QualType desugar() const { return QualType(this, 0); }
3098
3099 static bool classof(const Type *T) {
3100 return T->getTypeClass() == DependentSizedArray;
3101 }
3102
3103 void Profile(llvm::FoldingSetNodeID &ID) {
3104 Profile(ID, Context, getElementType(),
3105 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3106 }
3107
3108 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3109 QualType ET, ArraySizeModifier SizeMod,
3110 unsigned TypeQuals, Expr *E);
3111};
3112
3113/// Represents an extended address space qualifier where the input address space
3114/// value is dependent. Non-dependent address spaces are not represented with a
3115/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3116///
3117/// For example:
3118/// \code
3119/// template<typename T, int AddrSpace>
3120/// class AddressSpace {
3121/// typedef T __attribute__((address_space(AddrSpace))) type;
3122/// }
3123/// \endcode
3124class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3125 friend class ASTContext;
3126
3127 const ASTContext &Context;
3128 Expr *AddrSpaceExpr;
3129 QualType PointeeType;
3130 SourceLocation loc;
3131
3132 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3133 QualType can, Expr *AddrSpaceExpr,
3134 SourceLocation loc);
3135
3136public:
3137 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3138 QualType getPointeeType() const { return PointeeType; }
3139 SourceLocation getAttributeLoc() const { return loc; }
3140
3141 bool isSugared() const { return false; }
3142 QualType desugar() const { return QualType(this, 0); }
3143
3144 static bool classof(const Type *T) {
3145 return T->getTypeClass() == DependentAddressSpace;
3146 }
3147
3148 void Profile(llvm::FoldingSetNodeID &ID) {
3149 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3150 }
3151
3152 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3153 QualType PointeeType, Expr *AddrSpaceExpr);
3154};
3155
3156/// Represents an extended vector type where either the type or size is
3157/// dependent.
3158///
3159/// For example:
3160/// \code
3161/// template<typename T, int Size>
3162/// class vector {
3163/// typedef T __attribute__((ext_vector_type(Size))) type;
3164/// }
3165/// \endcode
3166class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3167 friend class ASTContext;
3168
3169 const ASTContext &Context;
3170 Expr *SizeExpr;
3171
3172 /// The element type of the array.
3173 QualType ElementType;
3174
3175 SourceLocation loc;
3176
3177 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3178 QualType can, Expr *SizeExpr, SourceLocation loc);
3179
3180public:
3181 Expr *getSizeExpr() const { return SizeExpr; }
3182 QualType getElementType() const { return ElementType; }
3183 SourceLocation getAttributeLoc() const { return loc; }
3184
3185 bool isSugared() const { return false; }
3186 QualType desugar() const { return QualType(this, 0); }
3187
3188 static bool classof(const Type *T) {
3189 return T->getTypeClass() == DependentSizedExtVector;
3190 }
3191
3192 void Profile(llvm::FoldingSetNodeID &ID) {
3193 Profile(ID, Context, getElementType(), getSizeExpr());
3194 }
3195
3196 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3197 QualType ElementType, Expr *SizeExpr);
3198};
3199
3200
3201/// Represents a GCC generic vector type. This type is created using
3202/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3203/// bytes; or from an Altivec __vector or vector declaration.
3204/// Since the constructor takes the number of vector elements, the
3205/// client is responsible for converting the size into the number of elements.
3206class VectorType : public Type, public llvm::FoldingSetNode {
3207public:
3208 enum VectorKind {
3209 /// not a target-specific vector type
3210 GenericVector,
3211
3212 /// is AltiVec vector
3213 AltiVecVector,
3214
3215 /// is AltiVec 'vector Pixel'
3216 AltiVecPixel,
3217
3218 /// is AltiVec 'vector bool ...'
3219 AltiVecBool,
3220
3221 /// is ARM Neon vector
3222 NeonVector,
3223
3224 /// is ARM Neon polynomial vector
3225 NeonPolyVector
3226 };
3227
3228protected:
3229 friend class ASTContext; // ASTContext creates these.
3230
3231 /// The element type of the vector.
3232 QualType ElementType;
3233
3234 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3235 VectorKind vecKind);
3236
3237 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3238 QualType canonType, VectorKind vecKind);
3239
3240public:
3241 QualType getElementType() const { return ElementType; }
3242 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3243
3244 static bool isVectorSizeTooLarge(unsigned NumElements) {
3245 return NumElements > VectorTypeBitfields::MaxNumElements;
3246 }
3247
3248 bool isSugared() const { return false; }
3249 QualType desugar() const { return QualType(this, 0); }
3250
3251 VectorKind getVectorKind() const {
3252 return VectorKind(VectorTypeBits.VecKind);
3253 }
3254
3255 void Profile(llvm::FoldingSetNodeID &ID) {
3256 Profile(ID, getElementType(), getNumElements(),
3257 getTypeClass(), getVectorKind());
3258 }
3259
3260 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3261 unsigned NumElements, TypeClass TypeClass,
3262 VectorKind VecKind) {
3263 ID.AddPointer(ElementType.getAsOpaquePtr());
3264 ID.AddInteger(NumElements);
3265 ID.AddInteger(TypeClass);
3266 ID.AddInteger(VecKind);
3267 }
3268
3269 static bool classof(const Type *T) {
3270 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3271 }
3272};
3273
3274/// Represents a vector type where either the type or size is dependent.
3275////
3276/// For example:
3277/// \code
3278/// template<typename T, int Size>
3279/// class vector {
3280/// typedef T __attribute__((vector_size(Size))) type;
3281/// }
3282/// \endcode
3283class DependentVectorType : public Type, public llvm::FoldingSetNode {
3284 friend class ASTContext;
3285
3286 const ASTContext &Context;
3287 QualType ElementType;
3288 Expr *SizeExpr;
3289 SourceLocation Loc;
3290
3291 DependentVectorType(const ASTContext &Context, QualType ElementType,
3292 QualType CanonType, Expr *SizeExpr,
3293 SourceLocation Loc, VectorType::VectorKind vecKind);
3294
3295public:
3296 Expr *getSizeExpr() const { return SizeExpr; }
3297 QualType getElementType() const { return ElementType; }
3298 SourceLocation getAttributeLoc() const { return Loc; }
3299 VectorType::VectorKind getVectorKind() const {
3300 return VectorType::VectorKind(VectorTypeBits.VecKind);
3301 }
3302
3303 bool isSugared() const { return false; }
3304 QualType desugar() const { return QualType(this, 0); }
3305
3306 static bool classof(const Type *T) {
3307 return T->getTypeClass() == DependentVector;
3308 }
3309
3310 void Profile(llvm::FoldingSetNodeID &ID) {
3311 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3312 }
3313
3314 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3315 QualType ElementType, const Expr *SizeExpr,
3316 VectorType::VectorKind VecKind);
3317};
3318
3319/// ExtVectorType - Extended vector type. This type is created using
3320/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3321/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3322/// class enables syntactic extensions, like Vector Components for accessing
3323/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3324/// Shading Language).
3325class ExtVectorType : public VectorType {
3326 friend class ASTContext; // ASTContext creates these.
3327
3328 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3329 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3330
3331public:
3332 static int getPointAccessorIdx(char c) {
3333 switch (c) {
3334 default: return -1;
3335 case 'x': case 'r': return 0;
3336 case 'y': case 'g': return 1;
3337 case 'z': case 'b': return 2;
3338 case 'w': case 'a': return 3;
3339 }
3340 }
3341
3342 static int getNumericAccessorIdx(char c) {
3343 switch (c) {
3344 default: return -1;
3345 case '0': return 0;
3346 case '1': return 1;
3347 case '2': return 2;
3348 case '3': return 3;
3349 case '4': return 4;
3350 case '5': return 5;
3351 case '6': return 6;
3352 case '7': return 7;
3353 case '8': return 8;
3354 case '9': return 9;
3355 case 'A':
3356 case 'a': return 10;
3357 case 'B':
3358 case 'b': return 11;
3359 case 'C':
3360 case 'c': return 12;
3361 case 'D':
3362 case 'd': return 13;
3363 case 'E':
3364 case 'e': return 14;
3365 case 'F':
3366 case 'f': return 15;
3367 }
3368 }
3369
3370 static int getAccessorIdx(char c, bool isNumericAccessor) {
3371 if (isNumericAccessor)
3372 return getNumericAccessorIdx(c);
3373 else
3374 return getPointAccessorIdx(c);
3375 }
3376
3377 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3378 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3379 return unsigned(idx-1) < getNumElements();
3380 return false;
3381 }
3382
3383 bool isSugared() const { return false; }
3384 QualType desugar() const { return QualType(this, 0); }
3385
3386 static bool classof(const Type *T) {
3387 return T->getTypeClass() == ExtVector;
3388 }
3389};
3390
3391/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3392/// class of FunctionNoProtoType and FunctionProtoType.
3393class FunctionType : public Type {
3394 // The type returned by the function.
3395 QualType ResultType;
3396
3397public:
3398 /// Interesting information about a specific parameter that can't simply
3399 /// be reflected in parameter's type. This is only used by FunctionProtoType
3400 /// but is in FunctionType to make this class available during the
3401 /// specification of the bases of FunctionProtoType.
3402 ///
3403 /// It makes sense to model language features this way when there's some
3404 /// sort of parameter-specific override (such as an attribute) that
3405 /// affects how the function is called. For example, the ARC ns_consumed
3406 /// attribute changes whether a parameter is passed at +0 (the default)
3407 /// or +1 (ns_consumed). This must be reflected in the function type,
3408 /// but isn't really a change to the parameter type.
3409 ///
3410 /// One serious disadvantage of modelling language features this way is
3411 /// that they generally do not work with language features that attempt
3412 /// to destructure types. For example, template argument deduction will
3413 /// not be able to match a parameter declared as
3414 /// T (*)(U)
3415 /// against an argument of type
3416 /// void (*)(__attribute__((ns_consumed)) id)
3417 /// because the substitution of T=void, U=id into the former will
3418 /// not produce the latter.
3419 class ExtParameterInfo {
3420 enum {
3421 ABIMask = 0x0F,
3422 IsConsumed = 0x10,
3423 HasPassObjSize = 0x20,
3424 IsNoEscape = 0x40,
3425 };
3426 unsigned char Data = 0;
3427
3428 public:
3429 ExtParameterInfo() = default;
3430
3431 /// Return the ABI treatment of this parameter.
3432 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3433 ExtParameterInfo withABI(ParameterABI kind) const {
3434 ExtParameterInfo copy = *this;
3435 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3436 return copy;
3437 }
3438
3439 /// Is this parameter considered "consumed" by Objective-C ARC?
3440 /// Consumed parameters must have retainable object type.
3441 bool isConsumed() const { return (Data & IsConsumed); }
3442 ExtParameterInfo withIsConsumed(bool consumed) const {
3443 ExtParameterInfo copy = *this;
3444 if (consumed)
3445 copy.Data |= IsConsumed;
3446 else
3447 copy.Data &= ~IsConsumed;
3448 return copy;
3449 }
3450
3451 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3452 ExtParameterInfo withHasPassObjectSize() const {
3453 ExtParameterInfo Copy = *this;
3454 Copy.Data |= HasPassObjSize;
3455 return Copy;
3456 }
3457
3458 bool isNoEscape() const { return Data & IsNoEscape; }
3459 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3460 ExtParameterInfo Copy = *this;
3461 if (NoEscape)
3462 Copy.Data |= IsNoEscape;
3463 else
3464 Copy.Data &= ~IsNoEscape;
3465 return Copy;
3466 }
3467
3468 unsigned char getOpaqueValue() const { return Data; }
3469 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3470 ExtParameterInfo result;
3471 result.Data = data;
3472 return result;
3473 }
3474
3475 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3476 return lhs.Data == rhs.Data;
3477 }
3478
3479 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3480 return lhs.Data != rhs.Data;
3481 }
3482 };
3483
3484 /// A class which abstracts out some details necessary for
3485 /// making a call.
3486 ///
3487 /// It is not actually used directly for storing this information in
3488 /// a FunctionType, although FunctionType does currently use the
3489 /// same bit-pattern.
3490 ///
3491 // If you add a field (say Foo), other than the obvious places (both,
3492 // constructors, compile failures), what you need to update is
3493 // * Operator==
3494 // * getFoo
3495 // * withFoo
3496 // * functionType. Add Foo, getFoo.
3497 // * ASTContext::getFooType
3498 // * ASTContext::mergeFunctionTypes
3499 // * FunctionNoProtoType::Profile
3500 // * FunctionProtoType::Profile
3501 // * TypePrinter::PrintFunctionProto
3502 // * AST read and write
3503 // * Codegen
3504 class ExtInfo {
3505 friend class FunctionType;
3506
3507 // Feel free to rearrange or add bits, but if you go over 12,
3508 // you'll need to adjust both the Bits field below and
3509 // Type::FunctionTypeBitfields.
3510
3511 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3512 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3513 //
3514 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3515 enum { CallConvMask = 0x1F };
3516 enum { NoReturnMask = 0x20 };
3517 enum { ProducesResultMask = 0x40 };
3518 enum { NoCallerSavedRegsMask = 0x80 };
3519 enum { NoCfCheckMask = 0x800 };
3520 enum {
3521 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3522 NoCallerSavedRegsMask | NoCfCheckMask),
3523 RegParmOffset = 8
3524 }; // Assumed to be the last field
3525 uint16_t Bits = CC_C;
3526
3527 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3528
3529 public:
3530 // Constructor with no defaults. Use this when you know that you
3531 // have all the elements (when reading an AST file for example).
3532 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3533 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3534 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value"
) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3534, __PRETTY_FUNCTION__))
;
3535 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3536 (producesResult ? ProducesResultMask : 0) |
3537 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3538 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3539 (NoCfCheck ? NoCfCheckMask : 0);
3540 }
3541
3542 // Constructor with all defaults. Use when for example creating a
3543 // function known to use defaults.
3544 ExtInfo() = default;
3545
3546 // Constructor with just the calling convention, which is an important part
3547 // of the canonical type.
3548 ExtInfo(CallingConv CC) : Bits(CC) {}
3549
3550 bool getNoReturn() const { return Bits & NoReturnMask; }
3551 bool getProducesResult() const { return Bits & ProducesResultMask; }
3552 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3553 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3554 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3555
3556 unsigned getRegParm() const {
3557 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3558 if (RegParm > 0)
3559 --RegParm;
3560 return RegParm;
3561 }
3562
3563 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3564
3565 bool operator==(ExtInfo Other) const {
3566 return Bits == Other.Bits;
3567 }
3568 bool operator!=(ExtInfo Other) const {
3569 return Bits != Other.Bits;
3570 }
3571
3572 // Note that we don't have setters. That is by design, use
3573 // the following with methods instead of mutating these objects.
3574
3575 ExtInfo withNoReturn(bool noReturn) const {
3576 if (noReturn)
3577 return ExtInfo(Bits | NoReturnMask);
3578 else
3579 return ExtInfo(Bits & ~NoReturnMask);
3580 }
3581
3582 ExtInfo withProducesResult(bool producesResult) const {
3583 if (producesResult)
3584 return ExtInfo(Bits | ProducesResultMask);
3585 else
3586 return ExtInfo(Bits & ~ProducesResultMask);
3587 }
3588
3589 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3590 if (noCallerSavedRegs)
3591 return ExtInfo(Bits | NoCallerSavedRegsMask);
3592 else
3593 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3594 }
3595
3596 ExtInfo withNoCfCheck(bool noCfCheck) const {
3597 if (noCfCheck)
3598 return ExtInfo(Bits | NoCfCheckMask);
3599 else
3600 return ExtInfo(Bits & ~NoCfCheckMask);
3601 }
3602
3603 ExtInfo withRegParm(unsigned RegParm) const {
3604 assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast
<void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3604, __PRETTY_FUNCTION__))
;
3605 return ExtInfo((Bits & ~RegParmMask) |
3606 ((RegParm + 1) << RegParmOffset));
3607 }
3608
3609 ExtInfo withCallingConv(CallingConv cc) const {
3610 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3611 }
3612
3613 void Profile(llvm::FoldingSetNodeID &ID) const {
3614 ID.AddInteger(Bits);
3615 }
3616 };
3617
3618 /// A simple holder for a QualType representing a type in an
3619 /// exception specification. Unfortunately needed by FunctionProtoType
3620 /// because TrailingObjects cannot handle repeated types.
3621 struct ExceptionType { QualType Type; };
3622
3623 /// A simple holder for various uncommon bits which do not fit in
3624 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3625 /// alignment of subsequent objects in TrailingObjects. You must update
3626 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3627 struct alignas(void *) FunctionTypeExtraBitfields {
3628 /// The number of types in the exception specification.
3629 /// A whole unsigned is not needed here and according to
3630 /// [implimits] 8 bits would be enough here.
3631 unsigned NumExceptionType;
3632 };
3633
3634protected:
3635 FunctionType(TypeClass tc, QualType res,
3636 QualType Canonical, bool Dependent,
3637 bool InstantiationDependent,
3638 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3639 ExtInfo Info)
3640 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3641 ContainsUnexpandedParameterPack),
3642 ResultType(res) {
3643 FunctionTypeBits.ExtInfo = Info.Bits;
3644 }
3645
3646 Qualifiers getFastTypeQuals() const {
3647 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3648 }
3649
3650public:
3651 QualType getReturnType() const { return ResultType; }
3652
3653 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3654 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3655
3656 /// Determine whether this function type includes the GNU noreturn
3657 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3658 /// type.
3659 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3660
3661 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3662 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3663
3664 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3665 "Const, volatile and restrict are assumed to be a subset of "
3666 "the fast qualifiers.");
3667
3668 bool isConst() const { return getFastTypeQuals().hasConst(); }
3669 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3670 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3671
3672 /// Determine the type of an expression that calls a function of
3673 /// this type.
3674 QualType getCallResultType(const ASTContext &Context) const {
3675 return getReturnType().getNonLValueExprType(Context);
3676 }
3677
3678 static StringRef getNameForCallConv(CallingConv CC);
3679
3680 static bool classof(const Type *T) {
3681 return T->getTypeClass() == FunctionNoProto ||
3682 T->getTypeClass() == FunctionProto;
3683 }
3684};
3685
3686/// Represents a K&R-style 'int foo()' function, which has
3687/// no information available about its arguments.
3688class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3689 friend class ASTContext; // ASTContext creates these.
3690
3691 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3692 : FunctionType(FunctionNoProto, Result, Canonical,
3693 /*Dependent=*/false, /*InstantiationDependent=*/false,
3694 Result->isVariablyModifiedType(),
3695 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3696
3697public:
3698 // No additional state past what FunctionType provides.
3699
3700 bool isSugared() const { return false; }
3701 QualType desugar() const { return QualType(this, 0); }
3702
3703 void Profile(llvm::FoldingSetNodeID &ID) {
3704 Profile(ID, getReturnType(), getExtInfo());
3705 }
3706
3707 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3708 ExtInfo Info) {
3709 Info.Profile(ID);
3710 ID.AddPointer(ResultType.getAsOpaquePtr());
3711 }
3712
3713 static bool classof(const Type *T) {
3714 return T->getTypeClass() == FunctionNoProto;
3715 }
3716};
3717
3718/// Represents a prototype with parameter type info, e.g.
3719/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3720/// parameters, not as having a single void parameter. Such a type can have
3721/// an exception specification, but this specification is not part of the
3722/// canonical type. FunctionProtoType has several trailing objects, some of
3723/// which optional. For more information about the trailing objects see
3724/// the first comment inside FunctionProtoType.
3725class FunctionProtoType final
3726 : public FunctionType,
3727 public llvm::FoldingSetNode,
3728 private llvm::TrailingObjects<
3729 FunctionProtoType, QualType, FunctionType::FunctionTypeExtraBitfields,
3730 FunctionType::ExceptionType, Expr *, FunctionDecl *,
3731 FunctionType::ExtParameterInfo, Qualifiers> {
3732 friend class ASTContext; // ASTContext creates these.
3733 friend TrailingObjects;
3734
3735 // FunctionProtoType is followed by several trailing objects, some of
3736 // which optional. They are in order:
3737 //
3738 // * An array of getNumParams() QualType holding the parameter types.
3739 // Always present. Note that for the vast majority of FunctionProtoType,
3740 // these will be the only trailing objects.
3741 //
3742 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3743 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3744 // a single FunctionTypeExtraBitfields. Present if and only if
3745 // hasExtraBitfields() is true.
3746 //
3747 // * Optionally exactly one of:
3748 // * an array of getNumExceptions() ExceptionType,
3749 // * a single Expr *,
3750 // * a pair of FunctionDecl *,
3751 // * a single FunctionDecl *
3752 // used to store information about the various types of exception
3753 // specification. See getExceptionSpecSize for the details.
3754 //
3755 // * Optionally an array of getNumParams() ExtParameterInfo holding
3756 // an ExtParameterInfo for each of the parameters. Present if and
3757 // only if hasExtParameterInfos() is true.
3758 //
3759 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3760 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3761 // if hasExtQualifiers() is true.
3762 //
3763 // The optional FunctionTypeExtraBitfields has to be before the data
3764 // related to the exception specification since it contains the number
3765 // of exception types.
3766 //
3767 // We put the ExtParameterInfos last. If all were equal, it would make
3768 // more sense to put these before the exception specification, because
3769 // it's much easier to skip past them compared to the elaborate switch
3770 // required to skip the exception specification. However, all is not
3771 // equal; ExtParameterInfos are used to model very uncommon features,
3772 // and it's better not to burden the more common paths.
3773
3774public:
3775 /// Holds information about the various types of exception specification.
3776 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3777 /// used to group together the various bits of information about the
3778 /// exception specification.
3779 struct ExceptionSpecInfo {
3780 /// The kind of exception specification this is.
3781 ExceptionSpecificationType Type = EST_None;
3782
3783 /// Explicitly-specified list of exception types.
3784 ArrayRef<QualType> Exceptions;
3785
3786 /// Noexcept expression, if this is a computed noexcept specification.
3787 Expr *NoexceptExpr = nullptr;
3788
3789 /// The function whose exception specification this is, for
3790 /// EST_Unevaluated and EST_Uninstantiated.
3791 FunctionDecl *SourceDecl = nullptr;
3792
3793 /// The function template whose exception specification this is instantiated
3794 /// from, for EST_Uninstantiated.
3795 FunctionDecl *SourceTemplate = nullptr;
3796
3797 ExceptionSpecInfo() = default;
3798
3799 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3800 };
3801
3802 /// Extra information about a function prototype. ExtProtoInfo is not
3803 /// stored as such in FunctionProtoType but is used to group together
3804 /// the various bits of extra information about a function prototype.
3805 struct ExtProtoInfo {
3806 FunctionType::ExtInfo ExtInfo;
3807 bool Variadic : 1;
3808 bool HasTrailingReturn : 1;
3809 Qualifiers TypeQuals;
3810 RefQualifierKind RefQualifier = RQ_None;
3811 ExceptionSpecInfo ExceptionSpec;
3812 const ExtParameterInfo *ExtParameterInfos = nullptr;
3813
3814 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3815
3816 ExtProtoInfo(CallingConv CC)
3817 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3818
3819 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3820 ExtProtoInfo Result(*this);
3821 Result.ExceptionSpec = ESI;
3822 return Result;
3823 }
3824 };
3825
3826private:
3827 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3828 return getNumParams();
3829 }
3830
3831 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3832 return hasExtraBitfields();
3833 }
3834
3835 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3836 return getExceptionSpecSize().NumExceptionType;
3837 }
3838
3839 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
3840 return getExceptionSpecSize().NumExprPtr;
3841 }
3842
3843 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
3844 return getExceptionSpecSize().NumFunctionDeclPtr;
3845 }
3846
3847 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
3848 return hasExtParameterInfos() ? getNumParams() : 0;
3849 }
3850
3851 /// Determine whether there are any argument types that
3852 /// contain an unexpanded parameter pack.
3853 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3854 unsigned numArgs) {
3855 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3856 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3857 return true;
3858
3859 return false;
3860 }
3861
3862 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3863 QualType canonical, const ExtProtoInfo &epi);
3864
3865 /// This struct is returned by getExceptionSpecSize and is used to
3866 /// translate an ExceptionSpecificationType to the number and kind
3867 /// of trailing objects related to the exception specification.
3868 struct ExceptionSpecSizeHolder {
3869 unsigned NumExceptionType;
3870 unsigned NumExprPtr;
3871 unsigned NumFunctionDeclPtr;
3872 };
3873
3874 /// Return the number and kind of trailing objects
3875 /// related to the exception specification.
3876 static ExceptionSpecSizeHolder
3877 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
3878 switch (EST) {
3879 case EST_None:
3880 case EST_DynamicNone:
3881 case EST_MSAny:
3882 case EST_BasicNoexcept:
3883 case EST_Unparsed:
3884 case EST_NoThrow:
3885 return {0, 0, 0};
3886
3887 case EST_Dynamic:
3888 return {NumExceptions, 0, 0};
3889
3890 case EST_DependentNoexcept:
3891 case EST_NoexceptFalse:
3892 case EST_NoexceptTrue:
3893 return {0, 1, 0};
3894
3895 case EST_Uninstantiated:
3896 return {0, 0, 2};
3897
3898 case EST_Unevaluated:
3899 return {0, 0, 1};
3900 }
3901 llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3901)
;
3902 }
3903
3904 /// Return the number and kind of trailing objects
3905 /// related to the exception specification.
3906 ExceptionSpecSizeHolder getExceptionSpecSize() const {
3907 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
3908 }
3909
3910 /// Whether the trailing FunctionTypeExtraBitfields is present.
3911 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
3912 // If the exception spec type is EST_Dynamic then we have > 0 exception
3913 // types and the exact number is stored in FunctionTypeExtraBitfields.
3914 return EST == EST_Dynamic;
3915 }
3916
3917 /// Whether the trailing FunctionTypeExtraBitfields is present.
3918 bool hasExtraBitfields() const {
3919 return hasExtraBitfields(getExceptionSpecType());
3920 }
3921
3922 bool hasExtQualifiers() const {
3923 return FunctionTypeBits.HasExtQuals;
3924 }
3925
3926public:
3927 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
3928
3929 QualType getParamType(unsigned i) const {
3930 assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index")
? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3930, __PRETTY_FUNCTION__))
;
3931 return param_type_begin()[i];
3932 }
3933
3934 ArrayRef<QualType> getParamTypes() const {
3935 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3936 }
3937
3938 ExtProtoInfo getExtProtoInfo() const {
3939 ExtProtoInfo EPI;
3940 EPI.ExtInfo = getExtInfo();
3941 EPI.Variadic = isVariadic();
3942 EPI.HasTrailingReturn = hasTrailingReturn();
3943 EPI.ExceptionSpec.Type = getExceptionSpecType();
3944 EPI.TypeQuals = getMethodQuals();
3945 EPI.RefQualifier = getRefQualifier();
3946 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3947 EPI.ExceptionSpec.Exceptions = exceptions();
3948 } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) {
3949 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3950 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3951 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3952 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3953 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3954 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3955 }
3956 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
3957 return EPI;
3958 }
3959
3960 /// Get the kind of exception specification on this function.
3961 ExceptionSpecificationType getExceptionSpecType() const {
3962 return static_cast<ExceptionSpecificationType>(
3963 FunctionTypeBits.ExceptionSpecType);
3964 }
3965
3966 /// Return whether this function has any kind of exception spec.
3967 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
3968
3969 /// Return whether this function has a dynamic (throw) exception spec.
3970 bool hasDynamicExceptionSpec() const {
3971 return isDynamicExceptionSpec(getExceptionSpecType());
3972 }
3973
3974 /// Return whether this function has a noexcept exception spec.
3975 bool hasNoexceptExceptionSpec() const {
3976 return isNoexceptExceptionSpec(getExceptionSpecType());
3977 }
3978
3979 /// Return whether this function has a dependent exception spec.
3980 bool hasDependentExceptionSpec() const;
3981
3982 /// Return whether this function has an instantiation-dependent exception
3983 /// spec.
3984 bool hasInstantiationDependentExceptionSpec() const;
3985
3986 /// Return the number of types in the exception specification.
3987 unsigned getNumExceptions() const {
3988 return getExceptionSpecType() == EST_Dynamic
3989 ? getTrailingObjects<FunctionTypeExtraBitfields>()
3990 ->NumExceptionType
3991 : 0;
3992 }
3993
3994 /// Return the ith exception type, where 0 <= i < getNumExceptions().
3995 QualType getExceptionType(unsigned i) const {
3996 assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3996, __PRETTY_FUNCTION__))
;
3997 return exception_begin()[i];
3998 }
3999
4000 /// Return the expression inside noexcept(expression), or a null pointer
4001 /// if there is none (because the exception spec is not of this form).
4002 Expr *getNoexceptExpr() const {
4003 if (!isComputedNoexcept(getExceptionSpecType()))
4004 return nullptr;
4005 return *getTrailingObjects<Expr *>();
4006 }
4007
4008 /// If this function type has an exception specification which hasn't
4009 /// been determined yet (either because it has not been evaluated or because
4010 /// it has not been instantiated), this is the function whose exception
4011 /// specification is represented by this type.
4012 FunctionDecl *getExceptionSpecDecl() const {
4013 if (getExceptionSpecType() != EST_Uninstantiated &&
4014 getExceptionSpecType() != EST_Unevaluated)
4015 return nullptr;
4016 return getTrailingObjects<FunctionDecl *>()[0];
4017 }
4018
4019 /// If this function type has an uninstantiated exception
4020 /// specification, this is the function whose exception specification
4021 /// should be instantiated to find the exception specification for
4022 /// this type.
4023 FunctionDecl *getExceptionSpecTemplate() const {
4024 if (getExceptionSpecType() != EST_Uninstantiated)
4025 return nullptr;
4026 return getTrailingObjects<FunctionDecl *>()[1];
4027 }
4028
4029 /// Determine whether this function type has a non-throwing exception
4030 /// specification.
4031 CanThrowResult canThrow() const;
4032
4033 /// Determine whether this function type has a non-throwing exception
4034 /// specification. If this depends on template arguments, returns
4035 /// \c ResultIfDependent.
4036 bool isNothrow(bool ResultIfDependent = false) const {
4037 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4038 }
4039
4040 /// Whether this function prototype is variadic.
4041 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4042
4043 /// Determines whether this function prototype contains a
4044 /// parameter pack at the end.
4045 ///
4046 /// A function template whose last parameter is a parameter pack can be
4047 /// called with an arbitrary number of arguments, much like a variadic
4048 /// function.
4049 bool isTemplateVariadic() const;
4050
4051 /// Whether this function prototype has a trailing return type.
4052 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4053
4054 Qualifiers getMethodQuals() const {
4055 if (hasExtQualifiers())
4056 return *getTrailingObjects<Qualifiers>();
4057 else
4058 return getFastTypeQuals();
4059 }
4060
4061 /// Retrieve the ref-qualifier associated with this function type.
4062 RefQualifierKind getRefQualifier() const {
4063 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4064 }
4065
4066 using param_type_iterator = const QualType *;
4067 using param_type_range = llvm::iterator_range<param_type_iterator>;
4068
4069 param_type_range param_types() const {
4070 return param_type_range(param_type_begin(), param_type_end());
4071 }
4072
4073 param_type_iterator param_type_begin() const {
4074 return getTrailingObjects<QualType>();
4075 }
4076
4077 param_type_iterator param_type_end() const {
4078 return param_type_begin() + getNumParams();
4079 }
4080
4081 using exception_iterator = const QualType *;
4082
4083 ArrayRef<QualType> exceptions() const {
4084 return llvm::makeArrayRef(exception_begin(), exception_end());
4085 }
4086
4087 exception_iterator exception_begin() const {
4088 return reinterpret_cast<exception_iterator>(
4089 getTrailingObjects<ExceptionType>());
4090 }
4091
4092 exception_iterator exception_end() const {
4093 return exception_begin() + getNumExceptions();
4094 }
4095
4096 /// Is there any interesting extra information for any of the parameters
4097 /// of this function type?
4098 bool hasExtParameterInfos() const {
4099 return FunctionTypeBits.HasExtParameterInfos;
4100 }
4101
4102 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4103 assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail
("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4103, __PRETTY_FUNCTION__))
;
4104 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4105 getNumParams());
4106 }
4107
4108 /// Return a pointer to the beginning of the array of extra parameter
4109 /// information, if present, or else null if none of the parameters
4110 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4111 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4112 if (!hasExtParameterInfos())
4113 return nullptr;
4114 return getTrailingObjects<ExtParameterInfo>();
4115 }
4116
4117 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4118 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4118, __PRETTY_FUNCTION__))
;
4119 if (hasExtParameterInfos())
4120 return getTrailingObjects<ExtParameterInfo>()[I];
4121 return ExtParameterInfo();
4122 }
4123
4124 ParameterABI getParameterABI(unsigned I) const {
4125 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4125, __PRETTY_FUNCTION__))
;
4126 if (hasExtParameterInfos())
4127 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4128 return ParameterABI::Ordinary;
4129 }
4130
4131 bool isParamConsumed(unsigned I) const {
4132 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4132, __PRETTY_FUNCTION__))
;
4133 if (hasExtParameterInfos())
4134 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4135 return false;
4136 }
4137
4138 bool isSugared() const { return false; }
4139 QualType desugar() const { return QualType(this, 0); }
4140
4141 void printExceptionSpecification(raw_ostream &OS,
4142 const PrintingPolicy &Policy) const;
4143
4144 static bool classof(const Type *T) {
4145 return T->getTypeClass() == FunctionProto;
4146 }
4147
4148 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4149 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4150 param_type_iterator ArgTys, unsigned NumArgs,
4151 const ExtProtoInfo &EPI, const ASTContext &Context,
4152 bool Canonical);
4153};
4154
4155/// Represents the dependent type named by a dependently-scoped
4156/// typename using declaration, e.g.
4157/// using typename Base<T>::foo;
4158///
4159/// Template instantiation turns these into the underlying type.
4160class UnresolvedUsingType : public Type {
4161 friend class ASTContext; // ASTContext creates these.
4162
4163 UnresolvedUsingTypenameDecl *Decl;
4164
4165 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4166 : Type(UnresolvedUsing, QualType(), true, true, false,
4167 /*ContainsUnexpandedParameterPack=*/false),
4168 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
4169
4170public:
4171 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4172
4173 bool isSugared() const { return false; }
4174 QualType desugar() const { return QualType(this, 0); }
4175
4176 static bool classof(const Type *T) {
4177 return T->getTypeClass() == UnresolvedUsing;
4178 }
4179
4180 void Profile(llvm::FoldingSetNodeID &ID) {
4181 return Profile(ID, Decl);
4182 }
4183
4184 static void Profile(llvm::FoldingSetNodeID &ID,
4185 UnresolvedUsingTypenameDecl *D) {
4186 ID.AddPointer(D);
4187 }
4188};
4189
4190class TypedefType : public Type {
4191 TypedefNameDecl *Decl;
4192
4193protected:
4194 friend class ASTContext; // ASTContext creates these.
4195
4196 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
4197 : Type(tc, can, can->isDependentType(),
4198 can->isInstantiationDependentType(),
4199 can->isVariablyModifiedType(),
4200 /*ContainsUnexpandedParameterPack=*/false),
4201 Decl(const_cast<TypedefNameDecl*>(D)) {
4202 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4202, __PRETTY_FUNCTION__))
;
4203 }
4204
4205public:
4206 TypedefNameDecl *getDecl() const { return Decl; }
4207
4208 bool isSugared() const { return true; }
4209 QualType desugar() const;
4210
4211 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4212};
4213
4214/// Sugar type that represents a type that was qualified by a qualifier written
4215/// as a macro invocation.
4216class MacroQualifiedType : public Type {
4217 friend class ASTContext; // ASTContext creates these.
4218
4219 QualType UnderlyingTy;
4220 const IdentifierInfo *MacroII;
4221
4222 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4223 const IdentifierInfo *MacroII)
4224 : Type(MacroQualified, CanonTy, UnderlyingTy->isDependentType(),
4225 UnderlyingTy->isInstantiationDependentType(),
4226 UnderlyingTy->isVariablyModifiedType(),
4227 UnderlyingTy->containsUnexpandedParameterPack()),
4228 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4229 assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4230, __PRETTY_FUNCTION__))
4230 "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4230, __PRETTY_FUNCTION__))
;
4231 }
4232
4233public:
4234 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4235 QualType getUnderlyingType() const { return UnderlyingTy; }
4236
4237 /// Return this attributed type's modified type with no qualifiers attached to
4238 /// it.
4239 QualType getModifiedType() const;
4240
4241 bool isSugared() const { return true; }
4242 QualType desugar() const;
4243
4244 static bool classof(const Type *T) {
4245 return T->getTypeClass() == MacroQualified;
4246 }
4247};
4248
4249/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4250class TypeOfExprType : public Type {
4251 Expr *TOExpr;
4252
4253protected:
4254 friend class ASTContext; // ASTContext creates these.
4255
4256 TypeOfExprType(Expr *E, QualType can = QualType());
4257
4258public:
4259 Expr *getUnderlyingExpr() const { return TOExpr; }
4260
4261 /// Remove a single level of sugar.
4262 QualType desugar() const;
4263
4264 /// Returns whether this type directly provides sugar.
4265 bool isSugared() const;
4266
4267 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4268};
4269
4270/// Internal representation of canonical, dependent
4271/// `typeof(expr)` types.
4272///
4273/// This class is used internally by the ASTContext to manage
4274/// canonical, dependent types, only. Clients will only see instances
4275/// of this class via TypeOfExprType nodes.
4276class DependentTypeOfExprType
4277 : public TypeOfExprType, public llvm::FoldingSetNode {
4278 const ASTContext &Context;
4279
4280public:
4281 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4282 : TypeOfExprType(E), Context(Context) {}
4283
4284 void Profile(llvm::FoldingSetNodeID &ID) {
4285 Profile(ID, Context, getUnderlyingExpr());
4286 }
4287
4288 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4289 Expr *E);
4290};
4291
4292/// Represents `typeof(type)`, a GCC extension.
4293class TypeOfType : public Type {
4294 friend class ASTContext; // ASTContext creates these.
4295
4296 QualType TOType;
4297
4298 TypeOfType(QualType T, QualType can)
4299 : Type(TypeOf, can, T->isDependentType(),
4300 T->isInstantiationDependentType(),
4301 T->isVariablyModifiedType(),
4302 T->containsUnexpandedParameterPack()),
4303 TOType(T) {
4304 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4304, __PRETTY_FUNCTION__))
;
4305 }
4306
4307public:
4308 QualType getUnderlyingType() const { return TOType; }
4309
4310 /// Remove a single level of sugar.
4311 QualType desugar() const { return getUnderlyingType(); }
4312
4313 /// Returns whether this type directly provides sugar.
4314 bool isSugared() const { return true; }
4315
4316 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4317};
4318
4319/// Represents the type `decltype(expr)` (C++11).
4320class DecltypeType : public Type {
4321 Expr *E;
4322 QualType UnderlyingType;
4323
4324protected:
4325 friend class ASTContext; // ASTContext creates these.
4326
4327 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4328
4329public:
4330 Expr *getUnderlyingExpr() const { return E; }
4331 QualType getUnderlyingType() const { return UnderlyingType; }
4332
4333 /// Remove a single level of sugar.
4334 QualType desugar() const;
4335
4336 /// Returns whether this type directly provides sugar.
4337 bool isSugared() const;
4338
4339 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4340};
4341
4342/// Internal representation of canonical, dependent
4343/// decltype(expr) types.
4344///
4345/// This class is used internally by the ASTContext to manage
4346/// canonical, dependent types, only. Clients will only see instances
4347/// of this class via DecltypeType nodes.
4348class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4349 const ASTContext &Context;
4350
4351public:
4352 DependentDecltypeType(const ASTContext &Context, Expr *E);
4353
4354 void Profile(llvm::FoldingSetNodeID &ID) {
4355 Profile(ID, Context, getUnderlyingExpr());
4356 }
4357
4358 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4359 Expr *E);
4360};
4361
4362/// A unary type transform, which is a type constructed from another.
4363class UnaryTransformType : public Type {
4364public:
4365 enum UTTKind {
4366 EnumUnderlyingType
4367 };
4368
4369private:
4370 /// The untransformed type.
4371 QualType BaseType;
4372
4373 /// The transformed type if not dependent, otherwise the same as BaseType.
4374 QualType UnderlyingType;
4375
4376 UTTKind UKind;
4377
4378protected:
4379 friend class ASTContext;
4380
4381 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4382 QualType CanonicalTy);
4383
4384public:
4385 bool isSugared() const { return !isDependentType(); }
4386 QualType desugar() const { return UnderlyingType; }
4387
4388 QualType getUnderlyingType() const { return UnderlyingType; }
4389 QualType getBaseType() const { return BaseType; }
4390
4391 UTTKind getUTTKind() const { return UKind; }
4392
4393 static bool classof(const Type *T) {
4394 return T->getTypeClass() == UnaryTransform;
4395 }
4396};
4397
4398/// Internal representation of canonical, dependent
4399/// __underlying_type(type) types.
4400///
4401/// This class is used internally by the ASTContext to manage
4402/// canonical, dependent types, only. Clients will only see instances
4403/// of this class via UnaryTransformType nodes.
4404class DependentUnaryTransformType : public UnaryTransformType,
4405 public llvm::FoldingSetNode {
4406public:
4407 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4408 UTTKind UKind);
4409
4410 void Profile(llvm::FoldingSetNodeID &ID) {
4411 Profile(ID, getBaseType(), getUTTKind());
4412 }
4413
4414 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4415 UTTKind UKind) {
4416 ID.AddPointer(BaseType.getAsOpaquePtr());
4417 ID.AddInteger((unsigned)UKind);
4418 }
4419};
4420
4421class TagType : public Type {
4422 friend class ASTReader;
4423
4424 /// Stores the TagDecl associated with this type. The decl may point to any
4425 /// TagDecl that declares the entity.
4426 TagDecl *decl;
4427
4428protected:
4429 TagType(TypeClass TC, const TagDecl *D, QualType can);
4430
4431public:
4432 TagDecl *getDecl() const;
4433
4434 /// Determines whether this type is in the process of being defined.
4435 bool isBeingDefined() const;
4436
4437 static bool classof(const Type *T) {
4438 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4439 }
4440};
4441
4442/// A helper class that allows the use of isa/cast/dyncast
4443/// to detect TagType objects of structs/unions/classes.
4444class RecordType : public TagType {
4445protected:
4446 friend class ASTContext; // ASTContext creates these.
4447
4448 explicit RecordType(const RecordDecl *D)
4449 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4450 explicit RecordType(TypeClass TC, RecordDecl *D)
4451 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4452
4453public:
4454 RecordDecl *getDecl() const {
4455 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4456 }
4457
4458 /// Recursively check all fields in the record for const-ness. If any field
4459 /// is declared const, return true. Otherwise, return false.
4460 bool hasConstFields() const;
4461
4462 bool isSugared() const { return false; }
4463 QualType desugar() const { return QualType(this, 0); }
4464
4465 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4466};
4467
4468/// A helper class that allows the use of isa/cast/dyncast
4469/// to detect TagType objects of enums.
4470class EnumType : public TagType {
4471 friend class ASTContext; // ASTContext creates these.
4472
4473 explicit EnumType(const EnumDecl *D)
4474 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4475
4476public:
4477 EnumDecl *getDecl() const {
4478 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4479 }
4480
4481 bool isSugared() const { return false; }
4482 QualType desugar() const { return QualType(this, 0); }
4483
4484 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4485};
4486
4487/// An attributed type is a type to which a type attribute has been applied.
4488///
4489/// The "modified type" is the fully-sugared type to which the attributed
4490/// type was applied; generally it is not canonically equivalent to the
4491/// attributed type. The "equivalent type" is the minimally-desugared type
4492/// which the type is canonically equivalent to.
4493///
4494/// For example, in the following attributed type:
4495/// int32_t __attribute__((vector_size(16)))
4496/// - the modified type is the TypedefType for int32_t
4497/// - the equivalent type is VectorType(16, int32_t)
4498/// - the canonical type is VectorType(16, int)
4499class AttributedType : public Type, public llvm::FoldingSetNode {
4500public:
4501 using Kind = attr::Kind;
4502
4503private:
4504 friend class ASTContext; // ASTContext creates these
4505
4506 QualType ModifiedType;
4507 QualType EquivalentType;
4508
4509 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4510 QualType equivalent)
4511 : Type(Attributed, canon, equivalent->isDependentType(),
4512 equivalent->isInstantiationDependentType(),
4513 equivalent->isVariablyModifiedType(),
4514 equivalent->containsUnexpandedParameterPack()),
4515 ModifiedType(modified), EquivalentType(equivalent) {
4516 AttributedTypeBits.AttrKind = attrKind;
4517 }
4518
4519public:
4520 Kind getAttrKind() const {
4521 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4522 }
4523
4524 QualType getModifiedType() const { return ModifiedType; }
4525 QualType getEquivalentType() const { return EquivalentType; }
4526
4527 bool isSugared() const { return true; }
4528 QualType desugar() const { return getEquivalentType(); }
4529
4530 /// Does this attribute behave like a type qualifier?
4531 ///
4532 /// A type qualifier adjusts a type to provide specialized rules for
4533 /// a specific object, like the standard const and volatile qualifiers.
4534 /// This includes attributes controlling things like nullability,
4535 /// address spaces, and ARC ownership. The value of the object is still
4536 /// largely described by the modified type.
4537 ///
4538 /// In contrast, many type attributes "rewrite" their modified type to
4539 /// produce a fundamentally different type, not necessarily related in any
4540 /// formalizable way to the original type. For example, calling convention
4541 /// and vector attributes are not simple type qualifiers.
4542 ///
4543 /// Type qualifiers are often, but not always, reflected in the canonical
4544 /// type.
4545 bool isQualifier() const;
4546
4547 bool isMSTypeSpec() const;
4548
4549 bool isCallingConv() const;
4550
4551 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4552
4553 /// Retrieve the attribute kind corresponding to the given
4554 /// nullability kind.
4555 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4556 switch (kind) {
4557 case NullabilityKind::NonNull:
4558 return attr::TypeNonNull;
4559
4560 case NullabilityKind::Nullable:
4561 return attr::TypeNullable;
4562
4563 case NullabilityKind::Unspecified:
4564 return attr::TypeNullUnspecified;
4565 }
4566 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4566)
;
4567 }
4568
4569 /// Strip off the top-level nullability annotation on the given
4570 /// type, if it's there.
4571 ///
4572 /// \param T The type to strip. If the type is exactly an
4573 /// AttributedType specifying nullability (without looking through
4574 /// type sugar), the nullability is returned and this type changed
4575 /// to the underlying modified type.
4576 ///
4577 /// \returns the top-level nullability, if present.
4578 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4579
4580 void Profile(llvm::FoldingSetNodeID &ID) {
4581 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4582 }
4583
4584 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4585 QualType modified, QualType equivalent) {
4586 ID.AddInteger(attrKind);
4587 ID.AddPointer(modified.getAsOpaquePtr());
4588 ID.AddPointer(equivalent.getAsOpaquePtr());
4589 }
4590
4591 static bool classof(const Type *T) {
4592 return T->getTypeClass() == Attributed;
4593 }
4594};
4595
4596class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4597 friend class ASTContext; // ASTContext creates these
4598
4599 // Helper data collector for canonical types.
4600 struct CanonicalTTPTInfo {
4601 unsigned Depth : 15;
4602 unsigned ParameterPack : 1;
4603 unsigned Index : 16;
4604 };
4605
4606 union {
4607 // Info for the canonical type.
4608 CanonicalTTPTInfo CanTTPTInfo;
4609
4610 // Info for the non-canonical type.
4611 TemplateTypeParmDecl *TTPDecl;
4612 };
4613
4614 /// Build a non-canonical type.
4615 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4616 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4617 /*InstantiationDependent=*/true,
4618 /*VariablyModified=*/false,
4619 Canon->containsUnexpandedParameterPack()),
4620 TTPDecl(TTPDecl) {}
4621
4622 /// Build the canonical type.
4623 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4624 : Type(TemplateTypeParm, QualType(this, 0),
4625 /*Dependent=*/true,
4626 /*InstantiationDependent=*/true,
4627 /*VariablyModified=*/false, PP) {
4628 CanTTPTInfo.Depth = D;
4629 CanTTPTInfo.Index = I;
4630 CanTTPTInfo.ParameterPack = PP;
4631 }
4632
4633 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4634 QualType Can = getCanonicalTypeInternal();
4635 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4636 }
4637
4638public:
4639 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4640 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4641 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4642
4643 TemplateTypeParmDecl *getDecl() const {
4644 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4645 }
4646
4647 IdentifierInfo *getIdentifier() const;
4648
4649 bool isSugared() const { return false; }
4650 QualType desugar() const { return QualType(this, 0); }
4651
4652 void Profile(llvm::FoldingSetNodeID &ID) {
4653 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4654 }
4655
4656 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4657 unsigned Index, bool ParameterPack,
4658 TemplateTypeParmDecl *TTPDecl) {
4659 ID.AddInteger(Depth);
4660 ID.AddInteger(Index);
4661 ID.AddBoolean(ParameterPack);
4662 ID.AddPointer(TTPDecl);
4663 }
4664
4665 static bool classof(const Type *T) {
4666 return T->getTypeClass() == TemplateTypeParm;
4667 }
4668};
4669
4670/// Represents the result of substituting a type for a template
4671/// type parameter.
4672///
4673/// Within an instantiated template, all template type parameters have
4674/// been replaced with these. They are used solely to record that a
4675/// type was originally written as a template type parameter;
4676/// therefore they are never canonical.
4677class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4678 friend class ASTContext;
4679
4680 // The original type parameter.
4681 const TemplateTypeParmType *Replaced;
4682
4683 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4684 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4685 Canon->isInstantiationDependentType(),
4686 Canon->isVariablyModifiedType(),
4687 Canon->containsUnexpandedParameterPack()),
4688 Replaced(Param) {}
4689
4690public:
4691 /// Gets the template parameter that was substituted for.
4692 const TemplateTypeParmType *getReplacedParameter() const {
4693 return Replaced;
4694 }
4695
4696 /// Gets the type that was substituted for the template
4697 /// parameter.
4698 QualType getReplacementType() const {
4699 return getCanonicalTypeInternal();
4700 }
4701
4702 bool isSugared() const { return true; }
4703 QualType desugar() const { return getReplacementType(); }
4704
4705 void Profile(llvm::FoldingSetNodeID &ID) {
4706 Profile(ID, getReplacedParameter(), getReplacementType());
4707 }
4708
4709 static void Profile(llvm::FoldingSetNodeID &ID,
4710 const TemplateTypeParmType *Replaced,
4711 QualType Replacement) {
4712 ID.AddPointer(Replaced);
4713 ID.AddPointer(Replacement.getAsOpaquePtr());
4714 }
4715
4716 static bool classof(const Type *T) {
4717 return T->getTypeClass() == SubstTemplateTypeParm;
4718 }
4719};
4720
4721/// Represents the result of substituting a set of types for a template
4722/// type parameter pack.
4723///
4724/// When a pack expansion in the source code contains multiple parameter packs
4725/// and those parameter packs correspond to different levels of template
4726/// parameter lists, this type node is used to represent a template type
4727/// parameter pack from an outer level, which has already had its argument pack
4728/// substituted but that still lives within a pack expansion that itself
4729/// could not be instantiated. When actually performing a substitution into
4730/// that pack expansion (e.g., when all template parameters have corresponding
4731/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4732/// at the current pack substitution index.
4733class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4734 friend class ASTContext;
4735
4736 /// The original type parameter.
4737 const TemplateTypeParmType *Replaced;
4738
4739 /// A pointer to the set of template arguments that this
4740 /// parameter pack is instantiated with.
4741 const TemplateArgument *Arguments;
4742
4743 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4744 QualType Canon,
4745 const TemplateArgument &ArgPack);
4746
4747public:
4748 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4749
4750 /// Gets the template parameter that was substituted for.
4751 const TemplateTypeParmType *getReplacedParameter() const {
4752 return Replaced;
4753 }
4754
4755 unsigned getNumArgs() const {
4756 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4757 }
4758
4759 bool isSugared() const { return false; }
4760 QualType desugar() const { return QualType(this, 0); }
4761
4762 TemplateArgument getArgumentPack() const;
4763
4764 void Profile(llvm::FoldingSetNodeID &ID);
4765 static void Profile(llvm::FoldingSetNodeID &ID,
4766 const TemplateTypeParmType *Replaced,
4767 const TemplateArgument &ArgPack);
4768
4769 static bool classof(const Type *T) {
4770 return T->getTypeClass() == SubstTemplateTypeParmPack;
4771 }
4772};
4773
4774/// Common base class for placeholders for types that get replaced by
4775/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4776/// class template types, and (eventually) constrained type names from the C++
4777/// Concepts TS.
4778///
4779/// These types are usually a placeholder for a deduced type. However, before
4780/// the initializer is attached, or (usually) if the initializer is
4781/// type-dependent, there is no deduced type and the type is canonical. In
4782/// the latter case, it is also a dependent type.
4783class DeducedType : public Type {
4784protected:
4785 DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4786 bool IsInstantiationDependent, bool ContainsParameterPack)
4787 : Type(TC,
4788 // FIXME: Retain the sugared deduced type?
4789 DeducedAsType.isNull() ? QualType(this, 0)
4790 : DeducedAsType.getCanonicalType(),
4791 IsDependent, IsInstantiationDependent,
4792 /*VariablyModified=*/false, ContainsParameterPack) {
4793 if (!DeducedAsType.isNull()) {
4794 if (DeducedAsType->isDependentType())
4795 setDependent();
4796 if (DeducedAsType->isInstantiationDependentType())
4797 setInstantiationDependent();
4798 if (DeducedAsType->containsUnexpandedParameterPack())
4799 setContainsUnexpandedParameterPack();
4800 }
4801 }
4802
4803public:
4804 bool isSugared() const { return !isCanonicalUnqualified(); }
4805 QualType desugar() const { return getCanonicalTypeInternal(); }
4806
4807 /// Get the type deduced for this placeholder type, or null if it's
4808 /// either not been deduced or was deduced to a dependent type.
4809 QualType getDeducedType() const {
4810 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4811 }
4812 bool isDeduced() const {
4813 return !isCanonicalUnqualified() || isDependentType();
4814 }
4815
4816 static bool classof(const Type *T) {
4817 return T->getTypeClass() == Auto ||
4818 T->getTypeClass() == DeducedTemplateSpecialization;
4819 }
4820};
4821
4822/// Represents a C++11 auto or C++14 decltype(auto) type.
4823class AutoType : public DeducedType, public llvm::FoldingSetNode {
4824 friend class ASTContext; // ASTContext creates these
4825
4826 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4827 bool IsDeducedAsDependent, bool IsDeducedAsPack)
4828 : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4829 IsDeducedAsDependent, IsDeducedAsPack) {
4830 AutoTypeBits.Keyword = (unsigned)Keyword;
4831 }
4832
4833public:
4834 bool isDecltypeAuto() const {
4835 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4836 }
4837
4838 AutoTypeKeyword getKeyword() const {
4839 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4840 }
4841
4842 void Profile(llvm::FoldingSetNodeID &ID) {
4843 Profile(ID, getDeducedType(), getKeyword(), isDependentType(),
4844 containsUnexpandedParameterPack());
4845 }
4846
4847 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4848 AutoTypeKeyword Keyword, bool IsDependent, bool IsPack) {
4849 ID.AddPointer(Deduced.getAsOpaquePtr());
4850 ID.AddInteger((unsigned)Keyword);
4851 ID.AddBoolean(IsDependent);
4852 ID.AddBoolean(IsPack);
4853 }
4854
4855 static bool classof(const Type *T) {
4856 return T->getTypeClass() == Auto;
4857 }
4858};
4859
4860/// Represents a C++17 deduced template specialization type.
4861class DeducedTemplateSpecializationType : public DeducedType,
4862 public llvm::FoldingSetNode {
4863 friend class ASTContext; // ASTContext creates these
4864
4865 /// The name of the template whose arguments will be deduced.
4866 TemplateName Template;
4867
4868 DeducedTemplateSpecializationType(TemplateName Template,
4869 QualType DeducedAsType,
4870 bool IsDeducedAsDependent)
4871 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4872 IsDeducedAsDependent || Template.isDependent(),
4873 IsDeducedAsDependent || Template.isInstantiationDependent(),
4874 Template.containsUnexpandedParameterPack()),
4875 Template(Template) {}
4876
4877public:
4878 /// Retrieve the name of the template that we are deducing.
4879 TemplateName getTemplateName() const { return Template;}
4880
4881 void Profile(llvm::FoldingSetNodeID &ID) {
4882 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4883 }
4884
4885 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4886 QualType Deduced, bool IsDependent) {
4887 Template.Profile(ID);
4888 ID.AddPointer(Deduced.getAsOpaquePtr());
4889 ID.AddBoolean(IsDependent);
4890 }
4891
4892 static bool classof(const Type *T) {
4893 return T->getTypeClass() == DeducedTemplateSpecialization;
4894 }
4895};
4896
4897/// Represents a type template specialization; the template
4898/// must be a class template, a type alias template, or a template
4899/// template parameter. A template which cannot be resolved to one of
4900/// these, e.g. because it is written with a dependent scope
4901/// specifier, is instead represented as a
4902/// @c DependentTemplateSpecializationType.
4903///
4904/// A non-dependent template specialization type is always "sugar",
4905/// typically for a \c RecordType. For example, a class template
4906/// specialization type of \c vector<int> will refer to a tag type for
4907/// the instantiation \c std::vector<int, std::allocator<int>>
4908///
4909/// Template specializations are dependent if either the template or
4910/// any of the template arguments are dependent, in which case the
4911/// type may also be canonical.
4912///
4913/// Instances of this type are allocated with a trailing array of
4914/// TemplateArguments, followed by a QualType representing the
4915/// non-canonical aliased type when the template is a type alias
4916/// template.
4917class alignas(8) TemplateSpecializationType
4918 : public Type,
4919 public llvm::FoldingSetNode {
4920 friend class ASTContext; // ASTContext creates these
4921
4922 /// The name of the template being specialized. This is
4923 /// either a TemplateName::Template (in which case it is a
4924 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4925 /// TypeAliasTemplateDecl*), a
4926 /// TemplateName::SubstTemplateTemplateParmPack, or a
4927 /// TemplateName::SubstTemplateTemplateParm (in which case the
4928 /// replacement must, recursively, be one of these).
4929 TemplateName Template;
4930
4931 TemplateSpecializationType(TemplateName T,
4932 ArrayRef<TemplateArgument> Args,
4933 QualType Canon,
4934 QualType Aliased);
4935
4936public:
4937 /// Determine whether any of the given template arguments are dependent.
4938 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4939 bool &InstantiationDependent);
4940
4941 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4942 bool &InstantiationDependent);
4943
4944 /// True if this template specialization type matches a current
4945 /// instantiation in the context in which it is found.
4946 bool isCurrentInstantiation() const {
4947 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4948 }
4949
4950 /// Determine if this template specialization type is for a type alias
4951 /// template that has been substituted.
4952 ///
4953 /// Nearly every template specialization type whose template is an alias
4954 /// template will be substituted. However, this is not the case when
4955 /// the specialization contains a pack expansion but the template alias
4956 /// does not have a corresponding parameter pack, e.g.,
4957 ///
4958 /// \code
4959 /// template<typename T, typename U, typename V> struct S;
4960 /// template<typename T, typename U> using A = S<T, int, U>;
4961 /// template<typename... Ts> struct X {
4962 /// typedef A<Ts...> type; // not a type alias
4963 /// };
4964 /// \endcode
4965 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
4966
4967 /// Get the aliased type, if this is a specialization of a type alias
4968 /// template.
4969 QualType getAliasedType() const {
4970 assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization"
) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4970, __PRETTY_FUNCTION__))
;
4971 return *reinterpret_cast<const QualType*>(end());
4972 }
4973
4974 using iterator = const TemplateArgument *;
4975
4976 iterator begin() const { return getArgs(); }
4977 iterator end() const; // defined inline in TemplateBase.h
4978
4979 /// Retrieve the name of the template that we are specializing.
4980 TemplateName getTemplateName() const { return Template; }
4981
4982 /// Retrieve the template arguments.
4983 const TemplateArgument *getArgs() const {
4984 return reinterpret_cast<const TemplateArgument *>(this + 1);
4985 }
4986
4987 /// Retrieve the number of template arguments.
4988 unsigned getNumArgs() const {
4989 return TemplateSpecializationTypeBits.NumArgs;
4990 }
4991
4992 /// Retrieve a specific template argument as a type.
4993 /// \pre \c isArgType(Arg)
4994 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4995
4996 ArrayRef<TemplateArgument> template_arguments() const {
4997 return {getArgs(), getNumArgs()};
4998 }
4999
5000 bool isSugared() const {
5001 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5002 }
5003
5004 QualType desugar() const {
5005 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5006 }
5007
5008 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5009 Profile(ID, Template, template_arguments(), Ctx);
5010 if (isTypeAlias())
5011 getAliasedType().Profile(ID);
5012 }
5013
5014 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5015 ArrayRef<TemplateArgument> Args,
5016 const ASTContext &Context);
5017
5018 static bool classof(const Type *T) {
5019 return T->getTypeClass() == TemplateSpecialization;
5020 }
5021};
5022
5023/// Print a template argument list, including the '<' and '>'
5024/// enclosing the template arguments.
5025void printTemplateArgumentList(raw_ostream &OS,
5026 ArrayRef<TemplateArgument> Args,
5027 const PrintingPolicy &Policy);
5028
5029void printTemplateArgumentList(raw_ostream &OS,
5030 ArrayRef<TemplateArgumentLoc> Args,
5031 const PrintingPolicy &Policy);
5032
5033void printTemplateArgumentList(raw_ostream &OS,
5034 const TemplateArgumentListInfo &Args,
5035 const PrintingPolicy &Policy);
5036
5037/// The injected class name of a C++ class template or class
5038/// template partial specialization. Used to record that a type was
5039/// spelled with a bare identifier rather than as a template-id; the
5040/// equivalent for non-templated classes is just RecordType.
5041///
5042/// Injected class name types are always dependent. Template
5043/// instantiation turns these into RecordTypes.
5044///
5045/// Injected class name types are always canonical. This works
5046/// because it is impossible to compare an injected class name type
5047/// with the corresponding non-injected template type, for the same
5048/// reason that it is impossible to directly compare template
5049/// parameters from different dependent contexts: injected class name
5050/// types can only occur within the scope of a particular templated
5051/// declaration, and within that scope every template specialization
5052/// will canonicalize to the injected class name (when appropriate
5053/// according to the rules of the language).
5054class InjectedClassNameType : public Type {
5055 friend class ASTContext; // ASTContext creates these.
5056 friend class ASTNodeImporter;
5057 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5058 // currently suitable for AST reading, too much
5059 // interdependencies.
5060
5061 CXXRecordDecl *Decl;
5062
5063 /// The template specialization which this type represents.
5064 /// For example, in
5065 /// template <class T> class A { ... };
5066 /// this is A<T>, whereas in
5067 /// template <class X, class Y> class A<B<X,Y> > { ... };
5068 /// this is A<B<X,Y> >.
5069 ///
5070 /// It is always unqualified, always a template specialization type,
5071 /// and always dependent.
5072 QualType InjectedType;
5073
5074 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5075 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
5076 /*InstantiationDependent=*/true,
5077 /*VariablyModified=*/false,
5078 /*ContainsUnexpandedParameterPack=*/false),
5079 Decl(D), InjectedType(TST) {
5080 assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast<
void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5080, __PRETTY_FUNCTION__))
;
5081 assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail
("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5081, __PRETTY_FUNCTION__))
;
5082 assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail
("TST->isDependentType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5082, __PRETTY_FUNCTION__))
;
5083 }
5084
5085public:
5086 QualType getInjectedSpecializationType() const { return InjectedType; }
5087
5088 const TemplateSpecializationType *getInjectedTST() const {
5089 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5090 }
5091
5092 TemplateName getTemplateName() const {
5093 return getInjectedTST()->getTemplateName();
5094 }
5095
5096 CXXRecordDecl *getDecl() const;
5097
5098 bool isSugared() const { return false; }
5099 QualType desugar() const { return QualType(this, 0); }
5100
5101 static bool classof(const Type *T) {
5102 return T->getTypeClass() == InjectedClassName;
5103 }
5104};
5105
5106/// The kind of a tag type.
5107enum TagTypeKind {
5108 /// The "struct" keyword.
5109 TTK_Struct,
5110
5111 /// The "__interface" keyword.
5112 TTK_Interface,
5113
5114 /// The "union" keyword.
5115 TTK_Union,
5116
5117 /// The "class" keyword.
5118 TTK_Class,
5119
5120 /// The "enum" keyword.
5121 TTK_Enum
5122};
5123
5124/// The elaboration keyword that precedes a qualified type name or
5125/// introduces an elaborated-type-specifier.
5126enum ElaboratedTypeKeyword {
5127 /// The "struct" keyword introduces the elaborated-type-specifier.
5128 ETK_Struct,
5129
5130 /// The "__interface" keyword introduces the elaborated-type-specifier.
5131 ETK_Interface,
5132
5133 /// The "union" keyword introduces the elaborated-type-specifier.
5134 ETK_Union,
5135
5136 /// The "class" keyword introduces the elaborated-type-specifier.
5137 ETK_Class,
5138
5139 /// The "enum" keyword introduces the elaborated-type-specifier.
5140 ETK_Enum,
5141
5142 /// The "typename" keyword precedes the qualified type name, e.g.,
5143 /// \c typename T::type.
5144 ETK_Typename,
5145
5146 /// No keyword precedes the qualified type name.
5147 ETK_None
5148};
5149
5150/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5151/// The keyword in stored in the free bits of the base class.
5152/// Also provides a few static helpers for converting and printing
5153/// elaborated type keyword and tag type kind enumerations.
5154class TypeWithKeyword : public Type {
5155protected:
5156 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5157 QualType Canonical, bool Dependent,
5158 bool InstantiationDependent, bool VariablyModified,
5159 bool ContainsUnexpandedParameterPack)
5160 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
5161 ContainsUnexpandedParameterPack) {
5162 TypeWithKeywordBits.Keyword = Keyword;
5163 }
5164
5165public:
5166 ElaboratedTypeKeyword getKeyword() const {
5167 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5168 }
5169
5170 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5171 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5172
5173 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5174 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5175 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5176
5177 /// Converts a TagTypeKind into an elaborated type keyword.
5178 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5179
5180 /// Converts an elaborated type keyword into a TagTypeKind.
5181 /// It is an error to provide an elaborated type keyword
5182 /// which *isn't* a tag kind here.
5183 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5184
5185 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5186
5187 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5188
5189 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5190 return getKeywordName(getKeywordForTagTypeKind(Kind));
5191 }
5192
5193 class CannotCastToThisType {};
5194 static CannotCastToThisType classof(const Type *);
5195};
5196
5197/// Represents a type that was referred to using an elaborated type
5198/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5199/// or both.
5200///
5201/// This type is used to keep track of a type name as written in the
5202/// source code, including tag keywords and any nested-name-specifiers.
5203/// The type itself is always "sugar", used to express what was written
5204/// in the source code but containing no additional semantic information.
5205class ElaboratedType final
5206 : public TypeWithKeyword,
5207 public llvm::FoldingSetNode,
5208 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5209 friend class ASTContext; // ASTContext creates these
5210 friend TrailingObjects;
5211
5212 /// The nested name specifier containing the qualifier.
5213 NestedNameSpecifier *NNS;
5214
5215 /// The type that this qualified name refers to.
5216 QualType NamedType;
5217
5218 /// The (re)declaration of this tag type owned by this occurrence is stored
5219 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5220 /// it, or obtain a null pointer if there is none.
5221
5222 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5223 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5224 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5225 NamedType->isDependentType(),
5226 NamedType->isInstantiationDependentType(),
5227 NamedType->isVariablyModifiedType(),
5228 NamedType->containsUnexpandedParameterPack()),
5229 NNS(NNS), NamedType(NamedType) {
5230 ElaboratedTypeBits.HasOwnedTagDecl = false;
5231 if (OwnedTagDecl) {
5232 ElaboratedTypeBits.HasOwnedTagDecl = true;
5233 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5234 }
5235 assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
5236 "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
5237 "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
;
5238 }
5239
5240public:
5241 /// Retrieve the qualification on this type.
5242 NestedNameSpecifier *getQualifier() const { return NNS; }
5243
5244 /// Retrieve the type named by the qualified-id.
5245 QualType getNamedType() const { return NamedType; }
5246
5247 /// Remove a single level of sugar.
5248 QualType desugar() const { return getNamedType(); }
5249
5250 /// Returns whether this type directly provides sugar.
5251 bool isSugared() const { return true; }
5252
5253 /// Return the (re)declaration of this type owned by this occurrence of this
5254 /// type, or nullptr if there is none.
5255 TagDecl *getOwnedTagDecl() const {
5256 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5257 : nullptr;
5258 }
5259
5260 void Profile(llvm::FoldingSetNodeID &ID) {
5261 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5262 }
5263
5264 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5265 NestedNameSpecifier *NNS, QualType NamedType,
5266 TagDecl *OwnedTagDecl) {
5267 ID.AddInteger(Keyword);
5268 ID.AddPointer(NNS);
5269 NamedType.Profile(ID);
5270 ID.AddPointer(OwnedTagDecl);
5271 }
5272
5273 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5274};
5275
5276/// Represents a qualified type name for which the type name is
5277/// dependent.
5278///
5279/// DependentNameType represents a class of dependent types that involve a
5280/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5281/// name of a type. The DependentNameType may start with a "typename" (for a
5282/// typename-specifier), "class", "struct", "union", or "enum" (for a
5283/// dependent elaborated-type-specifier), or nothing (in contexts where we
5284/// know that we must be referring to a type, e.g., in a base class specifier).
5285/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5286/// mode, this type is used with non-dependent names to delay name lookup until
5287/// instantiation.
5288class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5289 friend class ASTContext; // ASTContext creates these
5290
5291 /// The nested name specifier containing the qualifier.
5292 NestedNameSpecifier *NNS;
5293
5294 /// The type that this typename specifier refers to.
5295 const IdentifierInfo *Name;
5296
5297 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5298 const IdentifierInfo *Name, QualType CanonType)
5299 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
5300 /*InstantiationDependent=*/true,
5301 /*VariablyModified=*/false,
5302 NNS->containsUnexpandedParameterPack()),
5303 NNS(NNS), Name(Name) {}
5304
5305public:
5306 /// Retrieve the qualification on this type.
5307 NestedNameSpecifier *getQualifier() const { return NNS; }
5308
5309 /// Retrieve the type named by the typename specifier as an identifier.
5310 ///
5311 /// This routine will return a non-NULL identifier pointer when the
5312 /// form of the original typename was terminated by an identifier,
5313 /// e.g., "typename T::type".
5314 const IdentifierInfo *getIdentifier() const {
5315 return Name;
5316 }
5317
5318 bool isSugared() const { return false; }
5319 QualType desugar() const { return QualType(this, 0); }
5320
5321 void Profile(llvm::FoldingSetNodeID &ID) {
5322 Profile(ID, getKeyword(), NNS, Name);
5323 }
5324
5325 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5326 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5327 ID.AddInteger(Keyword);
5328 ID.AddPointer(NNS);
5329 ID.AddPointer(Name);
5330 }
5331
5332 static bool classof(const Type *T) {
5333 return T->getTypeClass() == DependentName;
5334 }
5335};
5336
5337/// Represents a template specialization type whose template cannot be
5338/// resolved, e.g.
5339/// A<T>::template B<T>
5340class alignas(8) DependentTemplateSpecializationType
5341 : public TypeWithKeyword,
5342 public llvm::FoldingSetNode {
5343 friend class ASTContext; // ASTContext creates these
5344
5345 /// The nested name specifier containing the qualifier.
5346 NestedNameSpecifier *NNS;
5347
5348 /// The identifier of the template.
5349 const IdentifierInfo *Name;
5350
5351 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5352 NestedNameSpecifier *NNS,
5353 const IdentifierInfo *Name,
5354 ArrayRef<TemplateArgument> Args,
5355 QualType Canon);
5356
5357 const TemplateArgument *getArgBuffer() const {
5358 return reinterpret_cast<const TemplateArgument*>(this+1);
5359 }
5360
5361 TemplateArgument *getArgBuffer() {
5362 return reinterpret_cast<TemplateArgument*>(this+1);
5363 }
5364
5365public:
5366 NestedNameSpecifier *getQualifier() const { return NNS; }
5367 const IdentifierInfo *getIdentifier() const { return Name; }
5368
5369 /// Retrieve the template arguments.
5370 const TemplateArgument *getArgs() const {
5371 return getArgBuffer();
5372 }
5373
5374 /// Retrieve the number of template arguments.
5375 unsigned getNumArgs() const {
5376 return DependentTemplateSpecializationTypeBits.NumArgs;
5377 }
5378
5379 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5380
5381 ArrayRef<TemplateArgument> template_arguments() const {
5382 return {getArgs(), getNumArgs()};
5383 }
5384
5385 using iterator = const TemplateArgument *;
5386
5387 iterator begin() const { return getArgs(); }
5388 iterator end() const; // inline in TemplateBase.h
5389
5390 bool isSugared() const { return false; }
5391 QualType desugar() const { return QualType(this, 0); }
5392
5393 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5394 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5395 }
5396
5397 static void Profile(llvm::FoldingSetNodeID &ID,
5398 const ASTContext &Context,
5399 ElaboratedTypeKeyword Keyword,
5400 NestedNameSpecifier *Qualifier,
5401 const IdentifierInfo *Name,
5402 ArrayRef<TemplateArgument> Args);
5403
5404 static bool classof(const Type *T) {
5405 return T->getTypeClass() == DependentTemplateSpecialization;
5406 }
5407};
5408
5409/// Represents a pack expansion of types.
5410///
5411/// Pack expansions are part of C++11 variadic templates. A pack
5412/// expansion contains a pattern, which itself contains one or more
5413/// "unexpanded" parameter packs. When instantiated, a pack expansion
5414/// produces a series of types, each instantiated from the pattern of
5415/// the expansion, where the Ith instantiation of the pattern uses the
5416/// Ith arguments bound to each of the unexpanded parameter packs. The
5417/// pack expansion is considered to "expand" these unexpanded
5418/// parameter packs.
5419///
5420/// \code
5421/// template<typename ...Types> struct tuple;
5422///
5423/// template<typename ...Types>
5424/// struct tuple_of_references {
5425/// typedef tuple<Types&...> type;
5426/// };
5427/// \endcode
5428///
5429/// Here, the pack expansion \c Types&... is represented via a
5430/// PackExpansionType whose pattern is Types&.
5431class PackExpansionType : public Type, public llvm::FoldingSetNode {
5432 friend class ASTContext; // ASTContext creates these
5433
5434 /// The pattern of the pack expansion.
5435 QualType Pattern;
5436
5437 PackExpansionType(QualType Pattern, QualType Canon,
5438 Optional<unsigned> NumExpansions)
5439 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5440 /*InstantiationDependent=*/true,
5441 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5442 /*ContainsUnexpandedParameterPack=*/false),
5443 Pattern(Pattern) {
5444 PackExpansionTypeBits.NumExpansions =
5445 NumExpansions ? *NumExpansions + 1 : 0;
5446 }
5447
5448public:
5449 /// Retrieve the pattern of this pack expansion, which is the
5450 /// type that will be repeatedly instantiated when instantiating the
5451 /// pack expansion itself.
5452 QualType getPattern() const { return Pattern; }
5453
5454 /// Retrieve the number of expansions that this pack expansion will
5455 /// generate, if known.
5456 Optional<unsigned> getNumExpansions() const {
5457 if (PackExpansionTypeBits.NumExpansions)
5458 return PackExpansionTypeBits.NumExpansions - 1;
5459 return None;
5460 }
5461
5462 bool isSugared() const { return !Pattern->isDependentType(); }
5463 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5464
5465 void Profile(llvm::FoldingSetNodeID &ID) {
5466 Profile(ID, getPattern(), getNumExpansions());
5467 }
5468
5469 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5470 Optional<unsigned> NumExpansions) {
5471 ID.AddPointer(Pattern.getAsOpaquePtr());
5472 ID.AddBoolean(NumExpansions.hasValue());
5473 if (NumExpansions)
5474 ID.AddInteger(*NumExpansions);
5475 }
5476
5477 static bool classof(const Type *T) {
5478 return T->getTypeClass() == PackExpansion;
5479 }
5480};
5481
5482/// This class wraps the list of protocol qualifiers. For types that can
5483/// take ObjC protocol qualifers, they can subclass this class.
5484template <class T>
5485class ObjCProtocolQualifiers {
5486protected:
5487 ObjCProtocolQualifiers() = default;
5488
5489 ObjCProtocolDecl * const *getProtocolStorage() const {
5490 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5491 }
5492
5493 ObjCProtocolDecl **getProtocolStorage() {
5494 return static_cast<T*>(this)->getProtocolStorageImpl();
5495 }
5496
5497 void setNumProtocols(unsigned N) {
5498 static_cast<T*>(this)->setNumProtocolsImpl(N);
5499 }
5500
5501 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5502 setNumProtocols(protocols.size());
5503 assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5504, __PRETTY_FUNCTION__))
5504 "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5504, __PRETTY_FUNCTION__))
;
5505 if (!protocols.empty())
5506 memcpy(getProtocolStorage(), protocols.data(),
5507 protocols.size() * sizeof(ObjCProtocolDecl*));
5508 }
5509
5510public:
5511 using qual_iterator = ObjCProtocolDecl * const *;
5512 using qual_range = llvm::iterator_range<qual_iterator>;
5513
5514 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5515 qual_iterator qual_begin() const { return getProtocolStorage(); }
5516 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5517
5518 bool qual_empty() const { return getNumProtocols() == 0; }
5519
5520 /// Return the number of qualifying protocols in this type, or 0 if
5521 /// there are none.
5522 unsigned getNumProtocols() const {
5523 return static_cast<const T*>(this)->getNumProtocolsImpl();
5524 }
5525
5526 /// Fetch a protocol by index.
5527 ObjCProtocolDecl *getProtocol(unsigned I) const {
5528 assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access"
) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5528, __PRETTY_FUNCTION__))
;
5529 return qual_begin()[I];
5530 }
5531
5532 /// Retrieve all of the protocol qualifiers.
5533 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5534 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5535 }
5536};
5537
5538/// Represents a type parameter type in Objective C. It can take
5539/// a list of protocols.
5540class ObjCTypeParamType : public Type,
5541 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5542 public llvm::FoldingSetNode {
5543 friend class ASTContext;
5544 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5545
5546 /// The number of protocols stored on this type.
5547 unsigned NumProtocols : 6;
5548
5549 ObjCTypeParamDecl *OTPDecl;
5550
5551 /// The protocols are stored after the ObjCTypeParamType node. In the
5552 /// canonical type, the list of protocols are sorted alphabetically
5553 /// and uniqued.
5554 ObjCProtocolDecl **getProtocolStorageImpl();
5555
5556 /// Return the number of qualifying protocols in this interface type,
5557 /// or 0 if there are none.
5558 unsigned getNumProtocolsImpl() const {
5559 return NumProtocols;
5560 }
5561
5562 void setNumProtocolsImpl(unsigned N) {
5563 NumProtocols = N;
5564 }
5565
5566 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5567 QualType can,
5568 ArrayRef<ObjCProtocolDecl *> protocols);
5569
5570public:
5571 bool isSugared() const { return true; }
5572 QualType desugar() const { return getCanonicalTypeInternal(); }
5573
5574 static bool classof(const Type *T) {
5575 return T->getTypeClass() == ObjCTypeParam;
5576 }
5577
5578 void Profile(llvm::FoldingSetNodeID &ID);
5579 static void Profile(llvm::FoldingSetNodeID &ID,
5580 const ObjCTypeParamDecl *OTPDecl,
5581 ArrayRef<ObjCProtocolDecl *> protocols);
5582
5583 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5584};
5585
5586/// Represents a class type in Objective C.
5587///
5588/// Every Objective C type is a combination of a base type, a set of
5589/// type arguments (optional, for parameterized classes) and a list of
5590/// protocols.
5591///
5592/// Given the following declarations:
5593/// \code
5594/// \@class C<T>;
5595/// \@protocol P;
5596/// \endcode
5597///
5598/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5599/// with base C and no protocols.
5600///
5601/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5602/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5603/// protocol list.
5604/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5605/// and protocol list [P].
5606///
5607/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5608/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5609/// and no protocols.
5610///
5611/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5612/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5613/// this should get its own sugar class to better represent the source.
5614class ObjCObjectType : public Type,
5615 public ObjCProtocolQualifiers<ObjCObjectType> {
5616 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5617
5618 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5619 // after the ObjCObjectPointerType node.
5620 // ObjCObjectType.NumProtocols - the number of protocols stored
5621 // after the type arguments of ObjCObjectPointerType node.
5622 //
5623 // These protocols are those written directly on the type. If
5624 // protocol qualifiers ever become additive, the iterators will need
5625 // to get kindof complicated.
5626 //
5627 // In the canonical object type, these are sorted alphabetically
5628 // and uniqued.
5629
5630 /// Either a BuiltinType or an InterfaceType or sugar for either.
5631 QualType BaseType;
5632
5633 /// Cached superclass type.
5634 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5635 CachedSuperClassType;
5636
5637 QualType *getTypeArgStorage();
5638 const QualType *getTypeArgStorage() const {
5639 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5640 }
5641
5642 ObjCProtocolDecl **getProtocolStorageImpl();
5643 /// Return the number of qualifying protocols in this interface type,
5644 /// or 0 if there are none.
5645 unsigned getNumProtocolsImpl() const {
5646 return ObjCObjectTypeBits.NumProtocols;
5647 }
5648 void setNumProtocolsImpl(unsigned N) {
5649 ObjCObjectTypeBits.NumProtocols = N;
5650 }
5651
5652protected:
5653 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5654
5655 ObjCObjectType(QualType Canonical, QualType Base,
5656 ArrayRef<QualType> typeArgs,
5657 ArrayRef<ObjCProtocolDecl *> protocols,
5658 bool isKindOf);
5659
5660 ObjCObjectType(enum Nonce_ObjCInterface)
5661 : Type(ObjCInterface, QualType(), false, false, false, false),
5662 BaseType(QualType(this_(), 0)) {
5663 ObjCObjectTypeBits.NumProtocols = 0;
5664 ObjCObjectTypeBits.NumTypeArgs = 0;
5665 ObjCObjectTypeBits.IsKindOf = 0;
5666 }
5667
5668 void computeSuperClassTypeSlow() const;
5669
5670public:
5671 /// Gets the base type of this object type. This is always (possibly
5672 /// sugar for) one of:
5673 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5674 /// user, which is a typedef for an ObjCObjectPointerType)
5675 /// - the 'Class' builtin type (same caveat)
5676 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5677 QualType getBaseType() const { return BaseType; }
5678
5679 bool isObjCId() const {
5680 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5681 }
5682
5683 bool isObjCClass() const {
5684 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5685 }
5686
5687 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5688 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5689 bool isObjCUnqualifiedIdOrClass() const {
5690 if (!qual_empty()) return false;
5691 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5692 return T->getKind() == BuiltinType::ObjCId ||
5693 T->getKind() == BuiltinType::ObjCClass;
5694 return false;
5695 }
5696 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5697 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5698
5699 /// Gets the interface declaration for this object type, if the base type
5700 /// really is an interface.
5701 ObjCInterfaceDecl *getInterface() const;
5702
5703 /// Determine whether this object type is "specialized", meaning
5704 /// that it has type arguments.
5705 bool isSpecialized() const;
5706
5707 /// Determine whether this object type was written with type arguments.
5708 bool isSpecializedAsWritten() const {
5709 return ObjCObjectTypeBits.NumTypeArgs > 0;
5710 }
5711
5712 /// Determine whether this object type is "unspecialized", meaning
5713 /// that it has no type arguments.
5714 bool isUnspecialized() const { return !isSpecialized(); }
5715
5716 /// Determine whether this object type is "unspecialized" as
5717 /// written, meaning that it has no type arguments.
5718 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5719
5720 /// Retrieve the type arguments of this object type (semantically).
5721 ArrayRef<QualType> getTypeArgs() const;
5722
5723 /// Retrieve the type arguments of this object type as they were
5724 /// written.
5725 ArrayRef<QualType> getTypeArgsAsWritten() const {
5726 return llvm::makeArrayRef(getTypeArgStorage(),
5727 ObjCObjectTypeBits.NumTypeArgs);
5728 }
5729
5730 /// Whether this is a "__kindof" type as written.
5731 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5732
5733 /// Whether this ia a "__kindof" type (semantically).
5734 bool isKindOfType() const;
5735
5736 /// Retrieve the type of the superclass of this object type.
5737 ///
5738 /// This operation substitutes any type arguments into the
5739 /// superclass of the current class type, potentially producing a
5740 /// specialization of the superclass type. Produces a null type if
5741 /// there is no superclass.
5742 QualType getSuperClassType() const {
5743 if (!CachedSuperClassType.getInt())
5744 computeSuperClassTypeSlow();
5745
5746 assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?"
) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5746, __PRETTY_FUNCTION__))
;
5747 return QualType(CachedSuperClassType.getPointer(), 0);
5748 }
5749
5750 /// Strip off the Objective-C "kindof" type and (with it) any
5751 /// protocol qualifiers.
5752 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5753
5754 bool isSugared() const { return false; }
5755 QualType desugar() const { return QualType(this, 0); }
5756
5757 static bool classof(const Type *T) {
5758 return T->getTypeClass() == ObjCObject ||
5759 T->getTypeClass() == ObjCInterface;
5760 }
5761};
5762
5763/// A class providing a concrete implementation
5764/// of ObjCObjectType, so as to not increase the footprint of
5765/// ObjCInterfaceType. Code outside of ASTContext and the core type
5766/// system should not reference this type.
5767class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5768 friend class ASTContext;
5769
5770 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5771 // will need to be modified.
5772
5773 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5774 ArrayRef<QualType> typeArgs,
5775 ArrayRef<ObjCProtocolDecl *> protocols,
5776 bool isKindOf)
5777 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5778
5779public:
5780 void Profile(llvm::FoldingSetNodeID &ID);
5781 static void Profile(llvm::FoldingSetNodeID &ID,
5782 QualType Base,
5783 ArrayRef<QualType> typeArgs,
5784 ArrayRef<ObjCProtocolDecl *> protocols,
5785 bool isKindOf);
5786};
5787
5788inline QualType *ObjCObjectType::getTypeArgStorage() {
5789 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5790}
5791
5792inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5793 return reinterpret_cast<ObjCProtocolDecl**>(
5794 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5795}
5796
5797inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5798 return reinterpret_cast<ObjCProtocolDecl**>(
5799 static_cast<ObjCTypeParamType*>(this)+1);
5800}
5801
5802/// Interfaces are the core concept in Objective-C for object oriented design.
5803/// They basically correspond to C++ classes. There are two kinds of interface
5804/// types: normal interfaces like `NSString`, and qualified interfaces, which
5805/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5806///
5807/// ObjCInterfaceType guarantees the following properties when considered
5808/// as a subtype of its superclass, ObjCObjectType:
5809/// - There are no protocol qualifiers. To reinforce this, code which
5810/// tries to invoke the protocol methods via an ObjCInterfaceType will
5811/// fail to compile.
5812/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5813/// T->getBaseType() == QualType(T, 0).
5814class ObjCInterfaceType : public ObjCObjectType {
5815 friend class ASTContext; // ASTContext creates these.
5816 friend class ASTReader;
5817 friend class ObjCInterfaceDecl;
5818
5819 mutable ObjCInterfaceDecl *Decl;
5820
5821 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5822 : ObjCObjectType(Nonce_ObjCInterface),
5823 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5824
5825public:
5826 /// Get the declaration of this interface.
5827 ObjCInterfaceDecl *getDecl() const { return Decl; }
5828
5829 bool isSugared() const { return false; }
5830 QualType desugar() const { return QualType(this, 0); }
5831
5832 static bool classof(const Type *T) {
5833 return T->getTypeClass() == ObjCInterface;
5834 }
5835
5836 // Nonsense to "hide" certain members of ObjCObjectType within this
5837 // class. People asking for protocols on an ObjCInterfaceType are
5838 // not going to get what they want: ObjCInterfaceTypes are
5839 // guaranteed to have no protocols.
5840 enum {
5841 qual_iterator,
5842 qual_begin,
5843 qual_end,
5844 getNumProtocols,
5845 getProtocol
5846 };
5847};
5848
5849inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5850 QualType baseType = getBaseType();
5851 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
5852 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
5853 return T->getDecl();
5854
5855 baseType = ObjT->getBaseType();
5856 }
5857
5858 return nullptr;
5859}
5860
5861/// Represents a pointer to an Objective C object.
5862///
5863/// These are constructed from pointer declarators when the pointee type is
5864/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
5865/// types are typedefs for these, and the protocol-qualified types 'id<P>'
5866/// and 'Class<P>' are translated into these.
5867///
5868/// Pointers to pointers to Objective C objects are still PointerTypes;
5869/// only the first level of pointer gets it own type implementation.
5870class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5871 friend class ASTContext; // ASTContext creates these.
5872
5873 QualType PointeeType;
5874
5875 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5876 : Type(ObjCObjectPointer, Canonical,
5877 Pointee->isDependentType(),
5878 Pointee->isInstantiationDependentType(),
5879 Pointee->isVariablyModifiedType(),
5880 Pointee->containsUnexpandedParameterPack()),
5881 PointeeType(Pointee) {}
5882
5883public:
5884 /// Gets the type pointed to by this ObjC pointer.
5885 /// The result will always be an ObjCObjectType or sugar thereof.
5886 QualType getPointeeType() const { return PointeeType; }
5887
5888 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5889 ///
5890 /// This method is equivalent to getPointeeType() except that
5891 /// it discards any typedefs (or other sugar) between this
5892 /// type and the "outermost" object type. So for:
5893 /// \code
5894 /// \@class A; \@protocol P; \@protocol Q;
5895 /// typedef A<P> AP;
5896 /// typedef A A1;
5897 /// typedef A1<P> A1P;
5898 /// typedef A1P<Q> A1PQ;
5899 /// \endcode
5900 /// For 'A*', getObjectType() will return 'A'.
5901 /// For 'A<P>*', getObjectType() will return 'A<P>'.
5902 /// For 'AP*', getObjectType() will return 'A<P>'.
5903 /// For 'A1*', getObjectType() will return 'A'.
5904 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5905 /// For 'A1P*', getObjectType() will return 'A1<P>'.
5906 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5907 /// adding protocols to a protocol-qualified base discards the
5908 /// old qualifiers (for now). But if it didn't, getObjectType()
5909 /// would return 'A1P<Q>' (and we'd have to make iterating over
5910 /// qualifiers more complicated).
5911 const ObjCObjectType *getObjectType() const {
5912 return PointeeType->castAs<ObjCObjectType>();
5913 }
5914
5915 /// If this pointer points to an Objective C
5916 /// \@interface type, gets the type for that interface. Any protocol
5917 /// qualifiers on the interface are ignored.
5918 ///
5919 /// \return null if the base type for this pointer is 'id' or 'Class'
5920 const ObjCInterfaceType *getInterfaceType() const;
5921
5922 /// If this pointer points to an Objective \@interface
5923 /// type, gets the declaration for that interface.
5924 ///
5925 /// \return null if the base type for this pointer is 'id' or 'Class'
5926 ObjCInterfaceDecl *getInterfaceDecl() const {
5927 return getObjectType()->getInterface();
5928 }
5929
5930 /// True if this is equivalent to the 'id' type, i.e. if
5931 /// its object type is the primitive 'id' type with no protocols.
5932 bool isObjCIdType() const {
5933 return getObjectType()->isObjCUnqualifiedId();
5934 }
5935
5936 /// True if this is equivalent to the 'Class' type,
5937 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5938 bool isObjCClassType() const {
5939 return getObjectType()->isObjCUnqualifiedClass();
5940 }
5941
5942 /// True if this is equivalent to the 'id' or 'Class' type,
5943 bool isObjCIdOrClassType() const {
5944 return getObjectType()->isObjCUnqualifiedIdOrClass();
5945 }
5946
5947 /// True if this is equivalent to 'id<P>' for some non-empty set of
5948 /// protocols.
5949 bool isObjCQualifiedIdType() const {
5950 return getObjectType()->isObjCQualifiedId();
5951 }
5952
5953 /// True if this is equivalent to 'Class<P>' for some non-empty set of
5954 /// protocols.
5955 bool isObjCQualifiedClassType() const {
5956 return getObjectType()->isObjCQualifiedClass();
5957 }
5958
5959 /// Whether this is a "__kindof" type.
5960 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5961
5962 /// Whether this type is specialized, meaning that it has type arguments.
5963 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5964
5965 /// Whether this type is specialized, meaning that it has type arguments.
5966 bool isSpecializedAsWritten() const {
5967 return getObjectType()->isSpecializedAsWritten();
5968 }
5969
5970 /// Whether this type is unspecialized, meaning that is has no type arguments.
5971 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5972
5973 /// Determine whether this object type is "unspecialized" as
5974 /// written, meaning that it has no type arguments.
5975 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5976
5977 /// Retrieve the type arguments for this type.
5978 ArrayRef<QualType> getTypeArgs() const {
5979 return getObjectType()->getTypeArgs();
5980 }
5981
5982 /// Retrieve the type arguments for this type.
5983 ArrayRef<QualType> getTypeArgsAsWritten() const {
5984 return getObjectType()->getTypeArgsAsWritten();
5985 }
5986
5987 /// An iterator over the qualifiers on the object type. Provided
5988 /// for convenience. This will always iterate over the full set of
5989 /// protocols on a type, not just those provided directly.
5990 using qual_iterator = ObjCObjectType::qual_iterator;
5991 using qual_range = llvm::iterator_range<qual_iterator>;
5992
5993 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5994
5995 qual_iterator qual_begin() const {
5996 return getObjectType()->qual_begin();
5997 }
5998
5999 qual_iterator qual_end() const {
6000 return getObjectType()->qual_end();
6001 }
6002
6003 bool qual_empty() const { return getObjectType()->qual_empty(); }
6004
6005 /// Return the number of qualifying protocols on the object type.
6006 unsigned getNumProtocols() const {
6007 return getObjectType()->getNumProtocols();
6008 }
6009
6010 /// Retrieve a qualifying protocol by index on the object type.
6011 ObjCProtocolDecl *getProtocol(unsigned I) const {
6012 return getObjectType()->getProtocol(I);
6013 }
6014
6015 bool isSugared() const { return false; }
6016 QualType desugar() const { return QualType(this, 0); }
6017
6018 /// Retrieve the type of the superclass of this object pointer type.
6019 ///
6020 /// This operation substitutes any type arguments into the
6021 /// superclass of the current class type, potentially producing a
6022 /// pointer to a specialization of the superclass type. Produces a
6023 /// null type if there is no superclass.
6024 QualType getSuperClassType() const;
6025
6026 /// Strip off the Objective-C "kindof" type and (with it) any
6027 /// protocol qualifiers.
6028 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6029 const ASTContext &ctx) const;
6030
6031 void Profile(llvm::FoldingSetNodeID &ID) {
6032 Profile(ID, getPointeeType());
6033 }
6034
6035 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6036 ID.AddPointer(T.getAsOpaquePtr());
6037 }
6038
6039 static bool classof(const Type *T) {
6040 return T->getTypeClass() == ObjCObjectPointer;
6041 }
6042};
6043
6044class AtomicType : public Type, public llvm::FoldingSetNode {
6045 friend class ASTContext; // ASTContext creates these.
6046
6047 QualType ValueType;
6048
6049 AtomicType(QualType ValTy, QualType Canonical)
6050 : Type(Atomic, Canonical, ValTy->isDependentType(),
6051 ValTy->isInstantiationDependentType(),
6052 ValTy->isVariablyModifiedType(),
6053 ValTy->containsUnexpandedParameterPack()),
6054 ValueType(ValTy) {}
6055
6056public:
6057 /// Gets the type contained by this atomic type, i.e.
6058 /// the type returned by performing an atomic load of this atomic type.
6059 QualType getValueType() const { return ValueType; }
6060
6061 bool isSugared() const { return false; }
6062 QualType desugar() const { return QualType(this, 0); }
6063
6064 void Profile(llvm::FoldingSetNodeID &ID) {
6065 Profile(ID, getValueType());
6066 }
6067
6068 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6069 ID.AddPointer(T.getAsOpaquePtr());
6070 }
6071
6072 static bool classof(const Type *T) {
6073 return T->getTypeClass() == Atomic;
6074 }
6075};
6076
6077/// PipeType - OpenCL20.
6078class PipeType : public Type, public llvm::FoldingSetNode {
6079 friend class ASTContext; // ASTContext creates these.
6080
6081 QualType ElementType;
6082 bool isRead;
6083
6084 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6085 : Type(Pipe, CanonicalPtr, elemType->isDependentType(),
6086 elemType->isInstantiationDependentType(),
6087 elemType->isVariablyModifiedType(),
6088 elemType->containsUnexpandedParameterPack()),
6089 ElementType(elemType), isRead(isRead) {}
6090
6091public:
6092 QualType getElementType() const { return ElementType; }
6093
6094 bool isSugared() const { return false; }
6095
6096 QualType desugar() const { return QualType(this, 0); }
6097
6098 void Profile(llvm::FoldingSetNodeID &ID) {
6099 Profile(ID, getElementType(), isReadOnly());
6100 }
6101
6102 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6103 ID.AddPointer(T.getAsOpaquePtr());
6104 ID.AddBoolean(isRead);
6105 }
6106
6107 static bool classof(const Type *T) {
6108 return T->getTypeClass() == Pipe;
6109 }
6110
6111 bool isReadOnly() const { return isRead; }
6112};
6113
6114/// A qualifier set is used to build a set of qualifiers.
6115class QualifierCollector : public Qualifiers {
6116public:
6117 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6118
6119 /// Collect any qualifiers on the given type and return an
6120 /// unqualified type. The qualifiers are assumed to be consistent
6121 /// with those already in the type.
6122 const Type *strip(QualType type) {
6123 addFastQualifiers(type.getLocalFastQualifiers());
6124 if (!type.hasLocalNonFastQualifiers())
6125 return type.getTypePtrUnsafe();
6126
6127 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6128 addConsistentQualifiers(extQuals->getQualifiers());
6129 return extQuals->getBaseType();
6130 }
6131
6132 /// Apply the collected qualifiers to the given type.
6133 QualType apply(const ASTContext &Context, QualType QT) const;
6134
6135 /// Apply the collected qualifiers to the given type.
6136 QualType apply(const ASTContext &Context, const Type* T) const;
6137};
6138
6139// Inline function definitions.
6140
6141inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6142 SplitQualType desugar =
6143 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6144 desugar.Quals.addConsistentQualifiers(Quals);
6145 return desugar;
6146}
6147
6148inline const Type *QualType::getTypePtr() const {
6149 return getCommonPtr()->BaseType;
6150}
6151
6152inline const Type *QualType::getTypePtrOrNull() const {
6153 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6154}
6155
6156inline SplitQualType QualType::split() const {
6157 if (!hasLocalNonFastQualifiers())
6158 return SplitQualType(getTypePtrUnsafe(),
6159 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6160
6161 const ExtQuals *eq = getExtQualsUnsafe();
6162 Qualifiers qs = eq->getQualifiers();
6163 qs.addFastQualifiers(getLocalFastQualifiers());
6164 return SplitQualType(eq->getBaseType(), qs);
6165}
6166
6167inline Qualifiers QualType::getLocalQualifiers() const {
6168 Qualifiers Quals;
6169 if (hasLocalNonFastQualifiers())
6170 Quals = getExtQualsUnsafe()->getQualifiers();
6171 Quals.addFastQualifiers(getLocalFastQualifiers());
6172 return Quals;
6173}
6174
6175inline Qualifiers QualType::getQualifiers() const {
6176 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6177 quals.addFastQualifiers(getLocalFastQualifiers());
6178 return quals;
6179}
6180
6181inline unsigned QualType::getCVRQualifiers() const {
6182 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6183 cvr |= getLocalCVRQualifiers();
6184 return cvr;
6185}
6186
6187inline QualType QualType::getCanonicalType() const {
6188 QualType canon = getCommonPtr()->CanonicalType;
6189 return canon.withFastQualifiers(getLocalFastQualifiers());
6190}
6191
6192inline bool QualType::isCanonical() const {
6193 return getTypePtr()->isCanonicalUnqualified();
6194}
6195
6196inline bool QualType::isCanonicalAsParam() const {
6197 if (!isCanonical()) return false;
6198 if (hasLocalQualifiers()) return false;
6199
6200 const Type *T = getTypePtr();
6201 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6202 return false;
6203
6204 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6205}
6206
6207inline bool QualType::isConstQualified() const {
6208 return isLocalConstQualified() ||
6209 getCommonPtr()->CanonicalType.isLocalConstQualified();
6210}
6211
6212inline bool QualType::isRestrictQualified() const {
6213 return isLocalRestrictQualified() ||
6214 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6215}
6216
6217
6218inline bool QualType::isVolatileQualified() const {
6219 return isLocalVolatileQualified() ||
6220 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6221}
6222
6223inline bool QualType::hasQualifiers() const {
6224 return hasLocalQualifiers() ||
6225 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6226}
6227
6228inline QualType QualType::getUnqualifiedType() const {
6229 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6230 return QualType(getTypePtr(), 0);
6231
6232 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6233}
6234
6235inline SplitQualType QualType::getSplitUnqualifiedType() const {
6236 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6237 return split();
6238
6239 return getSplitUnqualifiedTypeImpl(*this);
6240}
6241
6242inline void QualType::removeLocalConst() {
6243 removeLocalFastQualifiers(Qualifiers::Const);
6244}
6245
6246inline void QualType::removeLocalRestrict() {
6247 removeLocalFastQualifiers(Qualifiers::Restrict);
6248}
6249
6250inline void QualType::removeLocalVolatile() {
6251 removeLocalFastQualifiers(Qualifiers::Volatile);
6252}
6253
6254inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6255 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6255, __PRETTY_FUNCTION__))
;
6256 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6257 "Fast bits differ from CVR bits!");
6258
6259 // Fast path: we don't need to touch the slow qualifiers.
6260 removeLocalFastQualifiers(Mask);
6261}
6262
6263/// Return the address space of this type.
6264inline LangAS QualType::getAddressSpace() const {
6265 return getQualifiers().getAddressSpace();
6266}
6267
6268/// Return the gc attribute of this type.
6269inline Qualifiers::GC QualType::getObjCGCAttr() const {
6270 return getQualifiers().getObjCGCAttr();
6271}
6272
6273inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6274 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6275 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6276 return false;
6277}
6278
6279inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6280 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6281 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6282 return false;
6283}
6284
6285inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6286 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6287 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6288 return false;
6289}
6290
6291inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6292 if (const auto *PT = t.getAs<PointerType>()) {
6293 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6294 return FT->getExtInfo();
6295 } else if (const auto *FT = t.getAs<FunctionType>())
6296 return FT->getExtInfo();
6297
6298 return FunctionType::ExtInfo();
6299}
6300
6301inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6302 return getFunctionExtInfo(*t);
6303}
6304
6305/// Determine whether this type is more
6306/// qualified than the Other type. For example, "const volatile int"
6307/// is more qualified than "const int", "volatile int", and
6308/// "int". However, it is not more qualified than "const volatile
6309/// int".
6310inline bool QualType::isMoreQualifiedThan(QualType other) const {
6311 Qualifiers MyQuals = getQualifiers();
6312 Qualifiers OtherQuals = other.getQualifiers();
6313 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6314}
6315
6316/// Determine whether this type is at last
6317/// as qualified as the Other type. For example, "const volatile
6318/// int" is at least as qualified as "const int", "volatile int",
6319/// "int", and "const volatile int".
6320inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6321 Qualifiers OtherQuals = other.getQualifiers();
6322
6323 // Ignore __unaligned qualifier if this type is a void.
6324 if (getUnqualifiedType()->isVoidType())
6325 OtherQuals.removeUnaligned();
6326
6327 return getQualifiers().compatiblyIncludes(OtherQuals);
6328}
6329
6330/// If Type is a reference type (e.g., const
6331/// int&), returns the type that the reference refers to ("const
6332/// int"). Otherwise, returns the type itself. This routine is used
6333/// throughout Sema to implement C++ 5p6:
6334///
6335/// If an expression initially has the type "reference to T" (8.3.2,
6336/// 8.5.3), the type is adjusted to "T" prior to any further
6337/// analysis, the expression designates the object or function
6338/// denoted by the reference, and the expression is an lvalue.
6339inline QualType QualType::getNonReferenceType() const {
6340 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6341 return RefType->getPointeeType();
6342 else
6343 return *this;
6344}
6345
6346inline bool QualType::isCForbiddenLValueType() const {
6347 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6348 getTypePtr()->isFunctionType());
6349}
6350
6351/// Tests whether the type is categorized as a fundamental type.
6352///
6353/// \returns True for types specified in C++0x [basic.fundamental].
6354inline bool Type::isFundamentalType() const {
6355 return isVoidType() ||
6356 isNullPtrType() ||
6357 // FIXME: It's really annoying that we don't have an
6358 // 'isArithmeticType()' which agrees with the standard definition.
6359 (isArithmeticType() && !isEnumeralType());
6360}
6361
6362/// Tests whether the type is categorized as a compound type.
6363///
6364/// \returns True for types specified in C++0x [basic.compound].
6365inline bool Type::isCompoundType() const {
6366 // C++0x [basic.compound]p1:
6367 // Compound types can be constructed in the following ways:
6368 // -- arrays of objects of a given type [...];
6369 return isArrayType() ||
6370 // -- functions, which have parameters of given types [...];
6371 isFunctionType() ||
6372 // -- pointers to void or objects or functions [...];
6373 isPointerType() ||
6374 // -- references to objects or functions of a given type. [...]
6375 isReferenceType() ||
6376 // -- classes containing a sequence of objects of various types, [...];
6377 isRecordType() ||
6378 // -- unions, which are classes capable of containing objects of different
6379 // types at different times;
6380 isUnionType() ||
6381 // -- enumerations, which comprise a set of named constant values. [...];
6382 isEnumeralType() ||
6383 // -- pointers to non-static class members, [...].
6384 isMemberPointerType();
6385}
6386
6387inline bool Type::isFunctionType() const {
6388 return isa<FunctionType>(CanonicalType);
6389}
6390
6391inline bool Type::isPointerType() const {
6392 return isa<PointerType>(CanonicalType);
6393}
6394
6395inline bool Type::isAnyPointerType() const {
6396 return isPointerType() || isObjCObjectPointerType();
6397}
6398
6399inline bool Type::isBlockPointerType() const {
6400 return isa<BlockPointerType>(CanonicalType);
6401}
6402
6403inline bool Type::isReferenceType() const {
6404 return isa<ReferenceType>(CanonicalType);
6405}
6406
6407inline bool Type::isLValueReferenceType() const {
6408 return isa<LValueReferenceType>(CanonicalType);
6409}
6410
6411inline bool Type::isRValueReferenceType() const {
6412 return isa<RValueReferenceType>(CanonicalType);
6413}
6414
6415inline bool Type::isFunctionPointerType() const {
6416 if (const auto *T = getAs<PointerType>())
6417 return T->getPointeeType()->isFunctionType();
6418 else
6419 return false;
6420}
6421
6422inline bool Type::isFunctionReferenceType() const {
6423 if (const auto *T = getAs<ReferenceType>())
6424 return T->getPointeeType()->isFunctionType();
6425 else
6426 return false;
6427}
6428
6429inline bool Type::isMemberPointerType() const {
6430 return isa<MemberPointerType>(CanonicalType);
6431}
6432
6433inline bool Type::isMemberFunctionPointerType() const {
6434 if (const auto *T = getAs<MemberPointerType>())
6435 return T->isMemberFunctionPointer();
6436 else
6437 return false;
6438}
6439
6440inline bool Type::isMemberDataPointerType() const {
6441 if (const auto *T = getAs<MemberPointerType>())
6442 return T->isMemberDataPointer();
6443 else
6444 return false;
6445}
6446
6447inline bool Type::isArrayType() const {
6448 return isa<ArrayType>(CanonicalType);
6449}
6450
6451inline bool Type::isConstantArrayType() const {
6452 return isa<ConstantArrayType>(CanonicalType);
6453}
6454
6455inline bool Type::isIncompleteArrayType() const {
6456 return isa<IncompleteArrayType>(CanonicalType);
6457}
6458
6459inline bool Type::isVariableArrayType() const {
6460 return isa<VariableArrayType>(CanonicalType);
6461}
6462
6463inline bool Type::isDependentSizedArrayType() const {
6464 return isa<DependentSizedArrayType>(CanonicalType);
6465}
6466
6467inline bool Type::isBuiltinType() const {
6468 return isa<BuiltinType>(CanonicalType);
6469}
6470
6471inline bool Type::isRecordType() const {
6472 return isa<RecordType>(CanonicalType);
6473}
6474
6475inline bool Type::isEnumeralType() const {
6476 return isa<EnumType>(CanonicalType);
6477}
6478
6479inline bool Type::isAnyComplexType() const {
6480 return isa<ComplexType>(CanonicalType);
6481}
6482
6483inline bool Type::isVectorType() const {
6484 return isa<VectorType>(CanonicalType);
6485}
6486
6487inline bool Type::isExtVectorType() const {
6488 return isa<ExtVectorType>(CanonicalType);
6489}
6490
6491inline bool Type::isDependentAddressSpaceType() const {
6492 return isa<DependentAddressSpaceType>(CanonicalType);
6493}
6494
6495inline bool Type::isObjCObjectPointerType() const {
6496 return isa<ObjCObjectPointerType>(CanonicalType);
6497}
6498
6499inline bool Type::isObjCObjectType() const {
6500 return isa<ObjCObjectType>(CanonicalType);
6501}
6502
6503inline bool Type::isObjCObjectOrInterfaceType() const {
6504 return isa<ObjCInterfaceType>(CanonicalType) ||
6505 isa<ObjCObjectType>(CanonicalType);
6506}
6507
6508inline bool Type::isAtomicType() const {
6509 return isa<AtomicType>(CanonicalType);
6510}
6511
6512inline bool Type::isObjCQualifiedIdType() const {
6513 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6514 return OPT->isObjCQualifiedIdType();
6515 return false;
6516}
6517
6518inline bool Type::isObjCQualifiedClassType() const {
6519 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6520 return OPT->isObjCQualifiedClassType();
6521 return false;
6522}
6523
6524inline bool Type::isObjCIdType() const {
6525 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6526 return OPT->isObjCIdType();
6527 return false;
6528}
6529
6530inline bool Type::isObjCClassType() const {
6531 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6532 return OPT->isObjCClassType();
6533 return false;
6534}
6535
6536inline bool Type::isObjCSelType() const {
6537 if (const auto *OPT = getAs<PointerType>())
6538 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6539 return false;
6540}
6541
6542inline bool Type::isObjCBuiltinType() const {
6543 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6544}
6545
6546inline bool Type::isDecltypeType() const {
6547 return isa<DecltypeType>(this);
6548}
6549
6550#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6551 inline bool Type::is##Id##Type() const { \
6552 return isSpecificBuiltinType(BuiltinType::Id); \
6553 }
6554#include "clang/Basic/OpenCLImageTypes.def"
6555
6556inline bool Type::isSamplerT() const {
6557 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6558}
6559
6560inline bool Type::isEventT() const {
6561 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6562}
6563
6564inline bool Type::isClkEventT() const {
6565 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6566}
6567
6568inline bool Type::isQueueT() const {
6569 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6570}
6571
6572inline bool Type::isReserveIDT() const {
6573 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6574}
6575
6576inline bool Type::isImageType() const {
6577#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6578 return
6579#include "clang/Basic/OpenCLImageTypes.def"
6580 false; // end boolean or operation
6581}
6582
6583inline bool Type::isPipeType() const {
6584 return isa<PipeType>(CanonicalType);
6585}
6586
6587#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6588 inline bool Type::is##Id##Type() const { \
6589 return isSpecificBuiltinType(BuiltinType::Id); \
6590 }
6591#include "clang/Basic/OpenCLExtensionTypes.def"
6592
6593inline bool Type::isOCLIntelSubgroupAVCType() const {
6594#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6595 isOCLIntelSubgroupAVC##Id##Type() ||
6596 return
6597#include "clang/Basic/OpenCLExtensionTypes.def"
6598 false; // end of boolean or operation
6599}
6600
6601inline bool Type::isOCLExtOpaqueType() const {
6602#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6603 return
6604#include "clang/Basic/OpenCLExtensionTypes.def"
6605 false; // end of boolean or operation
6606}
6607
6608inline bool Type::isOpenCLSpecificType() const {
6609 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6610 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6611}
6612
6613inline bool Type::isTemplateTypeParmType() const {
6614 return isa<TemplateTypeParmType>(CanonicalType);
6615}
6616
6617inline bool Type::isSpecificBuiltinType(unsigned K) const {
6618 if (const BuiltinType *BT = getAs<BuiltinType>())
6619 if (BT->getKind() == (BuiltinType::Kind) K)
6620 return true;
6621 return false;
6622}
6623
6624inline bool Type::isPlaceholderType() const {
6625 if (const auto *BT = dyn_cast<BuiltinType>(this))
6626 return BT->isPlaceholderType();
6627 return false;
6628}
6629
6630inline const BuiltinType *Type::getAsPlaceholderType() const {
6631 if (const auto *BT = dyn_cast<BuiltinType>(this))
6632 if (BT->isPlaceholderType())
6633 return BT;
6634 return nullptr;
6635}
6636
6637inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6638 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ?
static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6638, __PRETTY_FUNCTION__))
;
6639 if (const auto *BT = dyn_cast<BuiltinType>(this))
6640 return (BT->getKind() == (BuiltinType::Kind) K);
6641 return false;
6642}
6643
6644inline bool Type::isNonOverloadPlaceholderType() const {
6645 if (const auto *BT = dyn_cast<BuiltinType>(this))
6646 return BT->isNonOverloadPlaceholderType();
6647 return false;
6648}
6649
6650inline bool Type::isVoidType() const {
6651 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6652 return BT->getKind() == BuiltinType::Void;
6653 return false;
6654}
6655
6656inline bool Type::isHalfType() const {
6657 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6658 return BT->getKind() == BuiltinType::Half;
6659 // FIXME: Should we allow complex __fp16? Probably not.
6660 return false;
6661}
6662
6663inline bool Type::isFloat16Type() const {
6664 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6665 return BT->getKind() == BuiltinType::Float16;
6666 return false;
6667}
6668
6669inline bool Type::isFloat128Type() const {
6670 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6671 return BT->getKind() == BuiltinType::Float128;
6672 return false;
6673}
6674
6675inline bool Type::isNullPtrType() const {
6676 if (const auto *BT = getAs<BuiltinType>())
6677 return BT->getKind() == BuiltinType::NullPtr;
6678 return false;
6679}
6680
6681bool IsEnumDeclComplete(EnumDecl *);
6682bool IsEnumDeclScoped(EnumDecl *);
6683
6684inline bool Type::isIntegerType() const {
6685 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6686 return BT->getKind() >= BuiltinType::Bool &&
6687 BT->getKind() <= BuiltinType::Int128;
6688 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6689 // Incomplete enum types are not treated as integer types.
6690 // FIXME: In C++, enum types are never integer types.
6691 return IsEnumDeclComplete(ET->getDecl()) &&
6692 !IsEnumDeclScoped(ET->getDecl());
6693 }
6694 return false;
6695}
6696
6697inline bool Type::isFixedPointType() const {
6698 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6699 return BT->getKind() >= BuiltinType::ShortAccum &&
6700 BT->getKind() <= BuiltinType::SatULongFract;
6701 }
6702 return false;
6703}
6704
6705inline bool Type::isFixedPointOrIntegerType() const {
6706 return isFixedPointType() || isIntegerType();
6707}
6708
6709inline bool Type::isSaturatedFixedPointType() const {
6710 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6711 return BT->getKind() >= BuiltinType::SatShortAccum &&
6712 BT->getKind() <= BuiltinType::SatULongFract;
6713 }
6714 return false;
6715}
6716
6717inline bool Type::isUnsaturatedFixedPointType() const {
6718 return isFixedPointType() && !isSaturatedFixedPointType();
6719}
6720
6721inline bool Type::isSignedFixedPointType() const {
6722 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6723 return ((BT->getKind() >= BuiltinType::ShortAccum &&
6724 BT->getKind() <= BuiltinType::LongAccum) ||
6725 (BT->getKind() >= BuiltinType::ShortFract &&
6726 BT->getKind() <= BuiltinType::LongFract) ||
6727 (BT->getKind() >= BuiltinType::SatShortAccum &&
6728 BT->getKind() <= BuiltinType::SatLongAccum) ||
6729 (BT->getKind() >= BuiltinType::SatShortFract &&
6730 BT->getKind() <= BuiltinType::SatLongFract));
6731 }
6732 return false;
6733}
6734
6735inline bool Type::isUnsignedFixedPointType() const {
6736 return isFixedPointType() && !isSignedFixedPointType();
6737}
6738
6739inline bool Type::isScalarType() const {
6740 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6741 return BT->getKind() > BuiltinType::Void &&
6742 BT->getKind() <= BuiltinType::NullPtr;
6743 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6744 // Enums are scalar types, but only if they are defined. Incomplete enums
6745 // are not treated as scalar types.
6746 return IsEnumDeclComplete(ET->getDecl());
6747 return isa<PointerType>(CanonicalType) ||
6748 isa<BlockPointerType>(CanonicalType) ||
6749 isa<MemberPointerType>(CanonicalType) ||
6750 isa<ComplexType>(CanonicalType) ||
6751 isa<ObjCObjectPointerType>(CanonicalType);
6752}
6753
6754inline bool Type::isIntegralOrEnumerationType() const {
6755 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6756 return BT->getKind() >= BuiltinType::Bool &&
6757 BT->getKind() <= BuiltinType::Int128;
6758
6759 // Check for a complete enum type; incomplete enum types are not properly an
6760 // enumeration type in the sense required here.
6761 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
6762 return IsEnumDeclComplete(ET->getDecl());
6763
6764 return false;
6765}
6766
6767inline bool Type::isBooleanType() const {
6768 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6769 return BT->getKind() == BuiltinType::Bool;
6770 return false;
6771}
6772
6773inline bool Type::isUndeducedType() const {
6774 auto *DT = getContainedDeducedType();
6775 return DT && !DT->isDeduced();
6776}
6777
6778/// Determines whether this is a type for which one can define
6779/// an overloaded operator.
6780inline bool Type::isOverloadableType() const {
6781 return isDependentType() || isRecordType() || isEnumeralType();
6782}
6783
6784/// Determines whether this type can decay to a pointer type.
6785inline bool Type::canDecayToPointerType() const {
6786 return isFunctionType() || isArrayType();
6787}
6788
6789inline bool Type::hasPointerRepresentation() const {
6790 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
6791 isObjCObjectPointerType() || isNullPtrType());
6792}
6793
6794inline bool Type::hasObjCPointerRepresentation() const {
6795 return isObjCObjectPointerType();
6796}
6797
6798inline const Type *Type::getBaseElementTypeUnsafe() const {
6799 const Type *type = this;
6800 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
6801 type = arrayType->getElementType().getTypePtr();
6802 return type;
6803}
6804
6805inline const Type *Type::getPointeeOrArrayElementType() const {
6806 const Type *type = this;
6807 if (type->isAnyPointerType())
6808 return type->getPointeeType().getTypePtr();
6809 else if (type->isArrayType())
6810 return type->getBaseElementTypeUnsafe();
6811 return type;
6812}
6813
6814/// Insertion operator for diagnostics. This allows sending Qualifiers into a
6815/// diagnostic with <<.
6816inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6817 Qualifiers Q) {
6818 DB.AddTaggedVal(Q.getAsOpaqueValue(),
6819 DiagnosticsEngine::ArgumentKind::ak_qual);
6820 return DB;
6821}
6822
6823/// Insertion operator for partial diagnostics. This allows sending Qualifiers
6824/// into a diagnostic with <<.
6825inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6826 Qualifiers Q) {
6827 PD.AddTaggedVal(Q.getAsOpaqueValue(),
6828 DiagnosticsEngine::ArgumentKind::ak_qual);
6829 return PD;
6830}
6831
6832/// Insertion operator for diagnostics. This allows sending QualType's into a
6833/// diagnostic with <<.
6834inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6835 QualType T) {
6836 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6837 DiagnosticsEngine::ak_qualtype);
6838 return DB;
6839}
6840
6841/// Insertion operator for partial diagnostics. This allows sending QualType's
6842/// into a diagnostic with <<.
6843inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6844 QualType T) {
6845 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6846 DiagnosticsEngine::ak_qualtype);
6847 return PD;
6848}
6849
6850// Helper class template that is used by Type::getAs to ensure that one does
6851// not try to look through a qualified type to get to an array type.
6852template <typename T>
6853using TypeIsArrayType =
6854 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
6855 std::is_base_of<ArrayType, T>::value>;
6856
6857// Member-template getAs<specific type>'.
6858template <typename T> const T *Type::getAs() const {
6859 static_assert(!TypeIsArrayType<T>::value,
6860 "ArrayType cannot be used with getAs!");
6861
6862 // If this is directly a T type, return it.
6863 if (const auto *Ty = dyn_cast<T>(this))
6864 return Ty;
6865
6866 // If the canonical form of this type isn't the right kind, reject it.
6867 if (!isa<T>(CanonicalType))
6868 return nullptr;
6869
6870 // If this is a typedef for the type, strip the typedef off without
6871 // losing all typedef information.
6872 return cast<T>(getUnqualifiedDesugaredType());
6873}
6874
6875template <typename T> const T *Type::getAsAdjusted() const {
6876 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
6877
6878 // If this is directly a T type, return it.
6879 if (const auto *Ty = dyn_cast<T>(this))
6880 return Ty;
6881
6882 // If the canonical form of this type isn't the right kind, reject it.
6883 if (!isa<T>(CanonicalType))
6884 return nullptr;
6885
6886 // Strip off type adjustments that do not modify the underlying nature of the
6887 // type.
6888 const Type *Ty = this;
6889 while (Ty) {
6890 if (const auto *A = dyn_cast<AttributedType>(Ty))
6891 Ty = A->getModifiedType().getTypePtr();
6892 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
6893 Ty = E->desugar().getTypePtr();
6894 else if (const auto *P = dyn_cast<ParenType>(Ty))
6895 Ty = P->desugar().getTypePtr();
6896 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
6897 Ty = A->desugar().getTypePtr();
6898 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
6899 Ty = M->desugar().getTypePtr();
6900 else
6901 break;
6902 }
6903
6904 // Just because the canonical type is correct does not mean we can use cast<>,
6905 // since we may not have stripped off all the sugar down to the base type.
6906 return dyn_cast<T>(Ty);
6907}
6908
6909inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
6910 // If this is directly an array type, return it.
6911 if (const auto *arr = dyn_cast<ArrayType>(this))
6912 return arr;
6913
6914 // If the canonical form of this type isn't the right kind, reject it.
6915 if (!isa<ArrayType>(CanonicalType))
6916 return nullptr;
6917
6918 // If this is a typedef for the type, strip the typedef off without
6919 // losing all typedef information.
6920 return cast<ArrayType>(getUnqualifiedDesugaredType());
6921}
6922
6923template <typename T> const T *Type::castAs() const {
6924 static_assert(!TypeIsArrayType<T>::value,
6925 "ArrayType cannot be used with castAs!");
6926
6927 if (const auto *ty = dyn_cast<T>(this)) return ty;
6928 assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) :
__assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6928, __PRETTY_FUNCTION__))
;
6929 return cast<T>(getUnqualifiedDesugaredType());
6930}
6931
6932inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
6933 assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void>
(0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6933, __PRETTY_FUNCTION__))
;
6934 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
6935 return cast<ArrayType>(getUnqualifiedDesugaredType());
6936}
6937
6938DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
6939 QualType CanonicalPtr)
6940 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
6941#ifndef NDEBUG
6942 QualType Adjusted = getAdjustedType();
6943 (void)AttributedType::stripOuterNullability(Adjusted);
6944 assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void>
(0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6944, __PRETTY_FUNCTION__))
;
6945#endif
6946}
6947
6948QualType DecayedType::getPointeeType() const {
6949 QualType Decayed = getDecayedType();
6950 (void)AttributedType::stripOuterNullability(Decayed);
6951 return cast<PointerType>(Decayed)->getPointeeType();
6952}
6953
6954// Get the decimal string representation of a fixed point type, represented
6955// as a scaled integer.
6956// TODO: At some point, we should change the arguments to instead just accept an
6957// APFixedPoint instead of APSInt and scale.
6958void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
6959 unsigned Scale);
6960
6961} // namespace clang
6962
6963#endif // LLVM_CLANG_AST_TYPE_H

/build/llvm-toolchain-snapshot-10~svn373517/include/llvm/ADT/PointerUnion.h

1//===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the PointerUnion class, which is a discriminated union of
10// pointer types.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_POINTERUNION_H
15#define LLVM_ADT_POINTERUNION_H
16
17#include "llvm/ADT/DenseMapInfo.h"
18#include "llvm/ADT/PointerIntPair.h"
19#include "llvm/Support/PointerLikeTypeTraits.h"
20#include <cassert>
21#include <cstddef>
22#include <cstdint>
23
24namespace llvm {
25
26template <typename T> struct PointerUnionTypeSelectorReturn {
27 using Return = T;
28};
29
30/// Get a type based on whether two types are the same or not.
31///
32/// For:
33///
34/// \code
35/// using Ret = typename PointerUnionTypeSelector<T1, T2, EQ, NE>::Return;
36/// \endcode
37///
38/// Ret will be EQ type if T1 is same as T2 or NE type otherwise.
39template <typename T1, typename T2, typename RET_EQ, typename RET_NE>
40struct PointerUnionTypeSelector {
41 using Return = typename PointerUnionTypeSelectorReturn<RET_NE>::Return;
42};
43
44template <typename T, typename RET_EQ, typename RET_NE>
45struct PointerUnionTypeSelector<T, T, RET_EQ, RET_NE> {
46 using Return = typename PointerUnionTypeSelectorReturn<RET_EQ>::Return;
47};
48
49template <typename T1, typename T2, typename RET_EQ, typename RET_NE>
50struct PointerUnionTypeSelectorReturn<
51 PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>> {
52 using Return =
53 typename PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>::Return;
54};
55
56namespace pointer_union_detail {
57 /// Determine the number of bits required to store integers with values < n.
58 /// This is ceil(log2(n)).
59 constexpr int bitsRequired(unsigned n) {
60 return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0;
61 }
62
63 template <typename... Ts> constexpr int lowBitsAvailable() {
64 return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
65 }
66
67 /// Find the index of a type in a list of types. TypeIndex<T, Us...>::Index
68 /// is the index of T in Us, or sizeof...(Us) if T does not appear in the
69 /// list.
70 template <typename T, typename ...Us> struct TypeIndex;
71 template <typename T, typename ...Us> struct TypeIndex<T, T, Us...> {
72 static constexpr int Index = 0;
73 };
74 template <typename T, typename U, typename... Us>
75 struct TypeIndex<T, U, Us...> {
76 static constexpr int Index = 1 + TypeIndex<T, Us...>::Index;
77 };
78 template <typename T> struct TypeIndex<T> {
79 static constexpr int Index = 0;
80 };
81
82 /// Find the first type in a list of types.
83 template <typename T, typename...> struct GetFirstType {
84 using type = T;
85 };
86
87 /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
88 /// for the template arguments.
89 template <typename ...PTs> class PointerUnionUIntTraits {
90 public:
91 static inline void *getAsVoidPointer(void *P) { return P; }
92 static inline void *getFromVoidPointer(void *P) { return P; }
93 static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>();
94 };
95
96 /// Implement assigment in terms of construction.
97 template <typename Derived, typename T> struct AssignableFrom {
98 Derived &operator=(T t) {
99 return static_cast<Derived &>(*this) = Derived(t);
100 }
101 };
102
103 template <typename Derived, typename ValTy, int I, typename ...Types>
104 class PointerUnionMembers;
105
106 template <typename Derived, typename ValTy, int I>
107 class PointerUnionMembers<Derived, ValTy, I> {
108 protected:
109 ValTy Val;
110 PointerUnionMembers() = default;
111 PointerUnionMembers(ValTy Val) : Val(Val) {}
112
113 friend struct PointerLikeTypeTraits<Derived>;
114 };
115
116 template <typename Derived, typename ValTy, int I, typename Type,
117 typename ...Types>
118 class PointerUnionMembers<Derived, ValTy, I, Type, Types...>
119 : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> {
120 using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>;
121 public:
122 using Base::Base;
123 PointerUnionMembers() = default;
124 PointerUnionMembers(Type V)
125 : Base(ValTy(const_cast<void *>(
126 PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
127 I)) {}
128
129 using Base::operator=;
130 Derived &operator=(Type V) {
131 this->Val = ValTy(
132 const_cast<void *>(PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
133 I);
134 return static_cast<Derived &>(*this);
135 };
136 };
137}
138
139/// A discriminated union of two or more pointer types, with the discriminator
140/// in the low bit of the pointer.
141///
142/// This implementation is extremely efficient in space due to leveraging the
143/// low bits of the pointer, while exposing a natural and type-safe API.
144///
145/// Common use patterns would be something like this:
146/// PointerUnion<int*, float*> P;
147/// P = (int*)0;
148/// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0"
149/// X = P.get<int*>(); // ok.
150/// Y = P.get<float*>(); // runtime assertion failure.
151/// Z = P.get<double*>(); // compile time failure.
152/// P = (float*)0;
153/// Y = P.get<float*>(); // ok.
154/// X = P.get<int*>(); // runtime assertion failure.
155template <typename... PTs>
156class PointerUnion
157 : public pointer_union_detail::PointerUnionMembers<
158 PointerUnion<PTs...>,
159 PointerIntPair<
160 void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int,
161 pointer_union_detail::PointerUnionUIntTraits<PTs...>>,
162 0, PTs...> {
163 // The first type is special because we want to directly cast a pointer to a
164 // default-initialized union to a pointer to the first type. But we don't
165 // want PointerUnion to be a 'template <typename First, typename ...Rest>'
166 // because it's much more convenient to have a name for the whole pack. So
167 // split off the first type here.
168 using First = typename pointer_union_detail::GetFirstType<PTs...>::type;
169 using Base = typename PointerUnion::PointerUnionMembers;
170
171public:
172 PointerUnion() = default;
173
174 PointerUnion(std::nullptr_t) : PointerUnion() {}
175 using Base::Base;
176
177 /// Test if the pointer held in the union is null, regardless of
178 /// which type it is.
179 bool isNull() const { return !this->Val.getPointer(); }
10
Assuming the condition is false
11
Returning zero, which participates in a condition later
180
181 explicit operator bool() const { return !isNull(); }
182
183 /// Test if the Union currently holds the type matching T.
184 template <typename T> int is() const {
185 constexpr int Index = pointer_union_detail::TypeIndex<T, PTs...>::Index;
186 static_assert(Index < sizeof...(PTs),
187 "PointerUnion::is<T> given type not in the union");
188 return this->Val.getInt() == Index;
189 }
190
191 /// Returns the value of the specified pointer type.
192 ///
193 /// If the specified pointer type is incorrect, assert.
194 template <typename T> T get() const {
195 assert(is<T>() && "Invalid accessor called")((is<T>() && "Invalid accessor called") ? static_cast
<void> (0) : __assert_fail ("is<T>() && \"Invalid accessor called\""
, "/build/llvm-toolchain-snapshot-10~svn373517/include/llvm/ADT/PointerUnion.h"
, 195, __PRETTY_FUNCTION__))
;
196 return PointerLikeTypeTraits<T>::getFromVoidPointer(this->Val.getPointer());
197 }
198
199 /// Returns the current pointer if it is of the specified pointer type,
200 /// otherwises returns null.
201 template <typename T> T dyn_cast() const {
202 if (is<T>())
203 return get<T>();
204 return T();
205 }
206
207 /// If the union is set to the first pointer type get an address pointing to
208 /// it.
209 First const *getAddrOfPtr1() const {
210 return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
211 }
212
213 /// If the union is set to the first pointer type get an address pointing to
214 /// it.
215 First *getAddrOfPtr1() {
216 assert(is<First>() && "Val is not the first pointer")((is<First>() && "Val is not the first pointer"
) ? static_cast<void> (0) : __assert_fail ("is<First>() && \"Val is not the first pointer\""
, "/build/llvm-toolchain-snapshot-10~svn373517/include/llvm/ADT/PointerUnion.h"
, 216, __PRETTY_FUNCTION__))
;
217 assert(((PointerLikeTypeTraits<First>::getAsVoidPointer(get<
First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-10~svn373517/include/llvm/ADT/PointerUnion.h"
, 220, __PRETTY_FUNCTION__))
218 PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) ==((PointerLikeTypeTraits<First>::getAsVoidPointer(get<
First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-10~svn373517/include/llvm/ADT/PointerUnion.h"
, 220, __PRETTY_FUNCTION__))
219 this->Val.getPointer() &&((PointerLikeTypeTraits<First>::getAsVoidPointer(get<
First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-10~svn373517/include/llvm/ADT/PointerUnion.h"
, 220, __PRETTY_FUNCTION__))
220 "Can't get the address because PointerLikeTypeTraits changes the ptr")((PointerLikeTypeTraits<First>::getAsVoidPointer(get<
First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-10~svn373517/include/llvm/ADT/PointerUnion.h"
, 220, __PRETTY_FUNCTION__))
;
221 return const_cast<First *>(
222 reinterpret_cast<const First *>(this->Val.getAddrOfPointer()));
223 }
224
225 /// Assignment from nullptr which just clears the union.
226 const PointerUnion &operator=(std::nullptr_t) {
227 this->Val.initWithPointer(nullptr);
228 return *this;
229 }
230
231 /// Assignment from elements of the union.
232 using Base::operator=;
233
234 void *getOpaqueValue() const { return this->Val.getOpaqueValue(); }
235 static inline PointerUnion getFromOpaqueValue(void *VP) {
236 PointerUnion V;
237 V.Val = decltype(V.Val)::getFromOpaqueValue(VP);
238 return V;
239 }
240};
241
242template <typename ...PTs>
243bool operator==(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
244 return lhs.getOpaqueValue() == rhs.getOpaqueValue();
245}
246
247template <typename ...PTs>
248bool operator!=(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
249 return lhs.getOpaqueValue() != rhs.getOpaqueValue();
250}
251
252template <typename ...PTs>
253bool operator<(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
254 return lhs.getOpaqueValue() < rhs.getOpaqueValue();
255}
256
257// Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
258// # low bits available = min(PT1bits,PT2bits)-1.
259template <typename ...PTs>
260struct PointerLikeTypeTraits<PointerUnion<PTs...>> {
261 static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
262 return P.getOpaqueValue();
263 }
264
265 static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
266 return PointerUnion<PTs...>::getFromOpaqueValue(P);
267 }
268
269 // The number of bits available are the min of the pointer types minus the
270 // bits needed for the discriminator.
271 static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype(
272 PointerUnion<PTs...>::Val)>::NumLowBitsAvailable;
273};
274
275/// A pointer union of three pointer types. See documentation for PointerUnion
276/// for usage.
277template <typename PT1, typename PT2, typename PT3>
278using PointerUnion3 = PointerUnion<PT1, PT2, PT3>;
279
280/// A pointer union of four pointer types. See documentation for PointerUnion
281/// for usage.
282template <typename PT1, typename PT2, typename PT3, typename PT4>
283using PointerUnion4 = PointerUnion<PT1, PT2, PT3, PT4>;
284
285// Teach DenseMap how to use PointerUnions as keys.
286template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
287 using Union = PointerUnion<PTs...>;
288 using FirstInfo =
289 DenseMapInfo<typename pointer_union_detail::GetFirstType<PTs...>::type>;
290
291 static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
292
293 static inline Union getTombstoneKey() {
294 return Union(FirstInfo::getTombstoneKey());
295 }
296
297 static unsigned getHashValue(const Union &UnionVal) {
298 intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
299 return DenseMapInfo<intptr_t>::getHashValue(key);
300 }
301
302 static bool isEqual(const Union &LHS, const Union &RHS) {
303 return LHS == RHS;
304 }
305};
306
307} // end namespace llvm
308
309#endif // LLVM_ADT_POINTERUNION_H